Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{BuildCache, Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Last completed candidate scan that started no tasks; absent otherwise.
137    #[serde(default)]
138    pub dispatch_wait: Option<DispatchWait>,
139    /// Effective startup capabilities of the question recovery loops.
140    #[serde(default)]
141    pub question_recovery: Option<crate::question_delivery::Recovery>,
142    /// Independent-worker control protocol supported by this scheduler.
143    #[serde(default)]
144    pub worker_protocol: Option<u32>,
145}
146
147impl Status {
148    /// A fresh, idle status for this process.
149    #[must_use]
150    pub fn new() -> Self {
151        let now = Timestamp::now();
152        Self {
153            schema: SCHEMA,
154            pid: std::process::id(),
155            started_at: now,
156            updated_at: now,
157            idle: true,
158            current: Vec::new(),
159            completed: 0,
160            polls: 0,
161            dispatch_wait: None,
162            question_recovery: None,
163            worker_protocol: Some(1),
164        }
165    }
166}
167
168impl Default for Status {
169    fn default() -> Self {
170        Self::new()
171    }
172}
173
174/// How the loop should behave.
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[serde(default)]
177pub struct Opts {
178    /// Repository used by tasks that name none.
179    pub repo: PathBuf,
180    /// Explicit `magi.toml`, instead of the discovered layer stack.
181    pub config: Option<PathBuf>,
182    /// Queue poll interval.
183    pub poll: Duration,
184    /// Attempts a task gets before it is held for a human.
185    pub max_attempts: usize,
186    /// Drain what is runnable now, then return, instead of waiting for more.
187    pub once: bool,
188    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
189    pub merge: Option<String>,
190    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
191    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
192    /// `None` resolves to [`crate::run::default_worktree_root`] - the
193    /// operator's real `~/wt/<repo>` - the same way a run with no
194    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
195    /// that does not own that directory (a test, an embedding that manages
196    /// worktrees itself) must set this, or every idle tick reclaims worktrees
197    /// out from under whoever actually does.
198    pub worktrees_root: Option<PathBuf>,
199}
200
201impl Default for Opts {
202    fn default() -> Self {
203        Self {
204            repo: PathBuf::from("."),
205            config: None,
206            poll: POLL,
207            max_attempts: 2,
208            once: false,
209            merge: None,
210            worktrees_root: None,
211        }
212    }
213}
214
215impl Opts {
216    fn absolute(&self) -> Result<Self> {
217        let mut opts = self.clone();
218        opts.repo = std::path::absolute(&opts.repo)?;
219        opts.config = opts
220            .config
221            .as_deref()
222            .map(std::path::absolute)
223            .transpose()?;
224        opts.worktrees_root = opts
225            .worktrees_root
226            .as_deref()
227            .map(std::path::absolute)
228            .transpose()?;
229        Ok(opts)
230    }
231}
232
233/// How many runs a plain `usize` from config may drive concurrently, floored
234/// at one. A `0` in a config file would otherwise stall the loop entirely -
235/// no runnable task could ever start - which is never what an operator who
236/// wrote `0` meant.
237fn max_concurrent(n: usize) -> usize {
238    n.max(1)
239}
240
241/// Where the status file lives.
242#[must_use]
243pub fn status_path() -> PathBuf {
244    crate::run::home().join("daemon.json")
245}
246
247/// Publish the status file for this process.
248pub fn write_status(status: &Status) -> Result<()> {
249    write_status_to(&status_path(), status)
250}
251
252/// Publish a status to an explicit path.
253///
254/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
255/// on every health poll and must never see a half-written one.
256pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
257    if let Some(parent) = path.parent() {
258        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
259    }
260    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
261    let tmp = path.with_extension("json.tmp");
262    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
263    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
264    Ok(())
265}
266
267/// Delete the status file. Called on the way out so a clean exit reads as
268/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
269pub fn clear_status() {
270    clear_status_at(&status_path());
271}
272
273/// Delete a status file at an explicit path, so the loop's teardown and
274/// [`clear_status`] cannot drift apart: the loop is handed the path it
275/// published to, and a test can watch a temp file disappear.
276fn clear_status_at(path: &Path) {
277    let _ = std::fs::remove_file(path);
278}
279
280/// A cooperative stop, shared with whoever asked the loop to run.
281///
282/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
283/// Ctrl-C listener and the web UI keep others, and every clone points at the
284/// same flag. There is no channel because there is nothing to send — the only
285/// message is "stop", it is idempotent, and a flag cannot be missed by a
286/// receiver that was not listening yet.
287///
288/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
289/// detached task workers keep their own lifetimes and ownership after this
290/// handle's scheduler exits.
291#[derive(Debug, Clone, Default)]
292pub struct Stop {
293    /// Set once, never cleared: a stop is not something an operator takes back
294    /// half way through, and a clearable flag would let a start racing a stop
295    /// resurrect a loop that is already unwinding.
296    stopped: Arc<AtomicBool>,
297    /// Live task workers observed by the scheduler's latest dispatch snapshot.
298    busy: Arc<std::sync::atomic::AtomicUsize>,
299    /// Wakes the idle wait. Without this a stop would not be seen until the
300    /// poll interval elapsed, and an operator tapping stop on a phone would
301    /// watch a button do nothing for five seconds.
302    wake: Arc<Notify>,
303    /// Handed to the run in flight, so a stop can also mean "park at the next
304    /// node boundary" instead of "finish the whole competition first".
305    pause: crate::graph::Pause,
306}
307
308impl Stop {
309    /// A stop nobody has asked for yet.
310    #[must_use]
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Ask the loop to stop. Idempotent, and safe to call before the loop
316    /// starts: the flag is checked before the first poll.
317    pub fn stop(&self) {
318        self.stopped.store(true, Ordering::SeqCst);
319        // `notify_one` rather than `notify_waiters` because the loop may not be
320        // parked yet: this stores a permit, so a wait that registers a moment
321        // later returns at once instead of sleeping out the whole interval.
322        self.wake.notify_one();
323    }
324
325    /// Has a stop been asked for?
326    #[must_use]
327    pub fn stopped(&self) -> bool {
328        self.stopped.load(Ordering::SeqCst)
329    }
330
331    /// Whether a requested scheduler retirement still has an active snapshot.
332    /// Workers continue independently after the scheduler has retired.
333    #[must_use]
334    pub fn finishing(&self) -> bool {
335        self.stopped() && self.busy_now()
336    }
337
338    /// Ask the loop to stop *and* the run in flight to park at its next node
339    /// boundary.
340    ///
341    /// Unlike plain stop, explicit park asks workers to checkpoint at their
342    /// existing safe boundaries. Binary replacement never needs a park.
343    pub fn park(&self, cause: crate::run::ParkCause) {
344        self.pause.park_for(cause);
345        self.stop();
346    }
347
348    /// Has a park been asked for?
349    #[must_use]
350    pub fn parking(&self) -> bool {
351        self.pause.parked()
352    }
353
354    /// The pause handle to give a runner.
355    #[must_use]
356    pub fn pause(&self) -> crate::graph::Pause {
357        self.pause.clone()
358    }
359
360    /// Whether the scheduler's latest snapshot contains active task workers.
361    #[must_use]
362    pub fn busy_now(&self) -> bool {
363        self.busy.load(Ordering::SeqCst) > 0
364    }
365
366    /// Wait out one poll interval, returning early once a stop is asked for.
367    async fn idle(&self, poll: Duration) {
368        tokio::select! {
369            () = tokio::time::sleep(poll) => {}
370            () = self.wake.notified() => {}
371        }
372    }
373}
374
375/// The daemon's published state, read permissively.
376///
377/// This mirrors [`Status`], but is a separate declaration on purpose: every
378/// field defaults, so a status file from an older or newer magi still yields
379/// a usable reading — one this build has never heard of — instead of a parse
380/// error that hides the daemon entirely.
381#[derive(Debug, Clone, Default, Deserialize)]
382#[serde(default)]
383pub struct Reading {
384    /// Format version the daemon claims.
385    pub schema: u32,
386    /// Daemon process id, for an operator who wants to stop it.
387    pub pid: Option<u32>,
388    /// When that process started.
389    pub started_at: Option<Timestamp>,
390    /// Last heartbeat. Absent means the file is unusable, hence not running.
391    pub updated_at: Option<Timestamp>,
392    /// True when the queue had nothing runnable at the last poll.
393    pub idle: bool,
394    /// What the daemon is working on. Empty means idle; more than one entry
395    /// means more than one run is in flight at once.
396    ///
397    /// `deserialize_with` rather than the plain derive: a daemon started
398    /// before this field became a list is still out there writing the old
399    /// shape — a single `{"task":...,"run":...}` object, or its absence —
400    /// on every heartbeat until it is restarted, and a live process reading
401    /// that file during the rollout must still see it as running rather than
402    /// as absent. A bare type change here would fail the whole struct's
403    /// deserialization on a type mismatch, defeating the permissiveness this
404    /// type exists for.
405    #[serde(deserialize_with = "de_current")]
406    pub current: Vec<Current>,
407    /// Tasks this daemon process has finished.
408    pub completed: u64,
409    /// Queue polls this daemon process has made.
410    pub polls: u64,
411    /// Last no-start scan, retaining unknown reason keys from newer writers.
412    pub dispatch_wait: Option<DispatchWait>,
413    /// Effective startup capabilities of the question recovery loops.
414    #[serde(default)]
415    pub question_recovery: Option<crate::question_delivery::Recovery>,
416    /// Independent-worker control protocol, absent on legacy embedded loops.
417    pub worker_protocol: Option<u32>,
418}
419
420/// Accept the old single-`Current`-or-absent shape as well as the current
421/// list, so a reader never has to know which build wrote the file.
422fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
423where
424    D: serde::Deserializer<'de>,
425{
426    #[derive(Deserialize)]
427    #[serde(untagged)]
428    enum Shape {
429        Many(Vec<Current>),
430        One(Current),
431    }
432    Ok(
433        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
434            Shape::Many(v) => v,
435            Shape::One(c) => vec![c],
436        }),
437    )
438}
439
440impl Reading {
441    /// Seconds since the last heartbeat, or `None` when there has never been
442    /// one.
443    #[must_use]
444    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
445        self.updated_at
446            .map(|at| (now.as_second() - at.as_second()).max(0))
447    }
448
449    /// Whether the loop counts as running: a heartbeat no older than
450    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
451    /// progress hours after the daemon that owned it was killed.
452    #[must_use]
453    pub fn running(&self, now: Timestamp) -> bool {
454        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
455    }
456}
457
458/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
459/// usable there.
460///
461/// Missing, half-written and unparseable all collapse to `None`, because the
462/// only question a reader asks is whether a daemon is alive, and a file it
463/// cannot read is not evidence that one is.
464#[must_use]
465pub fn read_status(home: &Path) -> Option<Reading> {
466    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
467    serde_json::from_str(&body).ok()
468}
469
470/// Read-only evidence of runs owned by a live daemon or independent worker.
471///
472/// CLI, sandboxed conversation controls and Web cleanup share this observation.
473/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
474/// Starting reservations and unknown worker state remain protected; observing
475/// them never creates, reconciles or archives files in the worker store.
476/// Callers interested in one identity use [`is_working_on`] or
477/// [`is_working_on_task`].
478#[must_use]
479pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
480    let mut current = read_status(home)
481        .filter(|reading| reading.running(now))
482        .map(|reading| reading.current)
483        .unwrap_or_default();
484    let workers = crate::worker::observe_active(home).and_then(|jobs| {
485        jobs.into_iter()
486            .filter(|job| job.kind == "task")
487            .map(|job| {
488                let request: TaskWorker = serde_json::from_value(job.payload)?;
489                let run = Queue::at(request.queue)
490                    .get(&request.task)
491                    .ok()
492                    .and_then(|task| task.execution_runs().last().cloned())
493                    .unwrap_or_default();
494                Ok(Current {
495                    worker: Some(job.id),
496                    task: request.task,
497                    run,
498                })
499            })
500            .collect::<Result<Vec<_>>>()
501    });
502    match workers {
503        Ok(workers) => {
504            for worker in workers {
505                if !current.iter().any(|claim| {
506                    claim.task == worker.task
507                        && claim.run == worker.run
508                        && claim.worker == worker.worker
509                }) {
510                    current.push(worker);
511                }
512            }
513        }
514        Err(error) => {
515            // This API gates destructive cleanup. Unknown worker ownership
516            // protects every known task/run instead of pretending it is idle.
517            tracing::error!("cannot determine active workers: {error:#}");
518            current.extend(
519                Queue::at(home.join("queue"))
520                    .list()
521                    .into_iter()
522                    .map(|task| Current {
523                        worker: None,
524                        task: task.id.clone(),
525                        run: task.execution_runs().last().cloned().unwrap_or_default(),
526                    }),
527            );
528            current.extend(
529                crate::run::list_ids_in(&home.join("runs"))
530                    .into_iter()
531                    .map(|run| Current {
532                        worker: None,
533                        task: String::new(),
534                        run,
535                    }),
536            );
537        }
538    }
539    current
540}
541
542/// Whether a live daemon is working on this run at this moment.
543#[must_use]
544pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
545    current_work(home, now).iter().any(|c| c.run == run)
546}
547
548/// Admission may ignore only this process's confirmed worker reservation.
549/// Keep anonymous/legacy daemon claims and every other worker, even for the
550/// same task. The run's execution lease and process identity are checked by
551/// the caller under the owner lock as well.
552pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
553    // A helper or test may inherit an identity from a different run store.
554    // That identity grants no exception here; retain all ownership evidence.
555    let same_home = std::env::var_os("MAGI_WORKER_HOME")
556        .is_some_and(|worker_home| Path::new(&worker_home) == home);
557    let caller = if same_home {
558        crate::worker::current_job(home)?
559    } else {
560        None
561    }
562    .filter(|job| {
563        job.kind == "task"
564            && job.status == crate::worker::Status::Running
565            && job.pid == Some(std::process::id())
566    });
567    Ok(other_claims_run(
568        &current_work(home, now),
569        run,
570        caller.as_ref().map(|job| job.id.as_str()),
571    ))
572}
573
574fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
575    claims
576        .iter()
577        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
578}
579
580/// Whether a live daemon is working on a run whose short id is this one.
581///
582/// For a worktree that has no run record to compare against at all -
583/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
584/// id is not available to hand to [`is_working_on`]. The short id is: a run's
585/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
586/// and it is exactly the gap between the daemon claiming a task and
587/// `RunState::new` saving the first `run.json` that this exists to protect -
588/// a run genuinely in flight but invisible to a scan of `runs/`.
589#[must_use]
590pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
591    current_work(home, now)
592        .iter()
593        .any(|c| crate::run::short_of(&c.run) == short)
594}
595
596/// Whether a live daemon is working on this task at this moment.
597#[must_use]
598pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
599    current_work(home, now).iter().any(|c| c.task == task)
600}
601
602/// Remove claim files whose owner is provably dead, or that have simply
603/// outlived `older_than`, and return the task ids swept.
604///
605/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
606/// destructor, and the orphaned `.lock` file would make its task permanently
607/// unclaimable — the backlog would stop for good at exactly the task that was
608/// in flight when the machine went down.
609///
610/// The pid recorded in the lock is the authority whenever it can be read at
611/// all; age is only a fallback for when it cannot be.
612///
613/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
614///   full stop — dead sweeps the lock immediately, regardless of age; alive
615///   protects it, regardless of age. This is what lets a lock be reclaimed in
616///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
617///   before this daemon even started, next to a `queued` task, no longer has
618///   to sit for six hours before anything notices its owner is gone.
619/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
620///   falls back to `older_than`, since there is nothing else to check.
621///
622/// Age must never override a *positive* liveness confirmation. `sweep`
623/// polls concurrently with independently running task workers. A worker may
624/// legitimately run longer than `older_than`; its live pid must still protect
625/// its claim. Age alone must never turn that claim into a second task attempt,
626/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
627/// to a second attempt — two `Runner`s writing the same `run.json` and the
628/// same worktree at once. `pid_alive` answering "alive" for anything it
629/// cannot determine (a live process, a pid this build cannot check, one
630/// under another account) is exactly what keeps that path from ever
631/// firing on a guess.
632///
633/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
634/// output unreadable must not be license to guess, and the risk of an
635/// unparseable lock outliving a genuinely dead owner is bounded by an order
636/// of magnitude above any plausible run rather than by a positive check.
637///
638/// Runs on every poll, not only at startup — a daemon up for days must keep
639/// noticing a lock some other, now-dead, daemon left behind just as readily
640/// as one it trips over on the way up.
641pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
642    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
643}
644
645/// [`sweep_stale_claims`] with its process-query boundary supplied by the
646/// caller. This keeps the lock policy testable where process listing is
647/// unavailable, while production still uses the platform query above.
648fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
649where
650    F: Fn(u32) -> bool,
651{
652    let this_process = std::process::id();
653    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
654        .into_iter()
655        .flatten()
656        .flatten()
657        .map(|e| e.path())
658        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
659        .filter(|p| {
660            match std::fs::read_to_string(p)
661                .ok()
662                .and_then(|body| body.trim().parse::<u32>().ok())
663            {
664                // This process wrote it and is asking the question right
665                // now, so it is definitionally still alive - settled without
666                // spawning a helper process at all.
667                Some(pid) if pid == this_process => false,
668                Some(pid) => !pid_alive(pid),
669                None => p
670                    .metadata()
671                    .and_then(|m| m.modified())
672                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
673                    .is_ok_and(|age| age >= older_than),
674            }
675        })
676        .filter(|p| std::fs::remove_file(p).is_ok())
677        .filter_map(|p| {
678            p.file_stem()
679                .and_then(|s| s.to_str())
680                .map(std::borrow::ToOwned::to_owned)
681        })
682        .collect();
683    swept.sort_unstable();
684    swept
685}
686
687/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
688/// no live daemon's heartbeat naming it? Deterministic — no model call, and
689/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
690/// shown.
691fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
692    task.status == TaskStatus::Running
693        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
694        && !is_working_on_task(home, &task.id, now)
695}
696
697/// Every task [`is_stalled`] right now — "止まったタスク" in
698/// `crate::conduct`'s vocabulary.
699fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
700    queue
701        .list()
702        .into_iter()
703        .filter(|t| is_stalled(t, home, now))
704        .collect()
705}
706
707/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
708/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
709/// `Failed`-and-so-also-runnable: a task that already attempted and lost
710/// belongs in [`finished_tasks`], where the question is a recovery, not a
711/// dependency.
712fn queued_tasks(queue: &Queue) -> Vec<Task> {
713    queue
714        .list()
715        .into_iter()
716        .filter(|t| t.status == TaskStatus::Queued)
717        .collect()
718}
719
720/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
721/// タスク" in `crate::conduct`'s vocabulary.
722fn finished_tasks(queue: &Queue) -> Vec<Task> {
723    queue
724        .list()
725        .into_iter()
726        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
727        .collect()
728}
729
730/// Deterministically resolve `Task::blocked_by`: a dependency task that
731/// reached `Done`, or a question that was answered, is removed — no model
732/// involved, on every poll. An answered question's content is copied onto
733/// the task ([`Task::record_answer`]) before its id is dropped, so it
734/// reaches the next `crate::conduct` prompt and the next run's instruction
735/// (see [`instruction_for`]) rather than only clearing the block.
736///
737/// A `blocked_by` id that names neither an existing task nor an existing
738/// question - `magi task rm` (or an operator by hand) deleted it while this
739/// task was still waiting - is caught before any of that: it can never
740/// become `Done` or `Answered`, so the ordinary loop below would otherwise
741/// leave the task `blocked` forever with nothing to notice. Such a task is
742/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
743/// which puts it in front of `crate::triage::run_once`'s own walk the next
744/// time it runs - see that module's doc for why the choice is "ask a human",
745/// never "assume the missing dependency was satisfied and unblock anyway".
746fn resolve_blockers(queue: &Queue, questions: &Questions) {
747    for listed in queue.list() {
748        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
749            continue;
750        }
751        let Ok(_claim) = queue.claim(&listed.id) else {
752            continue;
753        };
754        let Ok(mut task) = queue.get(&listed.id) else {
755            continue;
756        };
757        if task.status != TaskStatus::Blocked {
758            continue;
759        }
760        // A dependency deleted on purpose is released, not held - and before
761        // the missing check, so a pass that races the delete (or a claim that
762        // made `Queue::remove` skip this task) settles it quietly.
763        let deleted = queue.apply_deleted_blockers(&mut task, questions);
764        if !deleted.is_empty() {
765            record(queue, &mut task);
766            for id in &deleted {
767                queue.note_dependency_deleted(&task, id);
768            }
769            if task.status != TaskStatus::Blocked {
770                continue;
771            }
772        }
773        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
774        if !missing.is_empty() {
775            let language = language_of(&task, Path::new("."));
776            let mut cause = missing.clone();
777            cause.sort();
778            cause.dedup();
779            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
780            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
781                &task.blocked_by,
782                &missing,
783                &language,
784            )));
785            record(queue, &mut task);
786            continue;
787        }
788        // A conductor question nobody answered in time is retired by the
789        // waiter, and nothing else would ever move the task it blocks.
790        if let Some(q) = task.blocked_by.iter().find_map(|id| {
791            let crate::queue::Dependency::Question(full) =
792                crate::queue::dependency(queue, questions, id)
793            else {
794                return None;
795            };
796            questions.get_for_effects(&full).ok().filter(|q| {
797                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
798            })
799        }) {
800            let language = language_of(&task, Path::new("."));
801            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
802            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
803            record(queue, &mut task);
804            continue;
805        }
806        let mut changed = false;
807        for id in task.blocked_by.clone() {
808            let resolved = crate::queue::dependency(queue, questions, &id);
809            if let crate::queue::Dependency::Task(full) = &resolved {
810                if queue
811                    .get(full)
812                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
813                {
814                    task.unblock(&id);
815                    changed = true;
816                }
817                continue;
818            }
819            if let crate::queue::Dependency::Question(full) = resolved
820                && let Ok(q) = questions.get_for_effects(&full)
821                && q.status == ask::QuestionStatus::Answered
822            {
823                // The action sweep releases conductor blockers atomically
824                // with their selected operation. A fresh deputy lease must
825                // never leave an answered hold temporarily runnable.
826                if q.node == crate::conduct::NODE
827                    && q.chosen_action().is_some()
828                    && !task.action_applied(&q.id)
829                {
830                    continue;
831                }
832                let answer = match &q.answer {
833                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
834                    None => String::new(),
835                };
836                task.record_answer(q.summary.clone(), answer);
837                task.unblock(&id);
838                changed = true;
839            }
840        }
841        if changed {
842            record(queue, &mut task);
843        }
844    }
845}
846
847/// The `hold_reason` of a task whose conductor question went unanswered.
848fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
849    if crate::lang::is_japanese(language) {
850        format!(
851            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
852            q.short(),
853            q.summary
854        )
855    } else {
856        format!(
857            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
858            q.short(),
859            q.summary
860        )
861    }
862}
863
864/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
865/// for several unrelated reasons, and the waiter must not read them alike.
866#[derive(Debug, Clone, Copy, PartialEq, Eq)]
867pub(crate) enum ActionStanding {
868    /// The answer carries no action: the waiter delivers it as before.
869    NoAction,
870    /// The daemon will apply it (not applied, task idle, current attempt).
871    Pending,
872    /// Already applied (`Task::actions_applied`): the daemon has acted, so
873    /// delivering the word to the old seat would run it beside the new work.
874    Applied,
875    /// The question is about an earlier attempt than the task's latest.
876    Stale,
877    /// The task is running / blocked / done: the daemon defers for now.
878    Busy,
879}
880
881impl ActionStanding {
882    /// The daemon has acted or will act: the waiter must not deliver.
883    pub(crate) fn daemon_owns(self) -> bool {
884        matches!(self, Self::Pending | Self::Applied | Self::Stale)
885    }
886}
887
888/// Classify `q`'s chosen action against `task`. `Stale` is judged before
889/// `Busy`: a question about an earlier attempt must be stopped even while a
890/// newer competition is running.
891pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
892    if task.stale_question(q) {
893        ActionStanding::Stale
894    } else if q.chosen_action().is_none() {
895        ActionStanding::NoAction
896    } else if task.action_applied(&q.id) {
897        ActionStanding::Applied
898    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
899        ActionStanding::Stale
900    } else if matches!(
901        task.status,
902        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
903    ) {
904        ActionStanding::Busy
905    } else {
906        ActionStanding::Pending
907    }
908}
909
910/// What [`decide_action`] concluded about one answered question.
911#[derive(Debug, Clone, PartialEq, Eq)]
912enum ActionDecision {
913    /// Nothing to do now (no action, already applied, or the task is busy).
914    Skip,
915    /// Continue the named run instead of competing again.
916    Resume(String),
917    /// Requeue as a fresh competition.
918    Requeue,
919    /// Hold the task by explicit operator choice.
920    Hold,
921    /// Close the task as done.
922    Done,
923    /// The question is about an earlier attempt than the task's latest; it
924    /// is recorded as handled and changes nothing.
925    Stale,
926    /// The action cannot be carried out; hold the task and say why. Never
927    /// falls back to something else, because the operator chose this one.
928    Refuse(String),
929}
930
931/// Decide what the choice answered on `q` means for `task`. `load` reads a
932/// run's state, as with [`unfinished_run_with`]. `home` must name that same
933/// store for driver leases and question checkpoints.
934///
935/// `Resume` only fires on the task's *latest* run, and only while that run
936/// could actually make progress ([`RunStatus::resumable`], not released, review
937/// budget left); an answer naming anything else is refused rather than
938/// reinterpreted as a fresh competition.
939fn decide_action<F>(
940    home: &Path,
941    task: &Task,
942    q: &ask::Question,
943    p: &Phrases,
944    load: F,
945) -> ActionDecision
946where
947    F: FnOnce(&str) -> Result<RunState>,
948{
949    if task.stale_question(q) {
950        return ActionDecision::Stale;
951    }
952    let Some(action) = q.chosen_action() else {
953        return ActionDecision::Skip;
954    };
955    if task.action_applied(&q.id)
956        || matches!(
957            task.status,
958            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
959        )
960    {
961        return ActionDecision::Skip;
962    }
963    // A question about an earlier attempt must not act on a newer one. A
964    // conductor question is keyed by the task id, not a run, so it is exempt.
965    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
966        return ActionDecision::Stale;
967    }
968    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
969    let stopping = q.node == land::APPROVAL_NODE
970        && q.resolution()
971            .as_deref()
972            .is_some_and(crate::merge_decision::stops);
973    // An answer is the owner's decision as of when it was given: a manual hold
974    // placed before it (even after the question was asked) was seen and
975    // overruled by it, while a hold or release after it supersedes it.
976    let decision_at = q.answered_at.unwrap_or(q.asked_at);
977    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
978        return if repair || stopping {
979            ActionDecision::Refuse(format!(
980                "{} answer {} was superseded by a later operator decision; the task stays held. Inspect `magi show {}`; if this action is still wanted, explicitly release the existing owner with `magi task release {}`",
981                if repair { "repair" } else { "stop" },
982                q.id,
983                q.run,
984                task.id
985            ))
986        } else {
987            ActionDecision::Stale
988        };
989    }
990    match action {
991        a if a.maintenance() => ActionDecision::Skip,
992        ask::ChoiceAction::RecoverBase { .. }
993        | ask::ChoiceAction::ResumeRun { .. }
994        | ask::ChoiceAction::ReleaseTask { .. }
995        | ask::ChoiceAction::RerunChecks { .. }
996        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
997        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
998        ask::ChoiceAction::Hold => ActionDecision::Hold,
999        ask::ChoiceAction::Done => ActionDecision::Done,
1000        ask::ChoiceAction::Resume { run } => {
1001            if task.execution_runs().last() != Some(run) {
1002                return ActionDecision::Refuse((p.resume_not_latest)(
1003                    q.short(),
1004                    ask::short_id(run),
1005                ));
1006            }
1007            match load(run) {
1008                Ok(s) if stopping => {
1009                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1010                        || !s
1011                            .land_approval
1012                            .as_ref()
1013                            .is_some_and(|binding| binding.question == q.id)
1014                    {
1015                        ActionDecision::Stale
1016                    } else if s.liveness_under(home, false) == Liveness::Live {
1017                        ActionDecision::Skip
1018                    } else if s.status == RunStatus::Landing
1019                        && !s.released()
1020                        && s.retired_to.is_none()
1021                    {
1022                        ActionDecision::Resume(run.clone())
1023                    } else {
1024                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1025                    }
1026                }
1027                Ok(s)
1028                    if q.node == land::APPROVAL_NODE
1029                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1030                {
1031                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1032                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1033                    {
1034                        // A live/manual driver already consumed or superseded
1035                        // this answer. Do not hold its fresh approval wait.
1036                        ActionDecision::Stale
1037                    } else if s.liveness_under(home, false) == Liveness::Live {
1038                        ActionDecision::Skip
1039                    } else if s.status != RunStatus::Landing
1040                        || s.released()
1041                        || s.reviews.is_empty()
1042                        || !implementers_match(task, &s)
1043                        || !s
1044                            .land_approval
1045                            .as_ref()
1046                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1047                    {
1048                        ActionDecision::Refuse(format!(
1049                            "repair question {} no longer names a supported current approval on run {}; inspect `magi show {}` and restore the existing owner's approval before retrying; do not file another task",
1050                            q.id, run, run
1051                        ))
1052                    } else {
1053                        ActionDecision::Resume(run.clone())
1054                    }
1055                }
1056                Ok(s) if s.liveness_under(home, false) == Liveness::Live => {
1057                    ActionDecision::Refuse("run already has a live driver".into())
1058                }
1059                Ok(s) => match crate::handover::resume_refusal_under(&s, Some(home)) {
1060                    None => ActionDecision::Resume(run.clone()),
1061                    Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1062                        q.short(),
1063                        ask::short_id(run),
1064                        &reason.diagnostic(&s),
1065                    )),
1066                },
1067                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1068                    q.short(),
1069                    ask::short_id(run),
1070                    &format!("{e:#}"),
1071                )),
1072            }
1073        }
1074    }
1075}
1076
1077/// The fixed prose the daemon writes into [`Task::last_error`] and
1078/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1079/// `triage::Wording` and `land::Words`: only English and Japanese are
1080/// translated, anything else falls back to English.
1081///
1082/// Rendered when the reason is *generated*, so a reason keeps the language it
1083/// was written in if the setting changes later. The notification frame
1084/// (`Task <id> is held:`) is not here and stays English.
1085///
1086/// Deliberately **not** translated, because other code reads them back by
1087/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1088/// and `gate red`. IDs, node names, paths and external error text are embedded
1089/// as they are.
1090struct Phrases {
1091    /// `{}` = status label, then the detail.
1092    graph_stopped: fn(&str, &str) -> String,
1093    quorum_lost: &'static str,
1094    /// Followed by the seats' names.
1095    quota_took_out: &'static str,
1096    /// Followed by the status label.
1097    run_ended: &'static str,
1098    /// Followed by the question's short id.
1099    waiting_for_answer: &'static str,
1100    recovered_running: &'static str,
1101    no_run_to_recover: &'static str,
1102    could_not_start: &'static str,
1103    resume_not_latest: fn(&str, &str) -> String,
1104    resume_cannot_progress: fn(&str, &str, &str) -> String,
1105    resume_unreadable: fn(&str, &str, &str) -> String,
1106    /// A takeover refusal: the operator-facing text. English is the error's own
1107    /// `Display`; a translation keeps the machine detail apart in parentheses.
1108    handover_refused: fn(&crate::handover::Refused) -> String,
1109    /// Appended to a refused handover's hold reason (leading space included).
1110    handover_hint: &'static str,
1111    /// (seats that never answered, review rounds) for the review loop's
1112    /// "refusing to call it clean" stop.
1113    reviewers_never_answered: fn(usize, usize) -> String,
1114}
1115
1116const PHRASES_EN: Phrases = Phrases {
1117    graph_stopped: |status, detail| {
1118        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1119    },
1120    quorum_lost: "the judging panel lost its quorum",
1121    quota_took_out: "; quota took out ",
1122    run_ended: "run ended ",
1123    waiting_for_answer: " - waiting for operator answer to question ",
1124    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1125    no_run_to_recover: "task was `running` with no live daemon and no readable \
1126                        run to recover; held for a human to check what happened",
1127    could_not_start: "could not start the run: ",
1128    resume_not_latest: |q, run| {
1129        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1130    },
1131    resume_cannot_progress: |q, run, reason| {
1132        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1133    },
1134    resume_unreadable: |q, run, e| {
1135        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1136    },
1137    handover_refused: |r| r.to_string(),
1138    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1139    reviewers_never_answered: |missing, rounds| {
1140        format!(
1141            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1142             refusing to call it clean"
1143        )
1144    },
1145};
1146
1147const PHRASES_JA: Phrases = Phrases {
1148    graph_stopped: |status, detail| {
1149        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1150    },
1151    quorum_lost: "審査パネルが定足数を失いました",
1152    quota_took_out: "。クォータで脱落: ",
1153    run_ended: "run 終了: ",
1154    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1155    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1156    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1157                        何が起きたか人が確認するため保留にしました",
1158    could_not_start: "run を開始できませんでした: ",
1159    resume_not_latest: |q, run| {
1160        format!(
1161            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1162        )
1163    },
1164    resume_cannot_progress: |q, run, reason| {
1165        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1166    },
1167    resume_unreadable: |q, run, e| {
1168        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1169    },
1170    handover_refused: |r| {
1171        use crate::handover::Refused;
1172        match r {
1173            Refused::Foreign { branch, path, why } => format!(
1174                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1175                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1176                 から、やり直してください(詳細: {why})"
1177            ),
1178            Refused::Unsafe { branch, path, why } => format!(
1179                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1180                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1181                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1182            ),
1183            Refused::ReleaseFailed { branch, path, run } => format!(
1184                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1185                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1186                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1187            ),
1188        }
1189    },
1190    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1191    reviewers_never_answered: |missing, rounds| {
1192        format!(
1193            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1194             クリーンとは認めません"
1195        )
1196    },
1197};
1198
1199fn phrases(language: &str) -> &'static Phrases {
1200    if crate::lang::is_japanese(language) {
1201        &PHRASES_JA
1202    } else {
1203        &PHRASES_EN
1204    }
1205}
1206
1207/// The language of the repository a task belongs to, read best-effort for the
1208/// paths that have no run (and so no config of their own) to ask. An unreadable
1209/// config is English, not an error: a hold reason must still get written.
1210fn language_of(task: &Task, fallback: &Path) -> String {
1211    crate::lang::of_repo(&repo_for(task, fallback))
1212}
1213
1214/// The task an answered question speaks for: the one whose runs include the
1215/// question's run, or - for a conductor question, filed under the task's own
1216/// id - the task with that id.
1217pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1218    if q.node == crate::conduct::NODE {
1219        return tasks.iter().find(|t| t.id == q.run);
1220    }
1221    tasks.iter().find(|t| t.runs.contains(&q.run))
1222}
1223
1224/// Legacy conductor prose never becomes a maintenance command by inference.
1225/// Replace unsupported open labels under the question lock before dispatch.
1226fn repair_choice_offers(questions: &Questions) {
1227    let ownership = crate::task_chat::InquiryOwnership::default();
1228    for q in questions
1229        .list_for_effects_in(&ownership)
1230        .into_iter()
1231        .filter(|q| {
1232            q.status.open()
1233                && q.node == crate::conduct::NODE
1234                && q.choices
1235                    .iter()
1236                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1237        })
1238    {
1239        let _ = questions.update_in(&q.id, &ownership, |current| {
1240            if current.status.open() {
1241                crate::choice_effect::executable_conductor(current);
1242                if let Some(deputy) = &mut current.deputy {
1243                    deputy.brief = crate::deputy::brief(
1244                        &current.run,
1245                        &current.detail,
1246                        &current.choices,
1247                        &current.actions,
1248                    );
1249                }
1250            }
1251            Ok(())
1252        });
1253    }
1254}
1255
1256/// Apply answered typed choices. Only the daemon calls this in production;
1257/// deputies settle the question and never execute its actions.
1258pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1259    apply_maintenance_choices(queue, questions, home).await;
1260    apply_task_choice_actions(queue, questions, home);
1261}
1262
1263/// Apply bounded maintenance effects independently of question ownership: a
1264/// release watcher need not have a queue task, and a predecessor is another run.
1265async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1266    let ownership = crate::task_chat::InquiryOwnership::default();
1267    for q in questions.list_for_effects_in(&ownership) {
1268        // Read again under the same fence used by explicit settlement.
1269        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1270            continue;
1271        };
1272        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1273            continue;
1274        };
1275        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1276            continue;
1277        };
1278        // Receipt paths use question IDs, whose format is independent of run
1279        // IDs. Apply the question store's filename safety rule to both eras.
1280        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1281            continue;
1282        }
1283        if queue.list().iter().any(|task| {
1284            (task.id == q.run
1285                || task.runs.contains(&q.run)
1286                || q.routed_task.as_deref() == Some(&task.id))
1287                && task.stale_question(&q)
1288        }) {
1289            continue;
1290        }
1291        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1292            let tasks = queue.list();
1293            let owner = crate::task_chat::task_of(&q, &tasks);
1294            if let Some(owner) = owner
1295                && q.routed_task
1296                    .as_deref()
1297                    .is_none_or(|routed| routed == owner)
1298            {
1299                let result = crate::base_recovery_control::recover(
1300                    queue,
1301                    home,
1302                    crate::base_recovery_control::Request {
1303                        run: run.clone(),
1304                        head: stop.head.clone(),
1305                        actor: "decisions".into(),
1306                        request: q.id.clone(),
1307                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1308                        expected_stop: Some((stop.clone(), *episode)),
1309                    },
1310                )
1311                .await;
1312                if let Err(error) = result {
1313                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1314                    notices::raise_in(home, Notice::warn(
1315                        &format!("base-recovery:{}", q.id),
1316                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1317                    ).link(Link::Run { id: run.clone() }));
1318                }
1319            }
1320            continue;
1321        }
1322        let dir = home.join("choice-actions");
1323        if std::fs::create_dir_all(&dir).is_err() {
1324            continue;
1325        }
1326        let Ok(lock) = std::fs::OpenOptions::new()
1327            .create(true)
1328            .truncate(false)
1329            .write(true)
1330            .open(dir.join(format!("{}.lock", q.id)))
1331        else {
1332            continue;
1333        };
1334        if crate::pr_head::try_lock_file(&lock).is_err() {
1335            continue;
1336        }
1337        let fresh = !home
1338            .join("choice-actions")
1339            .join(format!("{}.json", q.id))
1340            .exists();
1341        let result = async {
1342            let receipt = dir.join(format!("{}.json", q.id));
1343            if receipt.exists() {
1344                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1345                anyhow::ensure!(
1346                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1347                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1348                );
1349                return Ok::<_, anyhow::Error>(());
1350            }
1351            // Never retry an uncertain external effect. The receipt is written
1352            // before calling gh, exactly like release_watch's rerun record.
1353            let record = |status: &str| -> anyhow::Result<()> {
1354                let tmp = receipt.with_extension("tmp");
1355                std::fs::write(
1356                    &tmp,
1357                    serde_json::to_vec(&serde_json::json!({
1358                        "action": action, "status": status,
1359                    }))?,
1360                )?;
1361                std::fs::rename(tmp, &receipt)?;
1362                Ok(())
1363            };
1364            let applied = async {
1365                match action {
1366                    ask::ChoiceAction::ResumeRun { run } => {
1367                        crate::resume::validate(home, run)?;
1368                        record("started")?;
1369                        let decided = q.answered_at.unwrap_or(q.asked_at);
1370                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1371                            crate::resume::validate_unqueued(home, run)?;
1372                            crate::resume::start(home, run.clone()).await?;
1373                        }
1374                    }
1375                    ask::ChoiceAction::ReleaseTask {
1376                        task,
1377                        held_at,
1378                        reason,
1379                    } => {
1380                        anyhow::ensure!(
1381                            queue.resolve_id(task)? == *task,
1382                            "task action requires an exact task ID"
1383                        );
1384                        let _claim = queue.claim(task)?;
1385                        let mut task = queue.get(task)?;
1386                        if task.action_applied(&q.id) {
1387                            return Ok(());
1388                        }
1389                        // Filing this conductor question temporarily wraps the
1390                        // original hold in a Blocked state. Restore only that
1391                        // exact blocker on the local copy before checking the
1392                        // hold binding; unrelated waits never authorize release.
1393                        if q.node == crate::conduct::NODE
1394                            && q.run == task.id
1395                            && task.status == TaskStatus::Blocked
1396                            && task.blocked_from == Some(TaskStatus::Held)
1397                            && task.blocked_by.as_slice() == [q.id.as_str()]
1398                        {
1399                            task.unblock(&q.id);
1400                        }
1401                        anyhow::ensure!(
1402                            task.status == TaskStatus::Held
1403                                && task.held_at == Some(*held_at)
1404                                && task.hold_reason.as_deref() == reason.as_deref()
1405                                && task
1406                                    .operator_decided_at
1407                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1408                            "task no longer has the hold this question names"
1409                        );
1410                        task.release_operator("choice", Some(&q.id));
1411                        task.mark_action_applied(&q.id);
1412                        queue.put(&mut task)?;
1413                    }
1414                    ask::ChoiceAction::AbandonRun { run } => {
1415                        record("started")?;
1416                        crate::driver::abandon_proven_dead(home, run)?;
1417                    }
1418                    ask::ChoiceAction::RerunChecks {
1419                        repo,
1420                        pr,
1421                        head,
1422                        runs,
1423                    } => {
1424                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1425                            .await?;
1426                    }
1427                    _ => unreachable!(),
1428                }
1429                Ok::<_, anyhow::Error>(())
1430            }
1431            .await;
1432            match applied {
1433                Ok(()) => record("applied"),
1434                Err(e) => {
1435                    record(&format!("refused or failed: {e:#}"))?;
1436                    Err(e)
1437                }
1438            }
1439        }
1440        .await;
1441        // Retire the originating blocker as well as the target operation.
1442        // A foreign resume leaves its issuer held instead of competing beside
1443        // the execution just started. Other successful maintenance lets the
1444        // original task retry its normal, guarded path.
1445        if home
1446            .join("choice-actions")
1447            .join(format!("{}.json", q.id))
1448            .exists()
1449            && let Some(listed) = task_of_question(&queue.list(), &q)
1450            && !listed.action_applied(&q.id)
1451            && let Ok(_claim) = queue.claim(&listed.id)
1452            && let Ok(mut origin) = queue.get(&listed.id)
1453        {
1454            if !origin.operator_held()
1455                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1456                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1457            {
1458                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1459                    origin.hold_machine(Some(format!(
1460                        "Maintenance choice {} settled; inspect its target before releasing this task",
1461                        q.id
1462                    )));
1463                } else {
1464                    origin.unblock(&q.id);
1465                }
1466            }
1467            origin.mark_action_applied(&q.id);
1468            let _ = queue.put(&mut origin);
1469        }
1470        if let Err(e) = result
1471            && fresh
1472        {
1473            notices::raise_in(
1474                home,
1475                Notice::warn(
1476                    &format!("action:{}", q.id),
1477                    format!("Choice action {} was not completed: {e:#}", q.id),
1478                )
1479                .link(if q.run_names_task() {
1480                    Link::Task { id: q.run.clone() }
1481                } else {
1482                    Link::Run { id: q.run.clone() }
1483                }),
1484            );
1485        }
1486    }
1487}
1488
1489/// Rerun the named failed workflow runs of a pull request, each at most once
1490/// per `request` (a question id, or a chat operation identity). The head,
1491/// lifecycle and failed state are re-read from the forge first; `started` is
1492/// called once those checks pass and before the first external call, and the
1493/// ledger entry is written before every `gh` call, so an uncertain result is
1494/// never repeated automatically.
1495pub(crate) async fn rerun_checks_once(
1496    home: &Path,
1497    request: &str,
1498    repo: &Path,
1499    pr: &str,
1500    head: &str,
1501    runs: &[String],
1502    started: impl FnOnce() -> anyhow::Result<()>,
1503) -> anyhow::Result<()> {
1504    use crate::release_watch::{GhForge, ReleaseForge};
1505    anyhow::ensure!(
1506        !runs.is_empty()
1507            && runs.len() <= 20
1508            && runs
1509                .iter()
1510                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1511            && !pr.starts_with('-'),
1512        "invalid rerun targets"
1513    );
1514    let snap = GhForge.snapshot(repo, pr).await?;
1515    anyhow::ensure!(
1516        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1517        "pull request head or lifecycle changed"
1518    );
1519    anyhow::ensure!(
1520        runs.iter().all(|r| snap
1521            .checks
1522            .iter()
1523            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1524        "named workflow is no longer failed on this pull request"
1525    );
1526    started()?;
1527    let dir = home.join("choice-actions");
1528    std::fs::create_dir_all(&dir)?;
1529    let rerun_lock = std::fs::OpenOptions::new()
1530        .create(true)
1531        .truncate(false)
1532        .write(true)
1533        .open(dir.join("reruns.lock"))?;
1534    crate::pr_head::try_lock_file(&rerun_lock)?;
1535    let ledger = dir.join("reruns.json");
1536    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1537        serde_json::from_slice(&std::fs::read(&ledger)?)?
1538    } else {
1539        Default::default()
1540    };
1541    for run in runs {
1542        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1543        if !recorded.insert(key) {
1544            continue;
1545        }
1546        let tmp = ledger.with_extension("tmp");
1547        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1548        std::fs::rename(tmp, &ledger)?;
1549        GhForge.rerun(repo, run).await?;
1550    }
1551    Ok(())
1552}
1553
1554/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1555///
1556/// Runs on every poll before the conductor looks at the queue. The task is
1557/// re-read under its claim, so a task somebody completed or held by hand in
1558/// the meantime is judged on what it is now. `Resume` releases the task and
1559/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1560/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1561/// ordinary `unfinished_run` logic resumes that same run.
1562pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1563    let tasks = queue.list();
1564    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1565    for q in questions.list_for_effects_in(&ownership) {
1566        // Read again under the same fence used by explicit settlement.
1567        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1568            continue;
1569        };
1570        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1571            continue;
1572        };
1573        // Dismissal is committed by the question writer, never a resume.
1574        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1575            continue;
1576        }
1577        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1578            continue;
1579        }
1580        let Some(listed) = task_of_question(&tasks, &q) else {
1581            if q.node == land::APPROVAL_NODE
1582                && q.resolution().as_deref().is_some_and(|choice| {
1583                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1584                })
1585            {
1586                notices::raise_in(
1587                    home,
1588                    Notice::warn(
1589                        &format!("repair-owner:{}", q.id),
1590                        format!(
1591                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1592                            q.run, q.run
1593                        ),
1594                    ).link(Link::Run { id: q.run.clone() }),
1595                );
1596            }
1597            continue;
1598        };
1599        if listed.action_applied(&q.id) {
1600            continue;
1601        }
1602        let Ok(_claim) = queue.claim(&listed.id) else {
1603            continue;
1604        };
1605        let Ok(mut task) = queue.get(&listed.id) else {
1606            continue;
1607        };
1608        // Work only on this local copy until the action can be committed.
1609        // In particular, a fresh lease below leaves the persisted task blocked.
1610        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1611            let blockers: Vec<_> = task
1612                .blocked_by
1613                .iter()
1614                .filter(|id| {
1615                    crate::queue::dependency(queue, questions, id)
1616                        == crate::queue::Dependency::Question(q.id.clone())
1617                })
1618                .cloned()
1619                .collect();
1620            if !blockers.is_empty() {
1621                for id in blockers {
1622                    task.unblock(&id);
1623                }
1624                let answer = match &q.answer {
1625                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1626                    None => String::new(),
1627                };
1628                task.record_answer(q.summary.clone(), answer);
1629            }
1630        }
1631        let language = language_of(&task, Path::new("."));
1632        let decision = decide_action(home, &task, &q, phrases(&language), |id| {
1633            RunState::load_under(id, home)
1634        });
1635        let ran = matches!(
1636            decision,
1637            ActionDecision::Resume(_)
1638                | ActionDecision::Requeue
1639                | ActionDecision::Hold
1640                | ActionDecision::Done
1641        );
1642        if ran && asker_may_still_read(questions, &q, home) {
1643            // The asking process or its seat can still take the word; act
1644            // once it has gone quiet. Bound on the remaining window: the
1645            // check is not atomic with the write below, so an asker that
1646            // takes the word in between (at most one poll, never more than
1647            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1648            // and `Task::actions_applied` under the claim keeps the action to
1649            // one application. The waiter does not deliver an answer that
1650            // carries an action (`waiter::decide_owned`), so it cannot race.
1651            continue;
1652        }
1653        let done = matches!(decision, ActionDecision::Done);
1654        // Resume owes an execution pass; only these task-local effects finish
1655        // in this write. Stale/refused actions never acquire an effect receipt.
1656        let completed = matches!(
1657            decision,
1658            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1659        );
1660        match decision {
1661            ActionDecision::Skip => continue,
1662            ActionDecision::Resume(run) => {
1663                task.release_operator("choice", Some(&q.id));
1664                task.resume_override = Some(crate::queue::OperatorResume {
1665                    question_id: q.id.clone(),
1666                    at: Timestamp::now(),
1667                    conductor_rehold: None,
1668                    forced: true,
1669                    pinned_run: Some(run),
1670                });
1671            }
1672            ActionDecision::Stale => {}
1673            ActionDecision::Requeue => {
1674                task.release_operator("choice-requeue", Some(&q.id));
1675                task.requeue();
1676            }
1677            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1678            ActionDecision::Done => task.succeed(),
1679            ActionDecision::Refuse(why) => {
1680                let _ =
1681                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1682                if task.operator_held() {
1683                    // A rejected answer does not release the operator's hold
1684                    // or reclassify it as recoverable by the conductor.
1685                    task.hold_reason = Some(match task.hold_reason.take() {
1686                        Some(reason) => format!("{reason}\n\n{why}"),
1687                        None => why,
1688                    });
1689                } else {
1690                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1691                    task.hold_machine(Some(why));
1692                }
1693                notices::raise(
1694                    Notice::warn(
1695                        &format!("action:{}", q.id),
1696                        "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
1697                    )
1698                    .link(Link::Task {
1699                        id: task.id.clone(),
1700                    }),
1701                );
1702            }
1703        }
1704        task.mark_action_applied(&q.id);
1705        if completed {
1706            task.decision_effects.insert(
1707                q.id.clone(),
1708                format!("decision: {}", q.resolution().expect("answered action")),
1709            );
1710        }
1711        // The applied id travels with the transition, so a failed save loses
1712        // neither and the answer is acted on at the next poll.
1713        record(queue, &mut task);
1714        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1715            supersede_prior_runs(&task, home);
1716        }
1717        // Delivery is only a note of who has read the answer; the task's own
1718        // mark above is the authority. Best effort.
1719        let _ = questions.update_in(&q.id, &ownership, |r| {
1720            r.answer_delivered = true;
1721            Ok(())
1722        });
1723    }
1724}
1725
1726/// Whether something may still read the answer to `q`: a fresh lease, or the
1727/// asking seat still listed as active in its run (its CLI can outlive the
1728/// `magi ask` that was killed).
1729fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1730    let now = Timestamp::now();
1731    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1732        return true;
1733    }
1734    q.node != crate::conduct::NODE
1735        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1736            s.seats_active()
1737                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1738        })
1739}
1740
1741/// Retire an unanswered conductor question after its task no longer refers to
1742/// it. Conductor questions use the task id in `Question::run`, so run-based
1743/// cleanup cannot observe a manual release or completion.
1744///
1745/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1746/// own question also carries a `run`, and a run id that happens to collide
1747/// with some task's id is not this loop's business — only a conductor
1748/// question actually uses the task id that way. One `Questions::list()` scan
1749/// is taken up front and matched against the in-memory task set, rather than
1750/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1751fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1752    let tasks = queue.list();
1753    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1754    let by_id: std::collections::BTreeMap<&str, &Task> =
1755        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1756    let referenced: Vec<&str> = tasks
1757        .iter()
1758        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1759        .collect();
1760
1761    for mut question in questions.list_for_effects_in(&ownership) {
1762        if !question.status.open()
1763            || question.node != crate::conduct::NODE
1764            || questions.held_reply_in(&question.id, &ownership)
1765        {
1766            continue;
1767        }
1768        // Keep questions a task still names, including when the reference
1769        // moved to a dependent task.
1770        // Preserve even ambiguous references: retiring a possibly referenced
1771        // question is unsafe until the operator disambiguates it.
1772        if referenced
1773            .iter()
1774            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1775        {
1776            continue;
1777        }
1778        let Some(task) = by_id.get(question.run.as_str()) else {
1779            continue;
1780        };
1781        question.abandon(format!(
1782            "task {} no longer waits for this answer",
1783            task.short()
1784        ));
1785        if let Err(e) = questions.put_in(&mut question, &ownership) {
1786            tracing::warn!(
1787                "could not retire question {} for task {}: {e:#}",
1788                question.short(),
1789                task.short()
1790            );
1791        }
1792    }
1793}
1794
1795/// What a finished run tells the queue about the task it came from.
1796///
1797/// A struct rather than a fourth and fifth boolean argument: the two flags
1798/// answer different questions about the same run, and a call site passing
1799/// `(…, true, false)` is one transposition away from refunding attempts
1800/// forever.
1801#[derive(Debug, Clone, Copy)]
1802pub struct Verdict {
1803    /// Where the graph stopped.
1804    pub status: RunStatus,
1805    /// The run opened a pull request.
1806    pub left_pr: bool,
1807    /// At least one seat was lost to a rate limit.
1808    pub quota_hit: bool,
1809    /// The run parked at a node boundary because it was asked to.
1810    pub parked: bool,
1811    /// The run never produced a single candidate a judge could look at.
1812    ///
1813    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1814    /// still have another candidate worth judging, in which case the loss was
1815    /// not the reason nothing came of the run. This is `true` only when the
1816    /// implement wave ended with nothing viable at all.
1817    pub no_viable_candidates: bool,
1818}
1819
1820/// Record a finished run against the task it came from.
1821///
1822/// Kept pure and separate from the loop because this mapping *is* the retry
1823/// policy, and a policy that can only be exercised by spawning a graph is a
1824/// policy nobody checks. The table:
1825///
1826/// | run status                           | task becomes        | attempt spent |
1827/// |---------------------------------------|---------------------|---------------|
1828/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1829/// | `Merged`, `Ready`                      | `Done`               | yes          |
1830/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1831/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1832/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1833/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1834/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1835/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1836/// | `Blocked` with a PR                    | `Held`               | yes          |
1837/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1838/// | `VerifiedNoop`                          | `Held`               | yes          |
1839/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1840///
1841/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1842/// deliberately: every candidate agreeing there is nothing to write is not a
1843/// machine fact about a rate limit, it is an unverified claim about the
1844/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1845/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1846/// claim could be wrong (a misread instruction, a stale check), and closing
1847/// the task automatically on an implementer's say-so would be the exact
1848/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1849/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1850/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1851/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1852/// claim regardless of whether the one already-spent attempt is refunded, and
1853/// [`Task::release`] resets the count to zero anyway the moment a human looks
1854/// at the evidence and lets it run again.
1855///
1856/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1857/// twice, together. A quorum lost to rate limits is a property of the machine
1858/// and not of the task, so the attempt is refunded and a reset quota picks
1859/// the work up where it stopped — and that is just as true when every
1860/// implement seat lost the same race and `after_implement` bails with nothing
1861/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1862/// machine fact. The `no_viable_candidates` guard is what keeps that row
1863/// narrow: a `Failed` run that produced a real candidate which then lost for
1864/// some other reason still spends the attempt, exactly like the quorum lost
1865/// to judges that answered with the wrong shape is ordinary flakiness, and
1866/// refunding *that* takes the bound off the retry loop entirely: run e633
1867/// stalled with `quota: []` after two judges wrote unusable JSON, was
1868/// refunded, and the next attempt paid for a fresh hour-long implement wave
1869/// before it could fail the same way. `max_attempts` exists precisely so
1870/// that cannot repeat forever.
1871///
1872/// A non-terminal status means `execute` returned while the graph was still
1873/// mid-flight, which is a bug rather than a verdict; it is treated as a
1874/// failure so that a task cannot loop on it either.
1875///
1876/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1877/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1878pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1879    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN)
1880}
1881
1882/// [`settle`], with the daemon's own fixed prose in `p`'s language.
1883fn settle_in(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize, p: &Phrases) {
1884    // A parked run is the operator's own doing, and its work is intact on
1885    // disk. The task goes back in line with its attempt refunded so the next
1886    // loop resumes the same run - which `one_task` prefers over competing
1887    // again - and so that swapping the binary a few times cannot exhaust a
1888    // budget meant for agents that actually misbehaved.
1889    if verdict.parked {
1890        task.park(detail);
1891        return;
1892    }
1893    match verdict.status {
1894        RunStatus::Merged | RunStatus::Ready
1895            if task.pr_recovery.as_ref().is_some_and(|s| {
1896                s.disposition != Some(crate::pr_recovery::Disposition::Review)
1897            }) =>
1898        {
1899            task.hold_manual(Some("Public delivery is not confirmed. Inspect the selected PR and run, then use recover-pr --disposition land with the intended source and validation configuration.".into()));
1900        }
1901        RunStatus::Merged | RunStatus::Ready => task.succeed(),
1902        RunStatus::AlreadyInBase => task.already_landed(detail),
1903        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1904        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1905            task.stall(detail)
1906        }
1907        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1908        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1909        RunStatus::Blocked => task.fail(detail, max_attempts),
1910        RunStatus::VerifiedNoop => task.handed_off(detail),
1911        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
1912    }
1913}
1914
1915/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1916/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1917/// itself has actually finished *and* its own last attempt is provably why:
1918/// this loads that run and requires `Merged`/`Ready` before touching
1919/// anything earlier in `runs`, since `Task::succeed` can also be called
1920/// directly on a task whose last attempt never landed at all.
1921///
1922/// Called right after whatever call set `task.status` to
1923/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1924/// `reclaim`'s, but also every other place a task can be closed by hand
1925/// without the loop ever settling it itself: `magi task done`
1926/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1927/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1928/// GitHub merge, say, exactly the workflow this repository's own
1929/// "Landing a run's winner by hand" documents — is just as much "this task's
1930/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1931/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1932/// forever, which is the exact backlog this status exists to clear. `pub`
1933/// for those two out-of-module callers; everything else about this stays
1934/// internal bookkeeping.
1935///
1936/// A run something is still actually driving is left alone: a
1937/// task cannot be `Done` while one of its *own* attempts is still in flight,
1938/// so a live one at this point can only be an unrelated process — a manual
1939/// `--resume` of this old, now-moot run — and rewriting under it would just
1940/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1941/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1942/// pair `run_report`/`run_detail` use for the same question elsewhere:
1943/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1944/// --resume` invoked by hand outside it, which `liveness` also checks via
1945/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1946/// (already terminal in some other way, or itself mid-run) is left untouched
1947/// too.
1948///
1949/// Best-effort, like the rest of this module's bookkeeping: a load or save
1950/// failure here is a `tracing::warn`, not a failed settle, and the next time
1951/// this same task's completion is recorded — or a daemon restart replays
1952/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1953/// separate reconciliation pass; if that gap ever matters in practice, one
1954/// can be added then.
1955///
1956/// `home` is a parameter, not the process-global [`crate::run::home`], for
1957/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1958/// calls this with `ui.home`, which is `crate::run::home()` in a real
1959/// process but a fixture's own directory under test — falling through to
1960/// the global there would read and write through whichever home some other
1961/// test in the same binary happened to pin into that `OnceLock` first, not
1962/// the run this call actually means.
1963pub fn supersede_prior_runs(task: &Task, home: &Path) {
1964    let now = Timestamp::now();
1965    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1966    // right behind a `Merged`/`Ready` verdict) from one set directly by
1967    // `magi task done`/its web equivalent/the conductor on a task whose last
1968    // recorded attempt never actually landed - that requires reading the
1969    // run itself, which is exactly what this does before trusting anything
1970    // in `runs` is safe to relabel.
1971    let last_run_succeeded = task
1972        .runs
1973        .last()
1974        .and_then(|id| RunState::load_under(id, home).ok())
1975        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1976    for id in task.superseded_attempts(last_run_succeeded) {
1977        let mut state = match RunState::load_under(id, home) {
1978            Ok(s) => s,
1979            Err(e) => {
1980                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1981                continue;
1982            }
1983        };
1984        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1985            continue;
1986        }
1987        let daemon_claims = is_working_on(home, id, now);
1988        if state.liveness(daemon_claims) == Liveness::Live {
1989            continue;
1990        }
1991        state.status = RunStatus::Superseded;
1992        if let Err(e) = state.save_under(home) {
1993            tracing::warn!("could not mark run {id} superseded: {e:#}");
1994        }
1995    }
1996}
1997
1998/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1999/// finish the moment it was called, because one of its earlier attempts was
2000/// still live then - a `magi run --resume` invoked by hand on an old run,
2001/// most likely.
2002///
2003/// That skip is correct at the time (rewriting under a run something is
2004/// still actively saving would just be undone), but a task only ever
2005/// reaches `Done` once, so without this nothing would ever look at it
2006/// again: if that manual process later ends anywhere other than
2007/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2008/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2009/// backlog this status exists to clear. Called on the same idle-only
2010/// cadence as [`janitor`], next to it rather than folded into it: this
2011/// walks `queue` and `janitor` never otherwise needs one.
2012///
2013/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2014/// more than one attempt, every pass: each call is a handful of local file
2015/// reads bounded by that task's own attempt count, the same order of cost
2016/// [`clean::fold_due`] already pays scanning every run on disk on the same
2017/// cadence, and a task already fully resolved costs one failed liveness
2018/// check turned no-op the moment its lingering attempt is no longer live.
2019fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2020    for task in queue.list() {
2021        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2022            continue;
2023        }
2024        supersede_prior_runs(&task, home);
2025    }
2026}
2027
2028/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2029/// task ends up held.
2030///
2031/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2032/// dead daemon never got back to) share this, so the two cannot drift into
2033/// disagreeing about which held tasks get a diagnostic.
2034fn settle_and_diagnose(
2035    task: &mut Task,
2036    verdict: Verdict,
2037    detail: &str,
2038    max_attempts: usize,
2039    state: &RunState,
2040) {
2041    let p = phrases(&state.config.graph.language);
2042    // Shared by normal completion and crash recovery, under the task claim.
2043    // No new attempt can own the task until the old driver has exited.
2044    if let Some(d) = &state.merge_decision {
2045        use crate::merge_decision as md;
2046        if task
2047            .execution_runs()
2048            .last()
2049            .is_some_and(|id| id != &state.id)
2050        {
2051            return;
2052        }
2053        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2054            task.succeed();
2055        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2056            if state.liveness(false) != Liveness::Dead {
2057                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2058                return;
2059            }
2060            let replacement = md::Replacement {
2061                question: d.question.clone(),
2062                run: state.id.clone(),
2063                pr: d.target.pr.clone(),
2064                agent: agent.to_owned(),
2065                context: format!(
2066                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2067                    d.target.pr,
2068                    state.id,
2069                    serde_json::to_string(&state.reviews).unwrap_or_default()
2070                ),
2071            };
2072            task.requeue();
2073            task.pr_recovery = None;
2074            task.review_of = None;
2075            task.replacement = Some(replacement);
2076        } else {
2077            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2078                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2079            } else { format!("PR closure was not confirmed. Task held; inspect the existing run before starting replacement work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str())) }));
2080        }
2081        task.mark_action_applied(&d.question);
2082        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2083            task.decision_effects
2084                .insert(d.question.clone(), format!("decision: {}", d.choice));
2085        }
2086        if let Some(pass) = state.passes.last() {
2087            task.record_pass_at(
2088                &state.id,
2089                pass.index,
2090                Some(pass.started_at),
2091                task.attempts,
2092                None,
2093            );
2094        }
2095        return;
2096    }
2097    if let Some(replacement) = &task.replacement
2098        && !state.parked
2099        && state.resource_block.is_none()
2100        && (state.viable().is_empty()
2101            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2102    {
2103        task.hold_manual(Some(format!("Selected implementer `{}` was unavailable, failed or hit quota before producing a viable implementation. No other implementer was dispatched. Inspect the run, restore availability, then explicitly release this task.", replacement.agent)));
2104        return;
2105    }
2106    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2107        let mut agents: Vec<_> = state
2108            .quota
2109            .iter()
2110            .filter(|q| {
2111                q.cause == crate::agent::QuotaCause::Authentication
2112                    && state
2113                        .passes
2114                        .last()
2115                        .is_none_or(|pass| q.at >= pass.started_at)
2116            })
2117            .map(|q| q.agent.as_str())
2118            .collect();
2119        agents.sort_unstable();
2120        agents.dedup();
2121        if !agents.is_empty() {
2122            task.stall(detail);
2123            task.notice_cause("agent-authentication", None, None);
2124            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2125            return;
2126        }
2127    }
2128    let attempts_before = task.attempts;
2129    // A run that stopped because a shared resource stayed busy was never a
2130    // failure of the task or of an agent. Earlier nodes may have run; only
2131    // the blocked operation lacks a result. The attempt is
2132    // refunded and the task is held by the machine, under a reason `triage`
2133    // can re-check, so the same run resumes with the same agents once the
2134    // resource is free. A park request still wins (it is the operator's).
2135    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2136        let disk_checked_at = task.disk_checked_at;
2137        task.notice_cause(
2138            &format!("resource:{}:{}", block.kind, block.node),
2139            None,
2140            None,
2141        );
2142        task.last_error = Some(detail.to_owned());
2143        task.diagnostic = None;
2144        task.attempts = task.attempts.saturating_sub(1);
2145        if block.kind == "agent authentication" {
2146            task.hold_machine(Some(format!(
2147                "[authentication] {}; no attempt was spent",
2148                block.detail
2149            )));
2150        } else if block.kind == "agent usage limit" {
2151            // Usage limits keep the existing cooldown-and-resume policy.
2152            if let Some(agent) = &state.config.graph.selected_implementer {
2153                task.hold_machine(Some(format!("[agent usage limit] Selected implementer `{agent}` is unavailable. No other implementer was dispatched; resume after usage is available. No attempt was spent.")));
2154            } else {
2155                task.status = TaskStatus::Failed;
2156                task.last_error = Some(block.detail.clone());
2157            }
2158        } else if block.kind == "disk pressure" {
2159            task.hold_machine(Some(format!(
2160                "{}{}",
2161                crate::disk::RUNNING_PRESSURE,
2162                block.detail
2163            )));
2164        } else {
2165            task.hold_machine(Some(format!(
2166                "{}{}; no attempt was spent; resume to retry the affected operation",
2167                crate::cache::RESOURCE_HOLD,
2168                block.description()
2169            )));
2170        }
2171        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2172            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2173        {
2174            task.mark_disk_capacity();
2175            task.disk_checked_at = disk_checked_at;
2176        }
2177        if let Some(pass) = state.passes.last() {
2178            task.record_pass_at(
2179                &state.id,
2180                pass.index,
2181                Some(pass.started_at),
2182                attempts_before,
2183                None,
2184            );
2185        }
2186        return;
2187    }
2188    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2189        state.parked
2190            && state.status == RunStatus::Landing
2191            && state
2192                .pr_pushed_head
2193                .as_ref()
2194                .is_none_or(|h| h == &hold.head)
2195            && task.execution_runs().last() == Some(&state.id)
2196    }) {
2197        // Settlement and crash recovery share this idempotency key. A later
2198        // explicit resume is a new pass and may refund its own attempt once.
2199        let pass = state.passes.last().map_or(0, |p| p.index);
2200        if !task
2201            .passes
2202            .iter()
2203            .any(|p| p.run == state.id && p.pass_index == pass)
2204        {
2205            task.attempts = task.attempts.saturating_sub(1);
2206        }
2207        task.hold_machine(Some(format!(
2208            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2209            hold.question
2210        )));
2211        task.last_error = Some(detail.to_owned());
2212        task.diagnostic = None;
2213        task.record_pass_at(
2214            &state.id,
2215            pass,
2216            state.passes.last().map(|p| p.started_at),
2217            attempts_before,
2218            Some(crate::run::ParkCause::Question),
2219        );
2220        return;
2221    }
2222    let unresolved = task.hold_notice_cause.clone();
2223    if state.base_sync_blocked() {
2224        // No automatic retry may turn a retained sync stop into a new competition.
2225        task.hold_machine(Some(detail.to_owned()));
2226        task.last_error = Some(detail.to_owned());
2227    } else if !verdict.parked
2228        && task
2229            .pr_recovery
2230            .as_ref()
2231            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2232        && matches!(
2233            verdict.status,
2234            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2235        )
2236    {
2237        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2238            task.succeed();
2239        } else {
2240            task.hold_manual(Some("Selected PR delivery is incomplete: local review or publication is not a confirmed public merge. Inspect the run and PR; use recover-pr --disposition land with --source-head <reviewed-full-SHA> and the required verification configuration. No automatic new attempt will start.".into()));
2241        }
2242    } else if !verdict.parked
2243        && task.pr_recovery.is_some()
2244        && matches!(
2245            verdict.status,
2246            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2247        )
2248        && !verdict.quota_hit
2249    {
2250        task.hold_unrequested_retry(Some(format!("Selected recovery stopped: {detail}. Inspect the retained source and run; correct the cause before explicitly releasing or selecting again. No automatic replacement will start.")));
2251    } else {
2252        settle_in(task, verdict, detail, max_attempts, p);
2253    }
2254    if !verdict.parked
2255        && !verdict.quota_hit
2256        && matches!(
2257            verdict.status,
2258            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2259        )
2260    {
2261        task.recovery_failed(state);
2262    }
2263    if state.prep_failure.is_some() {
2264        // Minting a run whose candidates could not be prepared is not work
2265        // on a newly approved attempt. Keep the unresolved outcome anchor.
2266        task.hold_notice_cause = unresolved;
2267        task.startup_notice_cause("startup-candidates");
2268    }
2269    // Written here, where the refund (or not) is decided, so the history is a
2270    // fact and not a later guess from the run's status.
2271    if let Some(pass) = state.passes.last() {
2272        let parked = match &pass.end {
2273            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2274            _ => None,
2275        };
2276        task.record_pass_at(
2277            &state.id,
2278            pass.index,
2279            Some(pass.started_at),
2280            attempts_before,
2281            parked,
2282        );
2283    }
2284    if task.status == TaskStatus::Held {
2285        if state.base_sync_blocked() {
2286            task.base_sync_notice(state);
2287        } else if state.prep_failure.is_none() {
2288            task.notice_cause(
2289                label(verdict.status),
2290                Some(&state.id),
2291                state.passes.last().map(|p| p.index),
2292            );
2293        }
2294        task.diagnostic = diagnostic(state);
2295        note_open_question(task, &state.id, p);
2296    }
2297}
2298
2299/// If `task` is held with a `magi ask` question still open on `run`, name the
2300/// question in [`Task::hold_reason`] rather than leaving the hold reading
2301/// only [`describe`]'s run summary.
2302///
2303/// This is the shape task 20260928-191407-05fd left underspecified: an
2304/// implementer settled a verified no-op and filed a question for the
2305/// operator, and the hold that followed said nothing about the question
2306/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2307/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2308/// marker) and must keep seeing it unchanged.
2309///
2310/// Best-effort: an unreadable question store must not stop a run from
2311/// settling, so this is a no-op rather than a propagated error when
2312/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2313fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2314    let Some(home) = crate::run::try_home() else {
2315        return;
2316    };
2317    let open = Questions::at(home.join("questions")).open_for(run);
2318    let Some(q) = open.first() else {
2319        return;
2320    };
2321    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2322    decisions.sort_unstable();
2323    task.notice_cause(
2324        &format!("questions:{}", decisions.join(",")),
2325        Some(run),
2326        None,
2327    );
2328    let base = task.hold_reason.clone().unwrap_or_default();
2329    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2330}
2331
2332/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2333/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2334/// by some other means entirely, like a manual `magi run` resume that
2335/// finishes the graph outside the queue's bookkeeping.
2336///
2337/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2338/// `settle` is separate from `attempt`: a task recovered this way must land
2339/// exactly where a live daemon would have put it — the same policy table,
2340/// not a second one that quietly drifts from it — and that is only checkable
2341/// without spawning a real run.
2342fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2343    match last_run {
2344        Some(state) => {
2345            let verdict = Verdict {
2346                status: state.status,
2347                left_pr: state.pr.is_some(),
2348                quota_hit: state.quota.iter().any(|loss| {
2349                    state
2350                        .passes
2351                        .last()
2352                        .is_none_or(|pass| loss.at >= pass.started_at)
2353                }),
2354                parked: state.parked,
2355                no_viable_candidates: state.viable().is_empty(),
2356            };
2357            let detail = format!(
2358                "{}{}",
2359                phrases(&state.config.graph.language).recovered_running,
2360                describe(&state)
2361            );
2362            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2363        }
2364        None => {
2365            // No run, so no config of its own: `language` is the task's
2366            // repository's setting, read by the caller.
2367            let why = phrases(language).no_run_to_recover;
2368            task.last_error = Some(why.to_owned());
2369            // The phone shows `hold_reason`, so a task held by the machine
2370            // says why there too and not only in `last_error`.
2371            task.notice_cause("missing-run", None, None);
2372            task.hold_machine(Some(why.to_owned()));
2373        }
2374    }
2375}
2376
2377/// Find every task left at `running` that no live process is actually
2378/// driving, and settle each one against whatever its last run became.
2379///
2380/// # Why a claim is proof, not a guess
2381///
2382/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2383/// `running`, and the guard is held for the task's whole time in that status:
2384/// `attempt` does not return, and the loop does not move past the scope
2385/// holding the claim, until the run has settled. So a `running` task whose
2386/// lock is gone cannot have a live owner — this process or any other —
2387/// without needing a staleness threshold or a pid check the way
2388/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2389/// task that never got as far as `running` at all. Taking the claim here is
2390/// the whole test: it either fails, because something really does hold it
2391/// and the task is left alone, or it succeeds, which is the proof — and it is
2392/// kept for the rest of the decision so nothing else can start a competing
2393/// run while this one is being written.
2394///
2395/// Called on every poll, not only at startup, for the reason
2396/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2397/// keep noticing this, not only on the one morning it happened to restart.
2398fn reclaim_orphaned_running(
2399    queue: &Queue,
2400    max_attempts: usize,
2401    live_workers: &std::collections::BTreeSet<String>,
2402) -> Vec<String> {
2403    let mut reclaimed = Vec::new();
2404    for listed in queue.list() {
2405        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2406            continue;
2407        }
2408        let Ok(_claim) = queue.claim(&listed.id) else {
2409            continue;
2410        };
2411        // Re-read under the claim: a release or an edit landed by a human
2412        // between the listing above and the claim just taken must not be
2413        // clobbered by a decision based on the stale copy.
2414        let Ok(mut task) = queue.get(&listed.id) else {
2415            continue;
2416        };
2417        if task.status != TaskStatus::Running {
2418            continue;
2419        }
2420        let last_run = task
2421            .execution_runs()
2422            .last()
2423            .and_then(|id| RunState::load(id).ok());
2424        // `execute` normally abandons a run's own open questions the moment
2425        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2426        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2427        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2428        // with the question still `open`, because the process died before
2429        // reaching that call. `reclaim` itself stays pure on purpose (see its
2430        // own doc), so the same cleanup runs here instead, against the run
2431        // this reclaim is already reading. `settle_run` costs nothing when
2432        // `execute` already got there first.
2433        if let Some(state) = &last_run
2434            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2435        {
2436            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2437        }
2438        let language = if last_run.is_none() {
2439            language_of(&task, Path::new("."))
2440        } else {
2441            String::new()
2442        };
2443        reclaim(&mut task, last_run, max_attempts, &language);
2444        if task.status == TaskStatus::Done {
2445            supersede_prior_runs(&task, &crate::run::home());
2446        }
2447        record(queue, &mut task);
2448        reclaimed.push(task.id.clone());
2449    }
2450    reclaimed
2451}
2452
2453/// Find every run whose `run.json` is provably dead — every seat it still
2454/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2455/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2456/// not merely "no daemon claims it" — and fail it, clearing the leftover
2457/// active seats so the run stops reading as `implementing` (or whichever
2458/// node) forever.
2459///
2460/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2461/// `running`, using whatever `run.json` already says — but nothing in that
2462/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2463/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2464/// never got back to sits exactly where it was left: `active` full of seats
2465/// nobody will ever answer for, `status` stuck on whatever node was in
2466/// flight. `magi show` already tells an operator this in prose (`no live
2467/// daemon claims this run right now`); this is what makes that fact durable
2468/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2469/// stay stuck once nothing is driving it.
2470///
2471/// Runs on every poll, not only at startup, for the reason
2472/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2473/// daemon up for days must keep noticing a run some other, now-dead, daemon
2474/// left behind just as readily as one it trips over on the way up.
2475///
2476/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2477/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2478/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2479/// `runs` directory instead: `home` here is a parameter precisely so a test
2480/// can point it away from the operator's real history (see [`drive`]'s own
2481/// doc), and a scan that fell through to the global home anyway would walk
2482/// whichever directory some *other* process or test pinned into that
2483/// `OnceLock` first — mutating runs this call was never handed.
2484fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2485    reclaim_abandoned_runs_with(
2486        home,
2487        now,
2488        crate::proc::pid_status,
2489        crate::proc::process_started_at,
2490    )
2491}
2492
2493/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2494/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2495/// for the identical reason: this sweep's real damage (wiping a run's active
2496/// seats and failing it) has to be provable against an injected answer in a
2497/// test, not just the real process table.
2498fn reclaim_abandoned_runs_with<F, G>(
2499    home: &Path,
2500    now: Timestamp,
2501    query: F,
2502    identity: G,
2503) -> Vec<String>
2504where
2505    F: Fn(u32) -> Option<bool>,
2506    G: Fn(u32) -> Option<String>,
2507{
2508    let mut abandoned = Vec::new();
2509    for entry in std::fs::read_dir(home.join("runs"))
2510        .into_iter()
2511        .flatten()
2512        .flatten()
2513    {
2514        let id = entry.file_name().to_string_lossy().into_owned();
2515        if !crate::run::is_run_id(&id) {
2516            continue;
2517        }
2518        // Serialize the proof and save with claims and takeover: a new
2519        // execution must not be overwritten after the liveness observation.
2520        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2521            continue;
2522        };
2523        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2524        // that module's docs for why a run this cannot parse is left alone
2525        // rather than guessed at. A different schema number is not that: this
2526        // touches only `status` and `active`, never a field whose meaning a
2527        // schema bump changed, so an old record's values serve this exactly
2528        // as well as a current one's (see `clean::read_state`'s own doc for
2529        // the same reasoning applied to folding).
2530        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2531            continue;
2532        };
2533        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2534            continue;
2535        };
2536        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2537            continue;
2538        }
2539        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2540        // it", which is also the normal, healthy shape of a manual `magi
2541        // run` / `magi review` sharing this same home — this scan walks
2542        // every run on disk, not only ones this daemon itself started. Such
2543        // a run's active seats can legitimately sit past their own timeout
2544        // for a little while (the CLI finishing up, its result still being
2545        // collected) without the process driving it having died. `liveness`
2546        // is what actually tells the two apart, by corroborating
2547        // `driver_pid` against the process it names — see its own doc. Only
2548        // its strongest, provable answer licenses wiping this run's active
2549        // seats and failing it out from under whatever is still running it.
2550        let daemon_claims = is_working_on(home, &id, now);
2551        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2552            != crate::run::Liveness::Dead
2553        {
2554            continue;
2555        }
2556        state.abandon("daemon");
2557        if let Err(e) = state.save_under(home) {
2558            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2559            continue;
2560        }
2561        // This run never passes through `Runner::execute` again, so its end
2562        // is announced here.
2563        if let Some(notice) = notices::run_ended(&state) {
2564            notices::raise_in(home, notice);
2565        }
2566        // The seat that asked is gone for good now, exactly like any other
2567        // door `graph::Runner::settle_questions` closes the moment `status`
2568        // lands somewhere non-resumable - see that method's own doc. Nothing
2569        // else reaches this one before the next `janitor()` startup pass
2570        // (`clean::abandon_settled_questions`), and a daemon that stays up
2571        // for days must not leave an open question badging the operator
2572        // until it happens to restart.
2573        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2574            tracing::warn!("abandon questions for {id}: {e:#}");
2575        }
2576        abandoned.push(id);
2577    }
2578    abandoned
2579}
2580
2581#[derive(Debug, Clone, Serialize, Deserialize)]
2582struct TaskWorker {
2583    opts: Opts,
2584    queue: PathBuf,
2585    task: String,
2586    #[serde(default)]
2587    lane: PermitKind,
2588    #[serde(default)]
2589    standalone: bool,
2590}
2591
2592fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2593    Ok(crate::worker::active(home)?
2594        .into_iter()
2595        .filter(|job| job.kind == "task")
2596        .collect())
2597}
2598
2599fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2600    task_jobs(home)?
2601        .into_iter()
2602        .filter_map(
2603            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2604                Ok(request) if !request.standalone => Some(Ok(job)),
2605                Ok(_) => None,
2606                Err(error) => Some(Err(error.into())),
2607            },
2608        )
2609        .collect()
2610}
2611
2612/// Whether an independent scheduler can be controlled without its web parent.
2613#[must_use]
2614pub fn managed(home: &Path) -> bool {
2615    match crate::worker::active(home) {
2616        Err(error) => {
2617            tracing::error!("cannot determine scheduler ownership: {error:#}");
2618            true
2619        }
2620        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2621        Ok(_) => {
2622            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2623                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2624        }
2625    }
2626}
2627
2628/// Start a detached, singleton scheduler using this executable generation.
2629pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2630    anyhow::ensure!(
2631        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2632        "the scheduler is stopping; wait for retirement before starting it again"
2633    );
2634    crate::worker::spawn(
2635        home,
2636        "scheduler",
2637        "scheduler",
2638        serde_json::to_value(opts.absolute()?)?,
2639    )
2640    .await
2641}
2642
2643fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2644    home.join("worker-parks").join(format!("{}.json", job.id))
2645}
2646
2647fn request_task_park(
2648    home: &Path,
2649    job: &crate::worker::Job,
2650    cause: crate::run::ParkCause,
2651) -> Result<()> {
2652    let path = park_request_path(home, job);
2653    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2654    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2655    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2656}
2657
2658/// Stop dispatch immediately; only an explicit park reaches existing workers.
2659pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2660    if control == crate::worker::Control::Park {
2661        for job in owned_task_jobs(home)? {
2662            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2663        }
2664    }
2665    crate::worker::request(home, "scheduler", control)
2666}
2667
2668/// Replace the scheduler, leaving all active task and conversation jobs alone.
2669pub async fn restart_detached(home: &Path) -> Result<()> {
2670    let active = crate::worker::active(home)?;
2671    let prior = active.into_iter().find(|job| job.kind == "scheduler");
2672    if prior.is_none() && !managed(home) {
2673        return Ok(());
2674    }
2675    let opts: Opts = match prior {
2676        Some(job) => serde_json::from_value(job.payload)?,
2677        None => serde_json::from_slice(&std::fs::read(home.join("scheduler-options.json"))?)?,
2678    };
2679    request_control(home, crate::worker::Control::Stop)?;
2680    loop {
2681        let reserved = crate::worker::active(home)?
2682            .iter()
2683            .any(|job| job.kind == "scheduler");
2684        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2685            break;
2686        }
2687        tokio::time::sleep(Duration::from_millis(100)).await;
2688    }
2689    spawn_detached(home, &opts).await?;
2690    Ok(())
2691}
2692
2693/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2694pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2695    let opts: Opts = serde_json::from_value(payload)?;
2696    let _ = home;
2697    serve_until(opts, Stop::new()).await
2698}
2699
2700/// Execute and settle one task with the queue claim owned by this process.
2701pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2702    let request: TaskWorker = serde_json::from_value(payload)?;
2703    let queue = Queue::at(request.queue);
2704    let key = format!("task:{}", request.task);
2705    let job = task_jobs(home)?
2706        .into_iter()
2707        .find(|job| job.key == key)
2708        .context("task worker reservation is missing")?;
2709    let park_path = park_request_path(home, &job);
2710    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2711    // our durable reservation. Never execute before that ownership hand-off.
2712    let _claim = loop {
2713        match queue.claim(&request.task) {
2714            Ok(claim) => break claim,
2715            // Only contention (the claim file exists) is worth waiting out; an
2716            // I/O failure must end this worker instead of pinning its lane.
2717            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2718                return Err(e.context("claim the task for its worker"));
2719            }
2720            Err(_) => {
2721                sweep_stale_claims(&queue, STALE_CLAIM);
2722                tokio::time::sleep(Duration::from_millis(50)).await;
2723            }
2724        }
2725    };
2726    let mut task = queue.get(&request.task)?;
2727    if !task.status.runnable()
2728        || (!request.standalone
2729            && request.lane
2730                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
2731    {
2732        return Ok(());
2733    }
2734    let stop = Stop::new();
2735    let watcher = {
2736        let home = home.to_path_buf();
2737        let stop = stop.clone();
2738        let park_path = park_path.clone();
2739        tokio::spawn(async move {
2740            loop {
2741                if crate::worker::control(&home, &key).ok().flatten().is_some() {
2742                    let cause = std::fs::read(&park_path)
2743                        .ok()
2744                        .and_then(|body| serde_json::from_slice(&body).ok())
2745                        .unwrap_or(crate::run::ParkCause::Operator);
2746                    stop.park(cause);
2747                    return;
2748                }
2749                tokio::time::sleep(Duration::from_millis(200)).await;
2750            }
2751        })
2752    };
2753    let quota = if request.standalone {
2754        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
2755    } else {
2756        let status = Arc::new(Mutex::new(Status::new()));
2757        Box::pin(attempt(
2758            &request.opts,
2759            &queue,
2760            &status,
2761            &stop,
2762            crate::graph::Pause::new(),
2763            &mut task,
2764        ))
2765        .await
2766    };
2767    watcher.abort();
2768    let _ = std::fs::remove_file(park_path);
2769    persist_cooldown(home, &quota).await?;
2770    Ok(())
2771}
2772
2773/// Launch the standalone task worker with a claim-to-reservation handoff.
2774/// Returns only after the worker owns a durable execution reservation.
2775pub async fn spawn_claimed(
2776    home: &Path,
2777    opts: &Opts,
2778    queue: &Queue,
2779    task: &Task,
2780    claim: crate::queue::Claim,
2781) -> Result<crate::worker::Job> {
2782    let request = TaskWorker {
2783        opts: opts.absolute()?,
2784        queue: std::path::absolute(queue.root())?,
2785        task: task.id.clone(),
2786        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
2787        standalone: true,
2788    };
2789    let job = crate::worker::spawn(
2790        home,
2791        "task",
2792        &format!("task:{}", task.id),
2793        serde_json::to_value(request)?,
2794    )
2795    .await?;
2796    drop(claim);
2797    Ok(job)
2798}
2799
2800/// Transfer a standalone caller's claim only after the detached worker is live,
2801/// then follow that worker to its final (non-automatically-retrying) outcome.
2802pub async fn run_detached_claimed(
2803    opts: &Opts,
2804    queue: &Queue,
2805    task: &mut Task,
2806    claim: crate::queue::Claim,
2807) -> Result<()> {
2808    let home = crate::run::home();
2809    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
2810    loop {
2811        // Reconcile execution leases even without a scheduler. A dead worker
2812        // must become a reported failure, never an infinite persisted wait.
2813        crate::worker::active(&home)?;
2814        let current = crate::worker::get(&home, &job.id)?;
2815        if matches!(
2816            current.status,
2817            crate::worker::Status::Finished | crate::worker::Status::Failed
2818        ) {
2819            *task = queue.get(&task.id)?;
2820            anyhow::ensure!(
2821                current.status != crate::worker::Status::Failed,
2822                "task worker failed: {}",
2823                current.result.as_deref().unwrap_or("unknown failure")
2824            );
2825            return Ok(());
2826        }
2827        tokio::time::sleep(Duration::from_millis(200)).await;
2828    }
2829}
2830
2831async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
2832    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
2833        let _lease = loop {
2834            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
2835                break lease;
2836            }
2837            tokio::time::sleep(Duration::from_millis(10)).await;
2838        };
2839        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
2840            let path = home.join("task-quota-cooldown.json");
2841            let temporary = path.with_extension("json.tmp");
2842            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
2843            std::fs::rename(temporary, path)?;
2844        }
2845    }
2846    Ok(())
2847}
2848
2849fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
2850    match std::fs::read(home.join("task-quota-cooldown.json")) {
2851        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
2852        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
2853        Err(error) => Err(error.into()),
2854    }
2855}
2856
2857/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
2858///
2859/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
2860/// sets, so there is one loop body rather than two that drift apart the first
2861/// time the retry policy changes on only one of them.
2862pub async fn serve(opts: Opts) -> Result<()> {
2863    tracing::info!(
2864        "automatic update and restart requires magi web; standalone serve does not restart"
2865    );
2866    serve_until(opts, Stop::new()).await
2867}
2868
2869/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
2870///
2871/// A stop retires dispatch promptly, including while a worker launch is being
2872/// acknowledged. Already reserved workers own their attempts independently and
2873/// finish with their started executable. Explicit park additionally forwards
2874/// durable park requests; neither scheduler retirement nor update does so.
2875///
2876/// While the queue is empty the stop is honoured within one wakeup rather than
2877/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
2878/// caller that taps stop does not sit through the remainder of a sleep.
2879pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
2880    let opts = opts.absolute()?;
2881    let home = crate::run::home();
2882    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
2883        .context("another scheduler already owns this home")?;
2884    if let Some(reading) = read_status(&home)
2885        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
2886    {
2887        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
2888    }
2889    if !crate::worker::active(&home)?
2890        .iter()
2891        .any(|job| job.kind == "scheduler")
2892    {
2893        crate::worker::clear_control(&home, "scheduler")?;
2894    }
2895    std::fs::write(
2896        home.join("scheduler-options.json"),
2897        serde_json::to_vec(&opts)?,
2898    )?;
2899    let control = {
2900        let home = home.clone();
2901        let stop = stop.clone();
2902        tokio::spawn(async move {
2903            loop {
2904                match crate::worker::control(&home, "scheduler").ok().flatten() {
2905                    Some(crate::worker::Control::Park) => {
2906                        let _ = request_control(&home, crate::worker::Control::Park);
2907                        stop.park(crate::run::ParkCause::Operator);
2908                        break;
2909                    }
2910                    Some(crate::worker::Control::Stop) => {
2911                        stop.stop();
2912                        break;
2913                    }
2914                    None => {}
2915                }
2916                tokio::time::sleep(Duration::from_millis(100)).await;
2917            }
2918        })
2919    };
2920    let signal = {
2921        let stop = stop.clone();
2922        tokio::spawn(async move {
2923            if tokio::signal::ctrl_c().await.is_ok() {
2924                stop.stop();
2925                tracing::info!("scheduler shutdown requested; independent workers continue");
2926            }
2927        })
2928    };
2929
2930    let worktrees_root = opts
2931        .worktrees_root
2932        .clone()
2933        .unwrap_or_else(crate::run::default_worktree_root);
2934    let outcome = drive(
2935        &opts,
2936        &Queue::open(),
2937        &status_path(),
2938        &crate::run::home(),
2939        &worktrees_root,
2940        &stop,
2941    )
2942    .await;
2943
2944    signal.abort();
2945    control.abort();
2946    outcome
2947}
2948
2949/// The loop proper: setup, poll, teardown, with the queue and the status file
2950/// supplied rather than discovered.
2951///
2952/// All three of `home`, `worktrees_root` and the queue/status paths are
2953/// parameters rather than resolved here, for the same reason:
2954/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
2955/// so a unit test that pinned it would fight every other test in the binary,
2956/// and a loop that resolved its own worktree bay could only be exercised
2957/// against the operator's real `~/wt/<repo>` - publishing over a live
2958/// daemon's status file, claiming tasks out of a live backlog, and, since
2959/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
2960/// whatever the operator actually has on disk.
2961async fn drive(
2962    opts: &Opts,
2963    queue: &Queue,
2964    status_file: &Path,
2965    home: &Path,
2966    worktrees_root: &Path,
2967    stop: &Stop,
2968) -> Result<()> {
2969    // The status file is a *snapshot*, not a stream of events: a reader only
2970    // ever wants the latest values, and every tick rewrites the whole file
2971    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
2972    // while an mpsc channel would force the loop to re-send unchanged fields on
2973    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
2974    // for no gain. The lock is only ever held across a field assignment, never
2975    // across an await.
2976    let recovery_cfg = prepare(&opts.repo, opts).ok();
2977    let daemon_cfg = recovery_cfg
2978        .as_ref()
2979        .map(|c| c.daemon.clone())
2980        .unwrap_or_default();
2981    let reconciled = crate::driver::reconcile(home);
2982    if !reconciled.is_empty() {
2983        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
2984    }
2985    let mut initial_status = Status::new();
2986    let owned = owned_task_jobs(home)?;
2987    initial_status.current = current_work(home, Timestamp::now())
2988        .into_iter()
2989        .filter(|current| {
2990            owned
2991                .iter()
2992                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
2993        })
2994        .collect();
2995    initial_status.idle = initial_status.current.is_empty();
2996    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
2997        recovery_cfg.as_ref(),
2998        daemon_cfg.max_deputies,
2999    ));
3000    let status = Arc::new(Mutex::new(initial_status));
3001    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3002    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3003
3004    // Read once at startup, not per task: how many runs this loop drives at
3005    // once is a property of the machine running it, not of whichever
3006    // repository a given task happens to name - see
3007    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3008    // fact in the same sense the agent roster is.
3009    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3010
3011    tracing::info!(
3012        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3013        queue.root().display(),
3014        opts.poll.as_secs(),
3015        opts.max_attempts,
3016        concurrency,
3017        if daemon_cfg.pause_for_interrupts {
3018            ", interrupts enabled"
3019        } else {
3020            ""
3021        }
3022    );
3023
3024    let outcome = tokio::select! {
3025        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3026            max_concurrent: concurrency,
3027            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3028            recovery_cfg,
3029        }) => outcome,
3030        () = async {
3031            while !stop.stopped() {
3032                tokio::time::sleep(Duration::from_millis(25)).await;
3033            }
3034        } => {
3035            if stop.parking() {
3036                request_control(home, crate::worker::Control::Park)?;
3037            }
3038            Ok(())
3039        }
3040    };
3041
3042    stop.busy.store(0, Ordering::SeqCst);
3043    beat.abort();
3044    clear_status_at(status_file);
3045    outcome
3046}
3047
3048/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3049/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3050pub(crate) fn release_watch_settings_from_config(
3051    home: &Path,
3052    repo: &Path,
3053    cfg: &Config,
3054) -> (Vec<PathBuf>, u64) {
3055    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3056        .into_iter()
3057        .map(|r| r.path)
3058        .collect();
3059    // Repositories the daemon has worked in, wherever they live: a task may
3060    // name one outside `[repos] roots`, and its release PR must be watched too.
3061    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3062        .list()
3063        .into_iter()
3064        .map(|t| t.repo)
3065        .collect();
3066    let runs = home.join("runs");
3067    for id in crate::run::list_ids_in(&runs) {
3068        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3069            .ok()
3070            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3071            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3072        known.extend(repo);
3073    }
3074    for k in known {
3075        let k = k.canonicalize().unwrap_or(k);
3076        if k.join(".git").exists() && !paths.contains(&k) {
3077            paths.push(k);
3078        }
3079    }
3080    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3081    if !paths.contains(&own) {
3082        paths.push(own);
3083    }
3084    (paths, cfg.daemon.release_stall_minutes)
3085}
3086
3087/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3088const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3089
3090/// Refresh the status file on a fixed tick.
3091///
3092/// Separate from the loop because a run takes tens of minutes: a status file
3093/// written only between tasks would look stale for the whole of every run, and
3094/// a reader would report the daemon dead exactly while it was busiest.
3095async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3096    loop {
3097        tokio::time::sleep(HEARTBEAT).await;
3098        let snapshot = {
3099            let mut guard = lock(&status);
3100            guard.updated_at = Timestamp::now();
3101            guard.clone()
3102        };
3103        if let Err(e) = write_status_to(&path, &snapshot) {
3104            // A failed heartbeat must not take the daemon down: the loop is the
3105            // product, the status file is only the window onto it.
3106            tracing::warn!("could not refresh the daemon status file: {e:#}");
3107        }
3108    }
3109}
3110
3111/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3112/// if so, whether that wait is over.
3113#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3114enum LandResume {
3115    /// The task's last run is not parked on a land approval; schedule it
3116    /// like any other candidate.
3117    NotLanding,
3118    /// Parked in `land`, waiting on a question nobody has answered yet.
3119    /// Left alone: attempting it now would only re-observe the same pull
3120    /// request and park again, spending a `gh` call on a decision that has
3121    /// not changed since the last time this was checked.
3122    StillWaiting,
3123    /// Parked in `land`, and the question is settled - answered or
3124    /// abandoned. Resuming this is the one kind of candidate that must not
3125    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3126    Ready,
3127}
3128
3129/// Classify a runnable candidate by whether it is parked on a land-merge
3130/// approval. Read-only - no claim taken, nothing written - so it is cheap
3131/// enough to call on every candidate, every poll.
3132fn land_resume_state(task: &Task) -> LandResume {
3133    let Some(run_id) = task.execution_runs().last() else {
3134        return LandResume::NotLanding;
3135    };
3136    let Ok(state) = RunState::load(run_id) else {
3137        return LandResume::NotLanding;
3138    };
3139    if !state.parked {
3140        return LandResume::NotLanding;
3141    }
3142    if state.status == RunStatus::Landing
3143        && state.land_approval.as_ref().is_some_and(|binding| {
3144            ask::Questions::open()
3145                .get_for_effects(&binding.question)
3146                .is_ok_and(|q| {
3147                    q.run == state.id
3148                        && q.resolution()
3149                            .as_deref()
3150                            .is_some_and(crate::merge_decision::stops)
3151                })
3152        })
3153    {
3154        return LandResume::Ready;
3155    }
3156    if !implementers_match(task, &state) {
3157        return LandResume::NotLanding;
3158    }
3159    // Parked in `land` on the merge approval, or at `merge` on the owner's
3160    // word about a title/body the posting gate withheld. Told apart by the
3161    // run's own record, not by a status both can share.
3162    let node = if state.status == RunStatus::Landing {
3163        land::APPROVAL_NODE
3164    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3165        crate::github_text::ASK_NODE
3166    } else {
3167        return LandResume::NotLanding;
3168    };
3169    let store = ask::Questions::open();
3170    let waiting = store
3171        .list_for_effects()
3172        .into_iter()
3173        .filter(|q| &q.run == run_id && q.node == node)
3174        .max_by(|a, b| a.id.cmp(&b.id));
3175    let Some(mut q) = waiting else {
3176        return LandResume::Ready;
3177    };
3178    if !q.status.open() {
3179        // Repair spends agent resources and must obey concurrency and quota
3180        // waits; only a merge/hold decision may use the decision-only lane.
3181        if q.resolution().as_deref() == Some(land::REPAIR) {
3182            return if state.liveness(false) == Liveness::Live {
3183                LandResume::StillWaiting
3184            } else {
3185                LandResume::NotLanding
3186            };
3187        }
3188        return LandResume::Ready;
3189    }
3190    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3191    // nobody ever answered; land's approval bypasses that wait entirely (see
3192    // `land::approval_gate`), so the same deadline has to be enforced here
3193    // instead, or `graph.answer_timeout` silently stops meaning anything for
3194    // a land approval and a run can sit `StillWaiting` forever with nobody
3195    // told to look at it.
3196    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3197    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3198    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3199        q.abandon(format!(
3200            "no answer within {}s of asking",
3201            timeout.as_secs().max(1)
3202        ));
3203        // If this can't be persisted, do not treat the wait as settled on a
3204        // guess: fall through and try again next poll.
3205        if store.put(&mut q).is_ok() {
3206            return LandResume::Ready;
3207        }
3208    }
3209    LandResume::StillWaiting
3210}
3211
3212/// How often the loop rechecks for new work while something it already
3213/// started is still running, rather than sleeping out the whole
3214/// [`Opts::poll`] interval.
3215///
3216/// Short on purpose: this is what lets a land-merge approval that comes back
3217/// while another task is mid-competition be noticed and resumed within a
3218/// fraction of a second, not within the next multi-second poll.
3219const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3220
3221/// How often [`poll`] rechecks the shared build cache against its cap at a
3222/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3223/// waiting for the queue to run dry.
3224///
3225/// A queue that never empties means the `janitor` call at the bottom of this
3226/// loop's fully-idle branch can go unreached for as long as the backlog
3227/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3228/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3229/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3230/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3231/// backlog of short tasks does not pay for that walk on every poll.
3232const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3233
3234/// State of [`poll`]'s own interrupt-scheduling sequence - see
3235/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3236/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3237/// both kept free of `Task`'s non-identity fields on purpose: every decision
3238/// here turns only on task ids and which ones are in flight, so the "never
3239/// more than one run at once" and "exactly one resume" invariants can be
3240/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3241/// queue - which is exactly the coverage this feature's first two attempts
3242/// were missing.
3243///
3244/// Persisted after every transition, so scheduler replacement preserves the
3245/// interrupt's exclusive turn and the interrupted task's priority resume.
3246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3247enum Interrupt {
3248    /// No interrupt sequence in progress. Ordinary dispatch applies.
3249    Idle,
3250    /// `interrupt_task` is runnable and exactly one other run is in flight;
3251    /// `parked` names that one task's id. Dispatch is withheld from
3252    /// everyone, including `interrupt_task` itself, until it has left
3253    /// flight - only then is `interrupt_task` let through.
3254    ///
3255    /// `parked` is a `Vec` rather than a bare id for symmetry with
3256    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3257    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3258    /// when exactly one run is in flight, so it is guaranteed to hold
3259    /// exactly one entry in practice - see that branch's own doc for why
3260    /// more than one is deliberately never attempted.
3261    Parking {
3262        parked: Vec<String>,
3263        interrupt_task: String,
3264    },
3265    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3266    /// withheld from everyone until it leaves flight - merged, failed, held,
3267    /// it makes no difference - at which point the sequence moves to
3268    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3269    /// going straight to `Idle` would hand `parked` back to ordinary
3270    /// priority-order dispatch, where a higher-priority task filed in the
3271    /// meantime could start ahead of it.
3272    Running {
3273        parked: Vec<String>,
3274        interrupt_task: String,
3275    },
3276    /// `interrupt_task` left flight; `parked` still names the one run this
3277    /// sequence owes a resume. Dispatch is withheld from everyone except
3278    /// that task - see [`interrupt_gate`] - so the resume this feature
3279    /// promises is never raced by, or run alongside, an unrelated candidate.
3280    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3281    /// own doc on abandonment - the moment it is no longer runnable at all.
3282    Resuming { parked: Vec<String> },
3283}
3284
3285/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3286/// and `runnable` are read-only snapshots of this tick's reality, and the
3287/// only side effect the caller still owes the world is asking whichever
3288/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3289/// site.
3290///
3291/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3292/// accepted rather than a narrower type because that is what [`poll`] already
3293/// has on hand from [`runnable`], and building a second, smaller list on
3294/// every tick just to satisfy this signature would cost more than it proves.
3295///
3296/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3297/// back to a task they are waiting on no longer being [`runnable`] - held,
3298/// blocked, deleted, or finished by some other means entirely, all of which
3299/// an operator can do to a task sitting in the queue with no claim on it at
3300/// all, at any moment, interrupt sequence or not. Without this check the
3301/// sequence would wait forever for a dispatch that can never come, and
3302/// `interrupt_gate` would withhold every other task in the queue right along
3303/// with it - a single `magi task hold` on the wrong id turning into a
3304/// daemon that never dispatches anything again.
3305fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3306    match state {
3307        Interrupt::Idle => {
3308            // Not just "something to interrupt": exactly one thing. More
3309            // than one run in flight only happens above the default
3310            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3311            // one resume, never run alongside anything else" only because
3312            // it is only ever seeded with exactly one id - see
3313            // `Interrupt::Resuming`'s own doc on why releasing more than one
3314            // parked id back to ordinary dispatch cannot be made safe
3315            // against that same setting's own extra concurrency slots.
3316            // Waiting here for the herd to settle to one is the
3317            // simplification this feature's own constraints ask for rather
3318            // than a second concurrency model to reconcile with the first.
3319            if in_flight.len() != 1 {
3320                return Interrupt::Idle;
3321            }
3322            match runnable.iter().find(|t| t.interrupt) {
3323                Some(t) => Interrupt::Parking {
3324                    parked: in_flight.to_vec(),
3325                    interrupt_task: t.id.clone(),
3326                },
3327                None => Interrupt::Idle,
3328            }
3329        }
3330        Interrupt::Parking {
3331            parked,
3332            interrupt_task,
3333        } => {
3334            if in_flight.iter().any(|id| parked.contains(id)) {
3335                // Still waiting for what was in flight to actually stop.
3336                Interrupt::Parking {
3337                    parked,
3338                    interrupt_task,
3339                }
3340            } else if in_flight.contains(&interrupt_task) {
3341                Interrupt::Running {
3342                    parked,
3343                    interrupt_task,
3344                }
3345            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3346                // The parked run(s) are gone, but the interrupt task has not
3347                // been dispatched yet on this tick - `interrupt_gate` is
3348                // what lets it through next.
3349                Interrupt::Parking {
3350                    parked,
3351                    interrupt_task,
3352                }
3353            } else {
3354                // The interrupt task itself is no longer runnable - see this
3355                // function's own doc on abandonment. The parked run(s) still
3356                // get their guaranteed resume; there is simply no interrupt
3357                // to run ahead of them any longer.
3358                Interrupt::Resuming { parked }
3359            }
3360        }
3361        Interrupt::Running {
3362            parked,
3363            interrupt_task,
3364        } => {
3365            if in_flight.contains(&interrupt_task) {
3366                Interrupt::Running {
3367                    parked,
3368                    interrupt_task,
3369                }
3370            } else {
3371                // The interrupt task's own run reached a terminal status,
3372                // whichever one - this is the *only* trigger that moves the
3373                // sequence on, driven straight off the same in-flight
3374                // bookkeeping `poll` already reaps every tick, not a second,
3375                // independent poll of anything.
3376                Interrupt::Resuming { parked }
3377            }
3378        }
3379        Interrupt::Resuming { parked } => {
3380            if in_flight.iter().any(|id| parked.contains(id)) {
3381                // One of the parked runs has been dispatched - the resume
3382                // this sequence owed is fulfilled. Whatever else is left in
3383                // `parked` (ordinarily nothing, at the default concurrency
3384                // of one) rejoins ordinary priority-order dispatch, same as
3385                // any other runnable task.
3386                Interrupt::Idle
3387            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3388                Interrupt::Resuming { parked }
3389            } else {
3390                // Abandonment (see this function's own doc): nothing left in
3391                // `parked` is even runnable any longer.
3392                Interrupt::Idle
3393            }
3394        }
3395    }
3396}
3397
3398/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3399/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3400/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3401/// indistinguishable from any other runnable task - exactly the "off does
3402/// nothing" this feature promises.
3403fn advance_interrupt_tick(
3404    enabled: bool,
3405    state: Interrupt,
3406    in_flight: &[String],
3407    runnable: &[Task],
3408) -> Interrupt {
3409    if !enabled {
3410        return Interrupt::Idle;
3411    }
3412    advance_interrupt(state, in_flight, runnable)
3413}
3414
3415/// Which of this tick's runnable candidates the interrupt sequence actually
3416/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3417/// each half is assertable on its own: this is the half that keeps a
3418/// competition and an interrupt from ever running at the same moment.
3419fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3420    match state {
3421        Interrupt::Idle => candidates,
3422        Interrupt::Parking {
3423            parked,
3424            interrupt_task,
3425        } => {
3426            if in_flight.iter().any(|id| parked.contains(id)) {
3427                Vec::new()
3428            } else {
3429                candidates
3430                    .into_iter()
3431                    .filter(|t| &t.id == interrupt_task)
3432                    .collect()
3433            }
3434        }
3435        Interrupt::Running { .. } => Vec::new(),
3436        // At most one: even if `parked` names more than one id (more than
3437        // one run was in flight when the sequence began, only possible
3438        // above the default `max_concurrent_runs = 1`), only the first match
3439        // is offered. Capping this to a single candidate - not merely to
3440        // `parked`'s own ids - is what makes "exactly one resume, never two
3441        // dispatched together" true regardless of how many ordinary slots
3442        // happen to be free this tick.
3443        Interrupt::Resuming { parked } => candidates
3444            .into_iter()
3445            .find(|t| parked.contains(&t.id))
3446            .into_iter()
3447            .collect(),
3448    }
3449}
3450
3451/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3452/// bundled into one parameter so `poll`'s own signature stays readable -
3453/// see [`drive`]'s call site for where these are actually read.
3454struct DispatchLimits {
3455    /// How many *ordinary* candidates run at once. See
3456    /// [`crate::config::Daemon::max_concurrent_runs`].
3457    max_concurrent: usize,
3458    /// See [`crate::config::Daemon::pause_for_interrupts`].
3459    pause_for_interrupts: bool,
3460    recovery_cfg: Option<Config>,
3461}
3462
3463/// Which semaphore, if any, dispatching a candidate should draw its permit
3464/// from.
3465///
3466/// Pure and separate from [`poll`]'s loop body for the same reason
3467/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3468/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3469/// exactly the policy this feature adds, and a policy only exercisable by
3470/// running the whole loop is a policy nobody checks.
3471#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3472enum PermitKind {
3473    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3474    /// Checked first - a task can be both a land resume and marked
3475    /// [`Task::urgent`], and the resume's own "must not queue behind
3476    /// anything" guarantee takes precedence.
3477    None,
3478    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3479    /// (never in addition to trying) the ordinary pool. This is what lets
3480    /// an urgent task dispatch while every ordinary slot is already checked
3481    /// out, and what stops a second urgent task from opening a third run: it
3482    /// waits on this same one-slot semaphore rather than falling through to
3483    /// the ordinary one.
3484    Urgent,
3485    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3486    /// above.
3487    #[default]
3488    Ordinary,
3489}
3490
3491/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3492/// own boolean, already computed by the caller from [`land_resume_state`].
3493fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3494    if priority {
3495        PermitKind::None
3496    } else if urgent {
3497        PermitKind::Urgent
3498    } else {
3499        PermitKind::Ordinary
3500    }
3501}
3502
3503fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3504    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3505        (0usize, 0usize),
3506        |(ordinary, urgent), request| match request.lane {
3507            PermitKind::Ordinary => (ordinary + 1, urgent),
3508            PermitKind::Urgent => (ordinary, urgent + 1),
3509            PermitKind::None => (ordinary, urgent),
3510        },
3511    );
3512    (
3513        limit.saturating_sub(ordinary),
3514        1usize.saturating_sub(urgent),
3515    )
3516}
3517
3518/// Why a runnable candidate was not dispatched. This does not alter policy.
3519#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3520enum SkipReason {
3521    ClaimUnavailable,
3522    RereadFailed,
3523    NoLongerRunnable,
3524    WaitingOnLanding,
3525    CoolingDown,
3526    OrdinaryCapacity,
3527    UrgentCapacity,
3528    InterruptGate,
3529}
3530
3531impl SkipReason {
3532    fn key(self) -> &'static str {
3533        match self {
3534            Self::ClaimUnavailable => "claim_unavailable",
3535            Self::RereadFailed => "reread_failed",
3536            Self::NoLongerRunnable => "no_longer_runnable",
3537            Self::WaitingOnLanding => "waiting_on_landing",
3538            Self::CoolingDown => "cooling_down",
3539            Self::OrdinaryCapacity => "ordinary_capacity",
3540            Self::UrgentCapacity => "urgent_capacity",
3541            Self::InterruptGate => "interrupt_gate",
3542        }
3543    }
3544
3545    fn describe(self) -> &'static str {
3546        match self {
3547            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3548            Self::RereadFailed => "could not re-read it",
3549            Self::NoLongerRunnable => "no longer runnable",
3550            Self::WaitingOnLanding => "waiting on landing",
3551            Self::CoolingDown => "quota cooldown",
3552            Self::OrdinaryCapacity => "no free ordinary slot",
3553            Self::UrgentCapacity => "urgent slot busy",
3554            Self::InterruptGate => "withheld by the interrupt sequence",
3555        }
3556    }
3557}
3558
3559/// A reason count from a completed dispatch scan.
3560#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3561pub struct DispatchReasonCount {
3562    /// Stable string key, so readers can preserve future reasons.
3563    pub reason: String,
3564    /// Candidates skipped for this reason.
3565    pub count: usize,
3566}
3567
3568/// Observations from a completed scan, not a fresh queue estimate.
3569#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3570pub struct DispatchWait {
3571    /// Runnable candidates before the interrupt gate.
3572    pub runnable: usize,
3573    /// Counts in descending order, with stable reason order for ties.
3574    pub reasons: Vec<DispatchReasonCount>,
3575}
3576
3577type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3578
3579fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3580    if runnable == 0 {
3581        return None;
3582    }
3583    let mut counts = std::collections::BTreeMap::new();
3584    for (_, reason) in skips {
3585        *counts.entry(*reason).or_insert(0usize) += 1;
3586    }
3587    let mut counts: Vec<_> = counts.into_iter().collect();
3588    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3589    Some(DispatchWait {
3590        runnable,
3591        reasons: counts
3592            .into_iter()
3593            .map(|(reason, count)| DispatchReasonCount {
3594                reason: reason.key().to_owned(),
3595                count,
3596            })
3597            .collect(),
3598    })
3599}
3600
3601fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3602    before
3603        .iter()
3604        .filter(|id| !after.iter().any(|task| &task.id == *id))
3605        .map(|id| (id.clone(), SkipReason::InterruptGate))
3606        .collect()
3607}
3608
3609fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3610    if *previous == current {
3611        return false;
3612    }
3613    *previous = current;
3614    true
3615}
3616
3617struct DispatchClaim {
3618    task: Task,
3619    claim: crate::queue::Claim,
3620    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3621}
3622
3623/// Claim and re-read before choosing a lane: a queue listing may predate an
3624/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3625fn claim_dispatch(
3626    queue: &Queue,
3627    candidate: &Task,
3628    cooling_down: bool,
3629    ordinary: &Arc<tokio::sync::Semaphore>,
3630    urgent: &Arc<tokio::sync::Semaphore>,
3631) -> std::result::Result<DispatchClaim, SkipReason> {
3632    let claim = queue
3633        .claim(&candidate.id)
3634        .map_err(|_| SkipReason::ClaimUnavailable)?;
3635    let task = match queue.get(&candidate.id) {
3636        Ok(t) if t.status.runnable() => t,
3637        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3638        Err(e) => {
3639            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3640            return Err(SkipReason::RereadFailed);
3641        }
3642    };
3643    let resume = land_resume_state(&task);
3644    if resume == LandResume::StillWaiting {
3645        return Err(SkipReason::WaitingOnLanding);
3646    }
3647    let priority = resume == LandResume::Ready;
3648    if !priority && cooling_down {
3649        return Err(SkipReason::CoolingDown);
3650    }
3651    // Never borrow an ordinary slot when the single urgent slot is busy.
3652    // Keep scanning other candidates when either pool has no free slot.
3653    let permit = match permit_kind(priority, task.urgent) {
3654        PermitKind::None => None,
3655        PermitKind::Urgent => Some(
3656            Arc::clone(urgent)
3657                .try_acquire_owned()
3658                .map_err(|_| SkipReason::UrgentCapacity)?,
3659        ),
3660        PermitKind::Ordinary => Some(
3661            Arc::clone(ordinary)
3662                .try_acquire_owned()
3663                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3664        ),
3665    };
3666    // Persist the dispatch order under the claim, before config discovery or
3667    // coordination waits can reorder concurrent starts.
3668    let stamp = Timestamp::now();
3669    let mut task = task;
3670    task.dispatched_at = Some(stamp);
3671    if let Err(e) = queue.modify(&task.id, |t| {
3672        t.dispatched_at = Some(stamp);
3673        true
3674    }) {
3675        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3676    }
3677    Ok(DispatchClaim {
3678        task,
3679        claim,
3680        permit,
3681    })
3682}
3683
3684/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3685/// teardown and cannot skip the teardown on an early return.
3686///
3687/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3688/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3689/// land approval that has since been answered is dispatched outside that
3690/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3691/// the whole point of parking there is that it must not queue behind
3692/// whatever else the loop happens to be running, even at the default of one.
3693/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3694/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3695/// these exemptions is still subject to the interrupt gate below, urgent
3696/// included: a land-resume or urgent candidate is exactly as much "something
3697/// else running" as an ordinary one from the interrupt sequence's point of
3698/// view, and letting either slip through while a run is being parked, or
3699/// while the interrupt task itself has the floor, is precisely the second
3700/// run 75dd's own "at most one run, ever, at once" guarantee must never
3701/// allow - see [`Interrupt`]'s own doc.
3702#[derive(Serialize, Deserialize)]
3703struct ServiceWorker {
3704    opts: Opts,
3705    queue: PathBuf,
3706    worktrees_root: PathBuf,
3707    operation: String,
3708}
3709
3710fn load_conductor(home: &Path) -> Result<Conductor> {
3711    match std::fs::read(home.join("conductor-state.json")) {
3712        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3713        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3714        Err(error) => Err(error.into()),
3715    }
3716}
3717
3718fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3719    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3720        .into_iter()
3721        .map(|c| c.task)
3722        .collect();
3723    let stalled = stalled_tasks(queue, home, Timestamp::now());
3724    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
3725    let finished = finished_tasks(queue)
3726        .into_iter()
3727        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
3728        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
3729        .collect();
3730    let queued = queued_tasks(queue)
3731        .into_iter()
3732        .filter(|t| !live.contains(&t.id))
3733        .collect();
3734    (queued, stalled, finished)
3735}
3736
3737// Separate latest dispatch and worker receipts expose version handoff and skips
3738// without erasing the last completed scan or treating observations as authority.
3739fn retention_service_receipt(
3740    home: &Path,
3741    operation: &str,
3742    phase: &str,
3743    outcome: &str,
3744    detail: &str,
3745    cfg: Option<&Config>,
3746) {
3747    if !matches!(operation, "housekeeping" | "disk-pressure") {
3748        return;
3749    }
3750    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
3751        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
3752        "operation": operation, "outcome": outcome, "detail": detail,
3753        "auto_fold": cfg.map(|c| c.disk.auto_fold),
3754        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
3755    if let Err(error) = crate::fold_evidence::atomic_write(
3756        &home.join(format!("source-eviction-{operation}-{phase}.json")),
3757        &serde_json::to_vec(&receipt).expect("service receipt"),
3758    ) {
3759        tracing::warn!("retention service receipt failed: {error:#}");
3760    }
3761}
3762
3763async fn start_service(
3764    home: &Path,
3765    opts: &Opts,
3766    queue: &Queue,
3767    worktrees_root: &Path,
3768    operation: &str,
3769    cfg: Option<&Config>,
3770    busy: bool,
3771) -> Result<()> {
3772    // Fetch policy is live configuration, unlike question recovery capacity.
3773    // Reload before both cadence and eligibility, including disabled -> enabled.
3774    let fetch_cfg = if operation == "fetch" {
3775        match prepare(&opts.repo, opts) {
3776            Ok(cfg) => Some(cfg),
3777            Err(error) => {
3778                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
3779                return Ok(());
3780            }
3781        }
3782    } else {
3783        None
3784    };
3785    let cfg = fetch_cfg.as_ref().or(cfg);
3786    let ticks = home.join("service-ticks");
3787    std::fs::create_dir_all(&ticks)?;
3788    let receipt = ticks.join(format!("daemon-{operation}"));
3789    let last = std::fs::read(&receipt)
3790        .ok()
3791        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
3792    let interval = match operation {
3793        "disk-pressure" => 30,
3794        "chat-goals" => 60,
3795        "cache" => CACHE_CHECK_INTERVAL_SECS,
3796        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
3797        _ => opts.poll.as_secs().max(1),
3798    };
3799    let now = Timestamp::now();
3800    if !cache_check_due(last, now, interval) {
3801        retention_service_receipt(
3802            home,
3803            operation,
3804            "dispatch",
3805            "skipped",
3806            "cadence not due",
3807            cfg,
3808        );
3809        return Ok(());
3810    }
3811    let key = format!("service:daemon-{operation}");
3812    if crate::worker::active(home)?
3813        .iter()
3814        .any(|job| job.key == key)
3815    {
3816        retention_service_receipt(
3817            home,
3818            operation,
3819            "dispatch",
3820            "skipped",
3821            "service worker already active",
3822            cfg,
3823        );
3824        return Ok(());
3825    }
3826    let eligible = match operation {
3827        "conductor" => {
3828            let (queued, stalled, finished) = conductor_work(queue, home);
3829            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3830                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
3831        }
3832        "maintenance" => {
3833            queue.list().iter().any(|task| {
3834                crate::triage::disk_wait_eligible(task)
3835                    && task
3836                        .disk_checked_at
3837                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
3838            }) || Questions::at(home.join("questions"))
3839                .list_for_effects()
3840                .iter()
3841                .any(|q| {
3842                    q.chosen_action().is_some_and(|action| action.maintenance())
3843                        && !home
3844                            .join("choice-actions")
3845                            .join(format!("{}.json", q.id))
3846                            .exists()
3847                })
3848        }
3849        "housekeeping" => !busy && runnable(queue).is_empty(),
3850        "cache" => {
3851            !busy
3852                && !runnable(queue).is_empty()
3853                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
3854        }
3855        "disk-pressure" => busy,
3856        "fetch" => {
3857            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
3858        }
3859        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
3860            .list()
3861            .iter()
3862            .any(|talk| {
3863                talk.status.open()
3864                    && talk.pending.is_empty()
3865                    && talk.pending_attachments.is_empty()
3866                    && talk.goals.iter().any(|goal| goal.active())
3867            }),
3868        _ => false,
3869    };
3870    if !eligible {
3871        retention_service_receipt(
3872            home,
3873            operation,
3874            "dispatch",
3875            "skipped",
3876            if operation == "housekeeping" {
3877                "active work or runnable task queue"
3878            } else {
3879                "no active work; idle housekeeping owns scan"
3880            },
3881            cfg,
3882        );
3883        return Ok(());
3884    }
3885    retention_service_receipt(
3886        home,
3887        operation,
3888        "dispatch",
3889        "launching",
3890        "eligible and cadence due",
3891        cfg,
3892    );
3893    let request = ServiceWorker {
3894        opts: opts.absolute()?,
3895        queue: std::path::absolute(queue.root())?,
3896        worktrees_root: std::path::absolute(worktrees_root)?,
3897        operation: operation.to_owned(),
3898    };
3899    if let Err(error) =
3900        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
3901    {
3902        retention_service_receipt(
3903            home,
3904            operation,
3905            "dispatch",
3906            "error",
3907            &format!("worker launch: {error:#}"),
3908            cfg,
3909        );
3910        tracing::warn!(operation, "could not launch daemon service: {error:#}");
3911    }
3912    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
3913    Ok(())
3914}
3915
3916/// Finite maintenance jobs survive scheduler replacement without duplicating
3917/// agent calls or cancelling an operation between its effect and receipt.
3918pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3919    let request: ServiceWorker = serde_json::from_value(payload)?;
3920    let opts = &request.opts;
3921    let queue = Queue::at(request.queue);
3922    let questions = Questions::at(home.join("questions"));
3923    match request.operation.as_str() {
3924        "chat-goals" => {
3925            let talks = crate::talk::Talks::at(home.join("talks"));
3926            crate::chat_goal_runtime::sweep(&talks, false).await;
3927        }
3928        "maintenance" => {
3929            apply_maintenance_choices(&queue, &questions, home).await;
3930            triage::monitor_disk_waits(
3931                &queue,
3932                &questions,
3933                opts.config.as_deref(),
3934                Timestamp::now(),
3935            );
3936        }
3937        "conductor" => {
3938            let path = home.join("conductor-state.json");
3939            let mut conductor = load_conductor(home)?;
3940            let (queued, stalled, finished) = conductor_work(&queue, home);
3941            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
3942                && conductor.worth_a_look(&queue, &stalled, &finished)
3943            {
3944                let cfg = prepare(&opts.repo, opts)?;
3945                conductor
3946                    .maybe_run(
3947                        &cfg,
3948                        &opts.repo,
3949                        &queue,
3950                        &questions,
3951                        home,
3952                        &queued,
3953                        &stalled,
3954                        &finished,
3955                        opts.max_attempts,
3956                    )
3957                    .await;
3958                let temporary = path.with_extension("json.tmp");
3959                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
3960                std::fs::rename(temporary, path)?;
3961            }
3962        }
3963        "fetch" => {
3964            let cfg = prepare(&opts.repo, opts)?;
3965            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
3966                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
3967                tracing::debug!("fetch origins: {outcome:?}");
3968            }
3969        }
3970        "cache" => {
3971            if task_jobs(home)?.is_empty() {
3972                let mut checked = None;
3973                maybe_prune_cache_between_runs(
3974                    &opts.repo,
3975                    opts,
3976                    home,
3977                    &Stop::new(),
3978                    &mut checked,
3979                    Timestamp::now(),
3980                )
3981                .await;
3982            }
3983        }
3984        "disk-pressure" => {
3985            if let Ok(cfg) = prepare(&opts.repo, opts) {
3986                retention_service_receipt(
3987                    home,
3988                    "disk-pressure",
3989                    "worker",
3990                    "running",
3991                    "retention sweep",
3992                    Some(&cfg),
3993                );
3994                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
3995                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
3996                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
3997                }
3998                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
3999                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4000                }
4001                for current in current_work(home, Timestamp::now()) {
4002                    if let Ok(state) = RunState::load_under(&current.run, home)
4003                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4004                    {
4005                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4006                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4007                        }) {
4008                            request_task_park(
4009                                home,
4010                                &job,
4011                                crate::run::ParkCause::Interrupt {
4012                                    reason: reason.clone(),
4013                                },
4014                            )?;
4015                        }
4016                        notices::raise_in(
4017                            home,
4018                            Notice::warn(
4019                                "disk:pressure",
4020                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4021                            ),
4022                        );
4023                    }
4024                }
4025            } else {
4026                retention_service_receipt(
4027                    home,
4028                    "disk-pressure",
4029                    "worker",
4030                    "error",
4031                    "configuration could not be loaded",
4032                    None,
4033                );
4034            }
4035        }
4036        "housekeeping" => {
4037            if task_jobs(home)?.is_empty() {
4038                match prepare(&opts.repo, opts) {
4039                    Ok(cfg) => {
4040                        retention_service_receipt(
4041                            home,
4042                            "housekeeping",
4043                            "worker",
4044                            "running",
4045                            "retention sweep",
4046                            Some(&cfg),
4047                        );
4048                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4049                    }
4050                    Err(error) => retention_service_receipt(
4051                        home,
4052                        "housekeeping",
4053                        "worker",
4054                        "error",
4055                        &format!("configuration: {error:#}"),
4056                        None,
4057                    ),
4058                }
4059                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4060                resweep_superseded_attempts(&queue, home);
4061                triage_held(&queue, home, opts).await;
4062            } else {
4063                retention_service_receipt(
4064                    home,
4065                    "housekeeping",
4066                    "worker",
4067                    "skipped",
4068                    "task worker became active",
4069                    None,
4070                );
4071            }
4072        }
4073        operation => bail!("unknown daemon service {operation}"),
4074    }
4075    Ok(())
4076}
4077
4078/// Only a different request under the same key is a dispatch handoff race.
4079/// Our own unacknowledged reservation is a startup failure, not competing work:
4080/// stop dispatch without fencing it, so an already detached child may still run.
4081fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4082    let key = format!("task:{}", request.task);
4083    let payload = serde_json::to_value(request)?;
4084    if crate::worker::active(home)?
4085        .iter()
4086        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4087    {
4088        tracing::warn!(
4089            "task {} acquired a competing worker reservation: {error:#}",
4090            crate::run::short_of(&request.task)
4091        );
4092        return Ok(());
4093    }
4094    tracing::error!("task worker startup stopped dispatch: {error:#}");
4095    notices::raise_in(
4096        home,
4097        Notice::error(
4098            "loop:worker-startup",
4099            // Startup diagnostics may contain private child-process details;
4100            // keep them in the local error/log rather than the chat or notifier.
4101            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),
4102        ).link(Link::Task { id: request.task.clone() }),
4103    );
4104    Err(error).with_context(|| {
4105        format!(
4106            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4107            crate::run::short_of(&request.task)
4108        )
4109    })
4110}
4111
4112async fn poll(
4113    opts: &Opts,
4114    queue: &Queue,
4115    status: &Arc<Mutex<Status>>,
4116    home: &Path,
4117    worktrees_root: &Path,
4118    stop: &Stop,
4119    limits: DispatchLimits,
4120) -> Result<()> {
4121    let mut attempted = Vec::new();
4122    let mut settling_once_services = false;
4123    let interrupt_path = home.join("scheduler-interrupt.json");
4124    let mut interrupt = match std::fs::read(&interrupt_path) {
4125        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4126        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4127        Err(error) => return Err(error.into()),
4128    };
4129    let mut previous = std::collections::BTreeSet::<String>::new();
4130    let mut previous_skips = DispatchSkips::new();
4131    while !stop.stopped() {
4132        let jobs: Vec<_> = crate::worker::active(home)?
4133            .into_iter()
4134            .filter(|job| job.kind == "task")
4135            .collect();
4136        let requests: Vec<_> = jobs
4137            .iter()
4138            .map(|job| {
4139                serde_json::from_value::<TaskWorker>(job.payload.clone())
4140                    .with_context(|| format!("read live task worker {}", job.id))
4141            })
4142            .collect::<Result<_>>()?;
4143        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4144        let owned: std::collections::BTreeSet<_> = requests
4145            .iter()
4146            .filter(|r| !r.standalone)
4147            .map(|r| r.task.clone())
4148            .collect();
4149        let current: Vec<_> = requests
4150            .iter()
4151            .zip(&jobs)
4152            .filter(|(request, _)| !request.standalone)
4153            .map(|(request, job)| Current {
4154                worker: Some(job.id.clone()),
4155                task: request.task.clone(),
4156                run: queue
4157                    .get(&request.task)
4158                    .ok()
4159                    .and_then(|task| task.execution_runs().last().cloned())
4160                    .unwrap_or_default(),
4161            })
4162            .collect();
4163        {
4164            let mut snapshot = lock(status);
4165            snapshot.polls += 1;
4166            snapshot.completed += previous.difference(&owned).count();
4167            snapshot.current = current;
4168            snapshot.idle = owned.is_empty();
4169            snapshot.dispatch_wait = None;
4170        }
4171        previous = owned.clone();
4172        stop.busy.store(owned.len(), Ordering::SeqCst);
4173
4174        // Slots are reconstructed from durable reservations and OS-held worker
4175        // leases, not this scheduler's lifetime or mutable task urgency.
4176        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4177        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4178        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4179        let mut permits = Vec::new();
4180        sweep_stale_claims(queue, STALE_CLAIM);
4181        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4182        reclaim_abandoned_runs(home, Timestamp::now());
4183        let questions = Questions::at(home.join("questions"));
4184
4185        // Deterministic: no model, run before the conductor sees anything so
4186        // its input reflects the queue's current, already-resolved state.
4187        crate::task_chat::sweep(
4188            queue,
4189            &crate::talk::Talks::at(home.join("talks")),
4190            &questions,
4191            home,
4192        );
4193        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4194            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4195        {
4196            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4197        }
4198        repair_choice_offers(&questions);
4199        resolve_blockers(queue, &questions);
4200        apply_task_choice_actions(queue, &questions, home);
4201        triage::apply_answers(queue, &questions);
4202        reconcile_task_questions(queue, &questions);
4203        let talks = crate::talk::Talks::at(home.join("talks"));
4204        crate::chat_notify::sweep(queue, &talks, home);
4205        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4206        crate::chat_watch::sweep(home, &talks);
4207        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4208            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4209        }
4210        let mut turns = tokio::task::JoinSet::new();
4211        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4212        // start_turns dispatches detached turns; no paid work lives in this set.
4213        while turns.join_next().await.is_some() {}
4214
4215        crate::consult::start_services(
4216            home,
4217            &opts.repo,
4218            limits.recovery_cfg.as_ref(),
4219            opts.config.as_deref(),
4220        )
4221        .await?;
4222        for operation in [
4223            "conductor",
4224            "maintenance",
4225            "housekeeping",
4226            "disk-pressure",
4227            "cache",
4228            "fetch",
4229            "chat-goals",
4230        ] {
4231            // Once an idle --once drain starts settling services, subsequent
4232            // scans only consume their effects. An expired cadence receipt
4233            // must not start another service and keep the drain alive.
4234            if settling_once_services {
4235                break;
4236            }
4237            if operation == "chat-goals" && stop.parking() {
4238                continue;
4239            }
4240            start_service(
4241                home,
4242                opts,
4243                queue,
4244                worktrees_root,
4245                operation,
4246                limits.recovery_cfg.as_ref(),
4247                !live.is_empty(),
4248            )
4249            .await?;
4250        }
4251        let latest = crate::worker::active(home)?;
4252        if latest.iter().any(|job| job.key == "service:daemon-cache")
4253            || latest
4254                .iter()
4255                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4256        {
4257            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4258            continue;
4259        }
4260        let candidates: Vec<Task> = runnable(queue)
4261            .into_iter()
4262            .filter(|task| !live.contains(&task.id))
4263            .filter(|task| !opts.once || !attempted.contains(&task.id))
4264            .collect();
4265        let in_flight: Vec<_> = owned.iter().cloned().collect();
4266        let prior_interrupt = std::mem::discriminant(&interrupt);
4267        interrupt = advance_interrupt_tick(
4268            limits.pause_for_interrupts,
4269            interrupt,
4270            &in_flight,
4271            &candidates,
4272        );
4273        // Same-variant transitions preserve their identities. Only an actual
4274        // transition needs a durable write, atomically before sending controls.
4275        if prior_interrupt != std::mem::discriminant(&interrupt) {
4276            let temporary = interrupt_path.with_extension("json.tmp");
4277            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4278            std::fs::rename(temporary, &interrupt_path)?;
4279        }
4280        if let Interrupt::Parking {
4281            parked,
4282            interrupt_task,
4283        } = &interrupt
4284        {
4285            for job in jobs.iter().filter(|job| {
4286                parked
4287                    .iter()
4288                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4289            }) {
4290                if crate::worker::control(home, &job.key)?.is_none() {
4291                    request_task_park(
4292                        home,
4293                        job,
4294                        crate::run::ParkCause::Interrupt {
4295                            reason: format!(
4296                                "task {} asked to run first",
4297                                crate::run::short_of(interrupt_task)
4298                            ),
4299                        },
4300                    )?;
4301                }
4302            }
4303        }
4304        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4305        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4306        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4307        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4308        let mut started = false;
4309        let mut resync = false;
4310        for candidate in candidates {
4311            if stop.stopped() {
4312                break;
4313            }
4314            let DispatchClaim {
4315                task,
4316                claim,
4317                permit,
4318            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4319                Ok(claim) => claim,
4320                Err(reason) => {
4321                    skips.insert((candidate.id, reason));
4322                    continue;
4323                }
4324            };
4325            if crate::worker::active(home)?
4326                .iter()
4327                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4328            {
4329                drop(claim);
4330                resync = true;
4331                break;
4332            }
4333            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4334            let request = TaskWorker {
4335                opts: opts.absolute()?,
4336                queue: std::path::absolute(queue.root())?,
4337                task: task.id.clone(),
4338                lane,
4339                standalone: false,
4340            };
4341            // Keep the claim until spawn acknowledges the worker's durable
4342            // reservation. The worker then claims and re-reads before attempt.
4343            if let Err(error) = crate::worker::spawn(
4344                home,
4345                "task",
4346                &format!("task:{}", task.id),
4347                serde_json::to_value(&request)?,
4348            )
4349            .await
4350            {
4351                task_worker_spawn_error(home, &request, error)?;
4352                drop(claim);
4353                resync = true;
4354                break;
4355            }
4356            drop(claim);
4357            permits.extend(permit);
4358            attempted.push(task.id);
4359            started = true;
4360        }
4361        if !resync && !stop.stopped() {
4362            if !started {
4363                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4364            }
4365            if changed_dispatch_skips(&mut previous_skips, skips) {
4366                if previous_skips.is_empty() {
4367                    tracing::info!("dispatch skips cleared");
4368                }
4369                for (task, reason) in &previous_skips {
4370                    tracing::info!(
4371                        task,
4372                        reason = reason.key(),
4373                        "task {} skipped: {}",
4374                        crate::run::short_of(task),
4375                        reason.describe()
4376                    );
4377                }
4378            }
4379        }
4380        if started || resync {
4381            continue;
4382        }
4383        if owned.is_empty() && opts.once {
4384            settling_once_services = true;
4385            // These finite services can own queue claims or publish answers.
4386            // A skipped claim is not an idle queue until they have finished;
4387            // scan again afterwards so their changes are actually scheduled.
4388            if crate::worker::active(home)?.iter().any(|job| {
4389                job.kind == "daemon-service"
4390                    && matches!(
4391                        job.key.as_str(),
4392                        "service:daemon-housekeeping"
4393                            | "service:daemon-conductor"
4394                            | "service:daemon-maintenance"
4395                    )
4396            }) {
4397                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4398                continue;
4399            }
4400            break;
4401        }
4402        stop.idle(if live.is_empty() {
4403            opts.poll
4404        } else {
4405            RECHECK_WHILE_BUSY.min(opts.poll)
4406        })
4407        .await;
4408    }
4409    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4410    // every queue claim and Runner driver lease through outcome settlement.
4411    stop.busy.store(0, Ordering::SeqCst);
4412    lock(status).dispatch_wait = None;
4413    Ok(())
4414}
4415
4416/// A maintenance pass may briefly own the same record while a worker starts.
4417/// Wait without blocking the executor or charging an agent attempt, then read
4418/// ownership again under the acquired lock. Other I/O failures still fail closed.
4419async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4420    let busy = |error: &anyhow::Error| {
4421        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4422            error.kind() == std::io::ErrorKind::WouldBlock
4423                || cfg!(windows) && error.raw_os_error() == Some(33)
4424        })
4425    };
4426    match crate::pr_head::owner_lock(home, id) {
4427        Ok(lock) => return Ok(lock),
4428        Err(error) if busy(&error) => {}
4429        Err(error) => return Err(error),
4430    }
4431    let wait = RunState::load_under(id, home)?
4432        .config
4433        .graph
4434        .timeout_resource_wait;
4435    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4436}
4437
4438/// Historical successors do not revoke a still-resumable public owner. Scan
4439/// under the same lock as publication/driver claims, and fail closed on unknown
4440/// history before spending another attempt.
4441async fn public_resume_owner(
4442    home: &Path,
4443    runs: &[String],
4444    repo: &Path,
4445) -> Result<Option<RunState>> {
4446    let mut owner = None;
4447    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4448        let _lock = resume_owner_lock(home, id).await?;
4449        let state = RunState::load_under(id, home)?;
4450        if state.released()
4451            || state.retired_to.is_some()
4452            || state.pr_taken_over_by.is_some()
4453            || !crate::handover::landing_checkpoint(&state)
4454        {
4455            continue;
4456        }
4457        anyhow::ensure!(
4458            crate::git::toplevel(&state.repo).await?.canonicalize()?
4459                == crate::git::toplevel(repo).await?.canonicalize()?,
4460            "public owner repository differs; inspect run lineage"
4461        );
4462        anyhow::ensure!(
4463            owner.is_none(),
4464            "multiple retained public owners; inspect run lineage"
4465        );
4466        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4467            anyhow::bail!(reason.diagnostic(&state));
4468        }
4469        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4470        anyhow::ensure!(
4471            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4472            "public owner's driver is live or unknown; wait before retrying"
4473        );
4474        owner = Some(state);
4475    }
4476    Ok(owner)
4477}
4478
4479/// Run one claimed task to a terminal status and record the outcome.
4480///
4481/// Every transition is flushed to the queue as it happens, so the state on disk
4482/// is what actually occurred rather than what this process still intends to
4483/// write.
4484async fn attempt(
4485    opts: &Opts,
4486    queue: &Queue,
4487    status: &Arc<Mutex<Status>>,
4488    stop: &Stop,
4489    interrupt_pause: crate::graph::Pause,
4490    task: &mut Task,
4491) -> Vec<QuotaLoss> {
4492    let repo = repo_for(task, &opts.repo);
4493    tracing::info!(
4494        "task {} — {} (repo {})",
4495        task.short(),
4496        task.title,
4497        repo.display()
4498    );
4499
4500    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4501        Ok(owner) => owner,
4502        Err(e) => {
4503            task.hold_machine(Some(format!(
4504                "Cannot verify existing public owner: {e:#}; no attempt started."
4505            )));
4506            record(queue, task);
4507            return Vec::new();
4508        }
4509    };
4510    let resume_runs = public_owner
4511        .as_ref()
4512        .map(|s| vec![s.id.clone()])
4513        .unwrap_or_else(|| task.execution_runs().to_vec());
4514
4515    // A stop spends no agent resources and uses the saved landing owner.
4516    // Current roster edits, missing attachments or a failed config fetch must
4517    // never turn it into a new implementation, or prevent a PR from closing.
4518    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4519        && previous
4520            .merge_decision
4521            .as_ref()
4522            .is_some_and(|decision| !decision.closed)
4523        && previous.status != RunStatus::Landing
4524        && !crate::merge_decision::resumable_hold(&previous)
4525    {
4526        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)));
4527        record(queue, task);
4528        return Vec::new();
4529    }
4530    let stop_owner = resume_runs
4531        .last()
4532        .and_then(|id| RunState::load(id).ok())
4533        .filter(|state| {
4534            crate::merge_decision::resumable_hold(state)
4535                || state.status == RunStatus::Landing
4536                    && state.land_approval.as_ref().is_some_and(|binding| {
4537                        Questions::open()
4538                            .get_for_effects(&binding.question)
4539                            .is_ok_and(|q| {
4540                                q.run == state.id
4541                                    && q.resolution()
4542                                        .as_deref()
4543                                        .is_some_and(crate::merge_decision::stops)
4544                            })
4545                    })
4546        });
4547    if let Some(owner) = stop_owner {
4548        let mut runner = match Runner::resume(&owner.id) {
4549            Ok(runner) => runner,
4550            Err(e) => {
4551                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4552                record(queue, task);
4553                return Vec::new();
4554            }
4555        };
4556        runner.on_pause(stop.pause());
4557        runner.watch_interrupt(interrupt_pause);
4558        let quota_before = runner.state.quota.clone();
4559        let before_start = task.clone();
4560        task.start(owner.id.clone());
4561        if let Err(error) = queue.put(task) {
4562            *task = before_start;
4563            let error = runner.fail_startup("task-start", error);
4564            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4565                task.record_startup_failure(failure.clone());
4566            }
4567            task.hold_manual(Some(format!(
4568                "Could not persist task start; no agents dispatched: {error:#}"
4569            )));
4570            record(queue, task);
4571            return Vec::new();
4572        }
4573        lock(status).current.push(Current {
4574            worker: None,
4575            task: task.id.clone(),
4576            run: owner.id,
4577        });
4578        runner.state.carry_dispatched_resumes(task);
4579        runner.state.next_pass_task_entry = true;
4580        let result = runner.execute().await;
4581        return finish_attempt(
4582            opts.max_attempts,
4583            queue,
4584            task,
4585            &runner.state,
4586            &quota_before,
4587            result,
4588        );
4589    }
4590
4591    if let Some(owner) = &public_owner
4592        && (task.fresh_start || !may_resume_run(owner, task))
4593    {
4594        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)));
4595        record(queue, task);
4596        return Vec::new();
4597    }
4598
4599    if let Some(state) = task
4600        .execution_runs()
4601        .last()
4602        .and_then(|id| RunState::load(id).ok())
4603        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4604    {
4605        task.hold_machine(Some(reason));
4606        record(queue, task);
4607        return Vec::new();
4608    }
4609
4610    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4611        && !task.fresh_start
4612        && task.pr_recovery.is_none()
4613    {
4614        // Authorization still takes the owner lock and execution lease and
4615        // rechecks liveness, retained HEAD and ownership before saving.
4616        let authorized = if crate::repair_budget::conflict_pending(task, &held) {
4617            true
4618        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4619            let home = queue.root().parent().expect("queue has a home");
4620            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4621                Ok(()) => true,
4622                Err(error) => {
4623                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4624                    false
4625                }
4626            }
4627        } else {
4628            false
4629        };
4630        if !authorized {
4631            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())));
4632            // Retain the existing stop identity when an old release reached the queue.
4633            task.base_sync_notice(&held);
4634            task.resume_override = None;
4635            record(queue, task);
4636            return Vec::new();
4637        }
4638    }
4639    let unfinished = (!task.fresh_start)
4640        .then(|| unfinished_run(&resume_runs, task.short()))
4641        .flatten()
4642        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4643    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4644    if task.repair_grants.last().is_some_and(|receipt| {
4645        task.execution_runs().last() == Some(&receipt.request.run)
4646            && task.operator_decided_at == receipt.decision
4647            && previous
4648                .as_ref()
4649                .is_none_or(|run| run.id != receipt.request.run)
4650    }) {
4651        task.hold_unrequested_retry(Some(
4652            "The retained repair run cannot be read or no longer owns this task's recovery. Inspect the saved grant and run; no replacement was started.".into(),
4653        ));
4654        record(queue, task);
4655        return Vec::new();
4656    }
4657    if let Some(id) = &task.disk_resume_run
4658        && unfinished.as_ref() != Some(id)
4659    {
4660        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()));
4661        record(queue, task);
4662        return Vec::new();
4663    }
4664
4665    if !task.fresh_start
4666        && task.pr_recovery.is_none()
4667        && task.review_branch.is_none()
4668        && task.resume_override.is_none()
4669        && previous
4670            .as_ref()
4671            .is_some_and(|run| run.retired_to.is_some())
4672        && unfinished.is_none()
4673    {
4674        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()));
4675        record(queue, task);
4676        return Vec::new();
4677    }
4678
4679    let saved_recovery = previous.as_ref().filter(|run| {
4680        task.replacement.is_none()
4681            && task.pr_recovery.as_ref().is_some_and(|selected| {
4682                selected
4683                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4684                    .is_ok()
4685                    && selected_starter(selected, Some(run), unfinished.as_deref())
4686                        == Starter::Resume(run.id.clone())
4687            })
4688    });
4689
4690    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
4691    // failure here is the network's or the operator's, not the task's: hold
4692    // without spending an attempt, never fall back to a possibly stale copy.
4693    let explicit = match &task.overrides {
4694        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
4695        Some(_) => opts.config.as_deref(),
4696        None => opts.config.as_deref(),
4697    };
4698    let (mut config, layers) = if let Some(run) = saved_recovery {
4699        // A matching resume owns its resolved configuration and evidence;
4700        // current layers and inherited overrides only configure new work.
4701        let mut saved = run.clone();
4702        if let Err(e) = saved.configure_recovery_resume() {
4703            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
4704            record(queue, task);
4705            return Vec::new();
4706        }
4707        (saved.config, Vec::new())
4708    } else {
4709        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
4710            Ok(loaded) => loaded,
4711            Err(e) => {
4712                let reason = format!("[config] {e:#}");
4713                record_config_failure(task, &e);
4714                task.last_error = Some(reason.clone());
4715                task.hold_machine(Some(reason));
4716                record(queue, task);
4717                return Vec::new();
4718            }
4719        };
4720        if let Err(e) = apply_options(&mut config, opts, task) {
4721            task.hold_manual(Some(format!(
4722                "[config] {e:#}; correct the merge override before releasing the task"
4723            )));
4724            record(queue, task);
4725            return Vec::new();
4726        }
4727        if let Some(selected) = &task.pr_recovery
4728            && let Err(e) = selected.configure(&mut config)
4729        {
4730            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
4731            record(queue, task);
4732            return Vec::new();
4733        }
4734        (config, layers)
4735    };
4736    let config_evidence = crate::pr_recovery::ConfigEvidence {
4737        layers,
4738        overrides: task.overrides.clone(),
4739        daemon_merge: task
4740            .overrides
4741            .as_ref()
4742            .is_none_or(|o| o.inherit_daemon_options)
4743            .then(|| opts.merge.clone())
4744            .flatten(),
4745    };
4746    apply_task_implementers(&mut config, task);
4747    if let Some(replacement) = &task.replacement {
4748        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
4749            old.liveness(false) == Liveness::Dead
4750                && old.merge_decision.as_ref().is_some_and(|d| {
4751                    d.closed
4752                        && d.question == replacement.question
4753                        && d.replacement_run.as_ref().is_none_or(|run| {
4754                            task.execution_runs().last() == Some(run)
4755                                && RunState::load(run).is_ok_and(|current| {
4756                                    current.replaces.as_ref().is_some_and(|pin| {
4757                                        pin.question == replacement.question
4758                                            && pin.agent == replacement.agent
4759                                    })
4760                                })
4761                        })
4762                })
4763        });
4764        if !safe {
4765            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()));
4766            record(queue, task);
4767            return Vec::new();
4768        }
4769        match config.agent(&replacement.agent) {
4770            Ok(agent) if crate::agent::installed(agent) => {}
4771            _ => {
4772                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)));
4773                record(queue, task);
4774                return Vec::new();
4775            }
4776        }
4777        config.graph.implementers = 1;
4778        config.graph.land_approval = true;
4779        config.merge.mode = MergeMode::Pr;
4780        config.graph.selected_implementer = Some(replacement.agent.clone());
4781    }
4782    let p = phrases(&config.graph.language);
4783    let start_failed = p.could_not_start;
4784    // Resolve once for both admission and settlement. The inputs are the
4785    // task's explicit sources (never prose), plus an explicit review source's
4786    // current head; review-only runs may rebase later, and neither fact can
4787    // refund a failed automatic generation.
4788    if let Ok(base) =
4789        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
4790            .await
4791        && let Ok(head) =
4792            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
4793    {
4794        let mut inputs = crate::queue::recovery_inputs(&task.sources);
4795        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
4796            let source = crate::git::rev_parse(&repo, branch)
4797                .await
4798                .unwrap_or_default();
4799            inputs.push_str(&format!(";review:{branch}:{source}"));
4800        }
4801        if let Some(reason) = task
4802            .recovery_exhausted(
4803                &head,
4804                &inputs,
4805                task.attempt_limit
4806                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
4807            )
4808            .filter(|_| {
4809                !task.repair_grants.last().is_some_and(|receipt| {
4810                    RunState::load(&receipt.request.run)
4811                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
4812                })
4813            })
4814        {
4815            task.hold_recovery_budget(
4816                reason,
4817                crate::queue::RecoveryAdmission { base: head, inputs },
4818            );
4819            record(queue, task);
4820            return Vec::new();
4821        }
4822        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
4823    }
4824
4825    // A resumable run of this task is carried on, never re-competed. The
4826    // candidates are built and paid for, and a fresh competition races a
4827    // second implementation against them.
4828    //
4829    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
4830    // started 3cbf on the same task a moment later, duplicating two and a
4831    // half hours of agent work. Then b25f stalled on a judge that timed out
4832    // and one that answered with no JSON - `quota: 0`, so nothing the machine
4833    // was to blame for - and 4043 started **one second** later, buying three
4834    // fresh implementations to reach the same panel. `RunStatus::resumable`
4835    // rather than `!done()` is what catches the second case: a stall is
4836    // terminal, and its cheap recovery re-asks only the absent seats.
4837    //
4838    // A load failure is warned about rather than silently read as "not
4839    // resumable": the alternative is exactly what let a schema mismatch on
4840    // run `eba2` fall through to a full re-competition with nobody told why.
4841    // `crate::conduct` is what actually offers a better answer than
4842    // `Runner::start` here (see `Recovery::Review`), once this task's next
4843    // failure shows it up as `held`/`failed` with the run state unreadable.
4844    // Keep a retained review selection intact until disk admission succeeds.
4845    let consume_review = !previous
4846        .as_ref()
4847        .is_some_and(|state| crate::repair_budget::pending(task, state));
4848    let review_branch = consume_review
4849        .then(|| review_branch_for(task, previous.as_ref()))
4850        .flatten();
4851    let branch_exists = match review_branch {
4852        Some(branch) => crate::git::branch_exists(&repo, branch)
4853            .await
4854            .unwrap_or(false),
4855        None => false,
4856    };
4857    // An explicit `magi review <branch>` is reviewed whatever happens to the
4858    // branch unless an explicit implementer change requires fresh work. An
4859    // unfinished run of the same task still wins, so a retry resumes.
4860    let proposed = review_retry_starter(
4861        task,
4862        previous.as_ref(),
4863        review_branch,
4864        branch_exists,
4865        unfinished.as_deref(),
4866    );
4867    let retry_selected = task.replacement.is_some()
4868        && task.resumption.is_some()
4869        && !task.fresh_start
4870        && previous.as_ref().is_some_and(|run| {
4871            run.replaces.is_some()
4872                && ((run.status == RunStatus::Failed && run.viable().is_empty())
4873                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
4874        });
4875    let stop_pin = task
4876        .resume_override
4877        .as_ref()
4878        .filter(|pin| {
4879            Questions::open()
4880                .get_for_effects(&pin.question_id)
4881                .is_ok_and(|q| {
4882                    q.node == land::APPROVAL_NODE
4883                        && q.resolution()
4884                            .as_deref()
4885                            .is_some_and(crate::merge_decision::stops)
4886                })
4887        })
4888        .and_then(|pin| pin.pinned_run.clone());
4889    let granted_run = task.repair_grants.last().and_then(|receipt| {
4890        let state = RunState::load(&receipt.request.run).ok()?;
4891        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
4892    });
4893    let starter = if let Some(run) = granted_run {
4894        Starter::Resume(run)
4895    } else if let Some(owner) = &public_owner {
4896        Starter::Resume(owner.id.clone())
4897    } else if let Some(run) = stop_pin {
4898        // Stop actions resume their exact owner even after seat-count edits;
4899        // they must never fall through to implementation or a takeover.
4900        Starter::Resume(run)
4901    } else if retry_selected {
4902        Starter::Resume(previous.as_ref().unwrap().id.clone())
4903    } else if let Some(selected) = &task.pr_recovery {
4904        if selected
4905            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
4906            .is_ok()
4907        {
4908            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
4909        } else {
4910            Starter::Review(selected.branch.clone())
4911        }
4912    } else {
4913        starter_with_implementers(task, previous.as_ref(), proposed)
4914    };
4915    // A retained execution still writes to its saved output volume. A newer
4916    // repository policy only selects the volume for a fresh run.
4917    let disk_reason = match &starter {
4918        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
4919            || {
4920                RunState::load(id)
4921                    .ok()
4922                    .and_then(|run| disk_gate(&run.repo, &run.config))
4923            },
4924            |run| disk_gate(&run.repo, &run.config),
4925        ),
4926        _ => disk_gate(&repo, &config),
4927    };
4928    if let Some(reason) = disk_reason {
4929        task.notice_cause("disk-space", None, None);
4930        task.last_error = Some(reason.clone());
4931        let disk_checked_at = task.disk_checked_at;
4932        task.hold_machine(Some(reason.clone()));
4933        if matches!(starter, Starter::Resume(_)) {
4934            task.mark_disk_capacity();
4935        } else {
4936            task.mark_startup_disk_capacity();
4937        }
4938        task.disk_checked_at = disk_checked_at;
4939        record(queue, task);
4940        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
4941        notices::raise(
4942            Notice::warn(
4943                &format!("disk:{}", repo.display()),
4944                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
4945            )
4946            .link(Link::Task {
4947                id: task.id.clone(),
4948            }),
4949        );
4950        return Vec::new();
4951    }
4952    let review_branch = if consume_review {
4953        let valid = review_branch.is_some();
4954        task.review_instruction = None;
4955        task.review_branch.take().filter(|_| valid)
4956    } else {
4957        None
4958    };
4959    // An explicit resume pin must never degrade into a new competition or
4960    // takeover, including when its run stops being eligible after the answer.
4961    if let Some(pin) = &task.resume_override
4962        && let Some(run) = &pin.pinned_run
4963        && starter != Starter::Resume(run.clone())
4964    {
4965        let run = run.clone();
4966        task.notice_cause("resume-owner", Some(&run), None);
4967        task.hold_machine(Some(format!(
4968            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
4969            task.id
4970        )));
4971        record(queue, task);
4972        return Vec::new();
4973    }
4974    // Automatic disk recovery resumes its retained run or stops: a changed
4975    // seat count or review branch must not turn it into a new competition.
4976    // No attempt is spent here.
4977    if let Some(run) = &task.disk_resume_run
4978        && starter != Starter::Resume(run.clone())
4979    {
4980        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()));
4981        record(queue, task);
4982        return Vec::new();
4983    }
4984    if task.replacement.is_some()
4985        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
4986        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
4987    {
4988        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()));
4989        record(queue, task);
4990        return Vec::new();
4991    }
4992    if let Some(reason) = retained_attempt_hold(
4993        task,
4994        &starter,
4995        config.disk.retained_attempt_limit,
4996        RunState::load,
4997    ) {
4998        // The review choice was consumed above. Preserve it across this hold
4999        // so a later release cannot silently become a fresh implementation.
5000        if let Starter::Review(branch) = &starter {
5001            task.review_branch = Some(branch.clone());
5002        }
5003        task.hold_unrequested_retry(Some(reason));
5004        record(queue, task);
5005        return Vec::new();
5006    }
5007    // Absolute paths of the files the task was filed with, re-read from the
5008    // task now so a file attached while it was held reaches a resumed run
5009    // too. A stored name whose file has gone is an error before any agent is
5010    // paid for, never a silent omission the implementer cannot notice.
5011    let attachments = match task_attachments(queue, task) {
5012        Ok(a) => a,
5013        Err(e) => {
5014            task.attempts += 1;
5015            task.fail_startup_target(
5016                "startup-attachments",
5017                e.name.clone(),
5018                format!("{start_failed}{e:#}"),
5019                opts.max_attempts,
5020            );
5021            record(queue, task);
5022            return Vec::new();
5023        }
5024    };
5025    let startup_pause = stop.pause();
5026    let startup_interrupt = interrupt_pause.clone();
5027    let wait = crate::repo_lock::WaitPolicy::new(
5028        Duration::from_secs(config.graph.timeout_resource_wait),
5029        move || startup_pause.parked() || startup_interrupt.parked(),
5030    );
5031    // Startup includes review takeover and recovery. Do not embed its large
5032    // future in both the wait scope and the surrounding attempt stack frame.
5033    let started = wait.scope(Box::pin(async { match &starter {
5034        Starter::Review(_) if task.pr_recovery.is_some() => {
5035            let selected = task.pr_recovery.clone().expect("selected recovery");
5036            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5037                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5038                    .await
5039                    .map(|mut r| {
5040                        r.state.attachments = attachments.clone();
5041                        r
5042                    }),
5043                Err(e) => Err(e),
5044            }
5045        }
5046        Starter::Review(branch) => {
5047            tracing::info!(
5048                "task {} reopens `{branch}` as a review-only pass",
5049                task.short()
5050            );
5051            // Every earlier attempt is superseded by the one being minted
5052            // now, so a branch one of them still holds may be taken over.
5053            let takeover = crate::handover::Takeover {
5054                earlier: task.earlier_attempts().to_vec(),
5055                home: crate::run::home(),
5056                choice: take_divergence_answer(branch, &config.merge.remote, task),
5057                task_instruction: Some(instruction_for(task)),
5058            };
5059            Runner::review_taking_over(
5060                &repo,
5061                branch,
5062                config,
5063                Some(takeover),
5064                crate::run::Origin::queue(&task.id),
5065            )
5066            .await
5067        }
5068        Starter::Resume(id) => {
5069            tracing::info!("resuming run {id} rather than competing again");
5070            Runner::resume(id).and_then(|mut r| {
5071                if retry_selected {
5072                    // The explicit queue release retries this same pinned
5073                    // implementation, preserving the attempt and worktrees.
5074                    for candidate in &mut r.state.candidates {
5075                        candidate.failed = None;
5076                        candidate.empty = false;
5077                        candidate.commits = 0;
5078                    }
5079                    r.state.status = RunStatus::Implementing;
5080                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5081                }
5082                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5083                    r.state.sources = task.sources.clone();
5084                }
5085                if r.state.prep_failure.is_some() {
5086                    let approval = task
5087                        .resumption
5088                        .as_ref()
5089                        .context("preparation retry requires an explicit task release")?;
5090                    r.retry_preparation(approval.at)?;
5091                }
5092                if let Some(instruction) =
5093                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5094                {
5095                    r.state.instruction = instruction;
5096                }
5097                r.state.attachments = attachments.clone();
5098                if task.replacement.is_some() {
5099                    r.state.config.merge.mode = MergeMode::Pr;
5100                    r.state.config.graph.land_approval = true;
5101                }
5102                // Replacements publish a new PR and ask again. Selected PR
5103                // recoveries keep their saved disposition; ordinary runs can
5104                // retain the task's merge override.
5105                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5106                    .overrides
5107                    .as_ref()
5108                    .and_then(|o| o.merge.as_deref())
5109                    .and_then(|m| merge_mode(m).ok())
5110                {
5111                    r.state.config.merge.mode = mode;
5112                }
5113                Ok(r)
5114            })
5115        }
5116        Starter::Start => {
5117            if let Some(branch) = &review_branch {
5118                tracing::warn!(
5119                    "conductor chose review for task {} but branch `{branch}` no longer \
5120                     exists; requeuing as a fresh competition instead",
5121                    task.short()
5122                );
5123            }
5124            let instruction = prepare_instruction(&starter, None, task)
5125                .unwrap_or_else(|| task.instruction.clone());
5126            Runner::start_naming(
5127                &repo,
5128                instruction,
5129                &task.title,
5130                config,
5131                crate::run::Origin::queue(&task.id),
5132            )
5133            .await
5134            .map(|mut r| {
5135                r.state.attachments = attachments.clone();
5136                r.state.sources = task.sources.clone();
5137                r
5138            })
5139        }
5140    }})).await;
5141    if let Err(error) = &started
5142        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5143    {
5144        task.record_startup_failure(failure.clone());
5145    }
5146    let mut runner = match started {
5147        Ok(r) => r,
5148        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5149            let detail = format!("{e:#}");
5150            task.last_error = Some(detail.clone());
5151            if e.is::<crate::build_target::AdmissionDiskWait>()
5152                && let Starter::Review(branch) = &starter
5153                && review_branch.is_some()
5154            {
5155                task.review_branch = Some(branch.clone());
5156                task.review_instruction = Some(task.instruction.clone());
5157            }
5158            if stop.parking() || interrupt_pause.parked() {
5159                let attempts = task.attempts;
5160                task.park(e.to_string());
5161                // Startup has not spent an attempt to refund.
5162                task.attempts = attempts;
5163            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5164                let disk_checked_at = task.disk_checked_at;
5165                task.hold_machine(Some(detail));
5166                task.mark_startup_disk_capacity();
5167                task.disk_checked_at = disk_checked_at;
5168            } else {
5169                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5170            }
5171            record(queue, task);
5172            return Vec::new();
5173        }
5174        // A branch an earlier attempt still holds and magi will not release
5175        // by itself is the operator's call, not a failed attempt: hold the
5176        // task with the reason, spend nothing, and say so on the bell.
5177        Err(e) if task.pr_recovery.is_some() => {
5178            task.startup_notice_cause("startup-public-head");
5179            task.attempts += 1;
5180            task.last_error = Some(format!("{start_failed}{e:#}"));
5181            task.hold_unrequested_retry(Some(format!(
5182                "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."
5183            )));
5184            record(queue, task);
5185            return Vec::new();
5186        }
5187        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5188            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5189                Some(r) => (p.handover_refused)(r),
5190                None => format!("{e:#}"),
5191            };
5192            task.startup_notice_cause("startup-handover");
5193            let reason = format!("{start_failed}{detail}");
5194            task.last_error = Some(reason.clone());
5195            // Consumed above by `take`; keep it so the released task retries
5196            // as a review of this same branch.
5197            let branch = match &starter {
5198                Starter::Review(branch) => Some(branch.clone()),
5199                _ => None,
5200            };
5201            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5202            // one page; the guidance rides in the reason, fixed per state so a
5203            // re-put never changes the wording and relights it.
5204            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5205            record(queue, task);
5206            tracing::warn!(
5207                "holding {} for a branch it cannot take over: {e:#}",
5208                task.short()
5209            );
5210            return Vec::new();
5211        }
5212        // A branch that differs between here and the remote in ways magi
5213        // cannot prove are the same change is a decision for the owner, not a
5214        // failed attempt: ask with both sides laid out, spend no attempt, and
5215        // let the answer requeue the task.
5216        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5217            let d = e
5218                .downcast_ref::<crate::reconcile::Diverged>()
5219                .expect("checked by the guard");
5220            let mut q = ask::Question::new(
5221                task.id.clone(),
5222                crate::reconcile::NODE.to_owned(),
5223                crate::reconcile::SEAT.to_owned(),
5224                d.summary(),
5225                d.detail(),
5226                d.choices(),
5227            );
5228            match Questions::open().put(&mut q) {
5229                Ok(()) => {
5230                    task.last_error = Some(format!("{e:#}"));
5231                    // Consumed above by `take`; the answer has to reach a review
5232                    // of this same branch, so keep pointing the task at it.
5233                    task.review_branch = Some(d.branch.clone());
5234                    task.review_instruction = Some(task.instruction.clone());
5235                    task.block(vec![q.id.clone()], Some(d.summary()));
5236                }
5237                Err(put) => {
5238                    tracing::warn!("could not file the divergence question: {put:#}");
5239                    task.attempts += 1;
5240                    task.fail_startup(
5241                        "startup-question-store",
5242                        format!("{start_failed}{e:#}"),
5243                        opts.max_attempts,
5244                    );
5245                }
5246            }
5247            record(queue, task);
5248            return Vec::new();
5249        }
5250        Err(e) => {
5251            // The answer was stale and nothing was applied: keep pointing at
5252            // the branch so the next attempt asks again against its new tips.
5253            // Nothing went wrong with the task, so no attempt is spent: a
5254            // budget one short of its limit must not hold it instead of
5255            // letting the question be asked again.
5256            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5257                && let Starter::Review(branch) = &starter
5258            {
5259                task.review_branch = Some(branch.clone());
5260                task.review_instruction = Some(task.instruction.clone());
5261                task.last_error = Some(format!("{start_failed}{e:#}"));
5262                task.status = crate::queue::TaskStatus::Failed;
5263                record(queue, task);
5264                return Vec::new();
5265            }
5266            task.attempts += 1;
5267            task.last_error = Some(format!("{start_failed}{e:#}"));
5268            task.startup_notice_cause("startup-source");
5269            task.hold_unrequested_retry(Some(format!(
5270                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5271            )));
5272            record(queue, task);
5273            return Vec::new();
5274        }
5275    };
5276    if !matches!(starter, Starter::Resume(_))
5277        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5278    {
5279        runner
5280            .state
5281            .event("build-cache", format!("{mode} selected by {source}"));
5282    }
5283    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5284        runner.state.recovery_config = Some(config_evidence);
5285    }
5286    if let Some(replacement) = &task.replacement {
5287        if matches!(starter, Starter::Start) {
5288            runner.state.instruction.push_str(&format!(
5289                "\n\n# Replacement review context\n{}",
5290                replacement.context
5291            ));
5292        }
5293        runner.state.replaces = Some(replacement.clone());
5294        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5295        if let Ok(mut old) = RunState::load(&replacement.run)
5296            && let Some(d) = &mut old.merge_decision
5297        {
5298            d.replacement_run = Some(runner.state.id.clone());
5299            old.event(
5300                "replacement",
5301                format!(
5302                    "replacement run {} owns the next attempt; old PR remains closed",
5303                    runner.state.id
5304                ),
5305            );
5306            if let Err(e) = old.save() {
5307                let error = runner.fail_startup("replacement-history", e);
5308                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5309                    task.record_startup_failure(failure.clone());
5310                }
5311                task.hold_manual(Some(format!(
5312                    "Could not link replacement history: {error:#}; no agents dispatched"
5313                )));
5314                record(queue, task);
5315                return Vec::new();
5316            }
5317        }
5318    }
5319    runner.state.task_instruction = Some(task.instruction.clone());
5320    // The follow-up depth is fixed now, while the task certainly exists:
5321    // deleting it later must not reset the cap (`crate::followup`).
5322    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5323    if runner.state.origin_chat.is_none() {
5324        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5325    }
5326    // A stop that means "park" reaches the graph through this handle.
5327    runner.on_pause(stop.pause());
5328    // `poll`'s interrupt scheduler reaches this one run - and no other -
5329    // through this handle. See `Pause`'s own doc for why these are never
5330    // the same one.
5331    runner.watch_interrupt(interrupt_pause);
5332
5333    // `start` has minted the run, so the task can now point at it. Persisting
5334    // `Running` before `execute` is what makes a crash mid-run legible.
5335    let run = runner.state.id.clone();
5336    let before_start = task.clone();
5337    task.start(run.clone());
5338    if let Err(error) = queue.put(task) {
5339        *task = before_start;
5340        let error = runner.fail_startup("task-start", error);
5341        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5342            task.record_startup_failure(failure.clone());
5343        }
5344        task.hold_manual(Some(format!(
5345            "Could not persist task start; no agents dispatched: {error:#}"
5346        )));
5347        record(queue, task);
5348        return Vec::new();
5349    }
5350    if task.status != TaskStatus::Running {
5351        // Queue::put kept a newer hold or continuation instead of this start.
5352        return Vec::new();
5353    }
5354    lock(status).current.push(Current {
5355        worker: None,
5356        task: task.id.clone(),
5357        run,
5358    });
5359
5360    // `RunState::quota` is the run's whole history across every resume, so
5361    // only what this execution added may arm the cooldown or earn a refund.
5362    let quota_before = runner.state.quota.clone();
5363    runner.state.carry_dispatched_resumes(task);
5364    runner.state.next_pass_task_entry = true;
5365    let result = runner.execute().await;
5366    finish_attempt(
5367        opts.max_attempts,
5368        queue,
5369        task,
5370        &runner.state,
5371        &quota_before,
5372        result,
5373    )
5374}
5375
5376/// Settle `task` after its run executed: the verdict, the diagnosis, the
5377/// supersession of earlier attempts and the save. Shared by the loop and by
5378/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5379/// Returns the quota losses this execution added to the run.
5380pub fn finish_attempt(
5381    max_attempts: usize,
5382    queue: &Queue,
5383    task: &mut Task,
5384    state: &RunState,
5385    quota_before: &[QuotaLoss],
5386    result: Result<()>,
5387) -> Vec<QuotaLoss> {
5388    let detail = match result {
5389        Ok(()) => describe(state),
5390        Err(e) => format!("{e:#}"),
5391    };
5392    let fresh = losses_this_attempt(quota_before, &state.quota);
5393    let verdict = Verdict {
5394        status: state.status,
5395        // A run that opened a pull request handed its work over, whatever the
5396        // gate then decided about merging it.
5397        left_pr: state.pr.is_some(),
5398        // Only a rate limit earns the task its attempt back - and only one
5399        // suffered now: a refund justified by a previous session's loss is
5400        // the same mistake as re-arming the cooldown from it. A stalled run
5401        // resumed without hitting quota again therefore spends its attempt,
5402        // like any other failure of the task's own.
5403        quota_hit: !fresh.is_empty(),
5404        // A run that parked was asked to stop; that is not a failure and must
5405        // not spend an attempt, or replacing the binary a few times would
5406        // exhaust a task's budget without an agent ever misbehaving.
5407        parked: state.parked,
5408        // A quota loss that left nothing viable is the same machine fact as a
5409        // `Stalled` quota loss; see `settle`'s doc table.
5410        no_viable_candidates: state.viable().is_empty(),
5411    };
5412    if let Some(replacement) = &state.replaces
5413        && let Some(pr) = &state.pr
5414        && let Ok(mut old) = RunState::load(&replacement.run)
5415        && let Some(d) = &mut old.merge_decision
5416    {
5417        d.replacement_pr = Some(pr.url.clone());
5418        let _ = old.save();
5419    }
5420    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5421    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5422        task.hold_unrequested_retry(Some(format!(
5423            "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.",
5424            task.short()
5425        )));
5426    }
5427    if task.status == TaskStatus::Done {
5428        supersede_prior_runs(task, &crate::run::home());
5429    }
5430    record(queue, task);
5431    tracing::info!(
5432        "task {} is {} after run {} ({})",
5433        task.short(),
5434        task.status.as_str(),
5435        state.short(),
5436        label(state.status)
5437    );
5438    fresh
5439}
5440
5441/// A task a hand-started run leaves runnable (failed with attempts to spare,
5442/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5443/// later must not spend agent calls on it. `magi task release` retries.
5444pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5445    // Parked work (including legacy Failed records with a parked run) is a
5446    // checkpoint or owner handoff, not an unrequested retry.
5447    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5448        && !awaiting_resume_with(task, RunState::load)
5449        // A run parked on the owner's word about a withheld PR title/body
5450        // resumes via `land_resume_state`, including review-only tasks that
5451        // `awaiting_resume_with` does not consider.
5452        && withheld_text_wait(task).is_none()
5453        && !(task.fresh_start && task.replacement.is_some())
5454    {
5455        let why = task.last_error.clone().map_or_else(
5456            || "the run did not finish".to_owned(),
5457            |e| format!("the run did not finish: {e}"),
5458        );
5459        task.hold_unrequested_retry(Some(format!(
5460            "{why}. It was started by hand, so it is not retried \
5461             automatically; `magi task release` retries it."
5462        )));
5463        record(queue, task);
5464    }
5465}
5466
5467/// Whether an attempt at a task whose newest run is `run` would resume that
5468/// run rather than start a fresh competition. `magi run --resume` hands a run
5469/// to a live loop only when this holds.
5470#[must_use]
5471pub fn loop_would_resume(run: &str) -> bool {
5472    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5473}
5474
5475/// A loop in another process that is alive right now: a fresh heartbeat in
5476/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5477/// carries the pid it published (`None` inside when it published none - a
5478/// fresh heartbeat is still evidence of a live loop).
5479///
5480/// The one judgement of "is somebody else serving this queue", shared by the
5481/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5482/// deciding whether to hand a task to the loop. A claim file proves nothing
5483/// here: whether a claim succeeds says nothing about whether its owner lives.
5484#[must_use]
5485pub fn foreign_loop(
5486    reading: Option<&Reading>,
5487    now: Timestamp,
5488    own_pid: u32,
5489) -> Option<Option<u32>> {
5490    let reading = reading.filter(|r| r.running(now))?;
5491    match reading.pid {
5492        Some(pid) if pid == own_pid => None,
5493        pid => Some(pid),
5494    }
5495}
5496
5497fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5498    reading.worker_protocol != Some(1)
5499        && (foreign_loop(Some(reading), now, own_pid).is_some()
5500            || reading
5501                .pid
5502                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5503}
5504
5505/// Low-level claimed-task execution shared by the detached standalone worker
5506/// and focused lifecycle fixtures. The caller must retain the queue claim for
5507/// this entire call. CLI callers transfer ownership through
5508/// [`run_detached_claimed`] instead of executing inside their own runtime.
5509///
5510/// The one deliberate difference from the loop: a task the attempt leaves
5511/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5512/// Nobody asked for a retry, and a daemon starting later must not spend agent
5513/// calls re-running a hand-started task behind the operator's back;
5514/// `magi task release` is the explicit retry.
5515pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5516    run_claimed_until(opts, queue, task, &Stop::new()).await;
5517}
5518
5519async fn run_claimed_until(
5520    opts: &Opts,
5521    queue: &Queue,
5522    task: &mut Task,
5523    stop: &Stop,
5524) -> Vec<QuotaLoss> {
5525    let status = Arc::new(Mutex::new(Status::new()));
5526    // An attempt embeds startup and graph futures. Keep it off the standalone
5527    // caller's stack, on both the initial execution and withheld-text resume.
5528    let mut quota = Box::pin(attempt(
5529        opts,
5530        queue,
5531        &status,
5532        stop,
5533        crate::graph::Pause::new(),
5534        task,
5535    ))
5536    .await;
5537    // A run parked on the owner's word about a withheld PR title/body has no
5538    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5539    // here with the claim still held, and resume once the question is settled
5540    // (answered, or abandoned at its deadline -> the neutral text).
5541    // A rejected reply files one more question (the gate asks at most twice),
5542    // so after a resume the run may be waiting again: keep going, with a fresh
5543    // limit for the new question. `resumes` bounds it even if a resume parks
5544    // without asking anything new.
5545    let mut resumes = 0;
5546    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5547        let Some(timeout) = withheld_text_wait(task) else {
5548            break;
5549        };
5550        eprintln!(
5551            "waiting for the owner's answer on a withheld pull request text \
5552             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5553        );
5554        // The deadline abandons the question itself; the extra margin only
5555        // covers an abandon that could not be saved.
5556        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5557        let ready = loop {
5558            match land_resume_state(task) {
5559                LandResume::StillWaiting
5560                    if !stop.parking() && std::time::Instant::now() < limit =>
5561                {
5562                    tokio::time::sleep(WITHHELD_POLL).await;
5563                }
5564                LandResume::Ready => break true,
5565                _ => break false,
5566            }
5567        };
5568        if !ready || stop.parking() {
5569            break;
5570        }
5571        resumes += 1;
5572        quota.extend(
5573            Box::pin(attempt(
5574                opts,
5575                queue,
5576                &status,
5577                stop,
5578                crate::graph::Pause::new(),
5579                task,
5580            ))
5581            .await,
5582        );
5583    }
5584    hold_if_runnable(queue, task);
5585    quota
5586}
5587
5588/// Resumes an in-process run makes for withheld-text questions: the gate asks
5589/// at most twice, plus one for a resume that asks nothing new.
5590const MAX_WITHHELD_RESUMES: u32 = 3;
5591
5592/// How often an in-process run rechecks its withheld-text question.
5593const WITHHELD_POLL: Duration = Duration::from_secs(15);
5594
5595/// The `answer_timeout` (seconds) of the task's last run when that run is
5596/// parked on an unresolved withheld-text question; `None` otherwise.
5597fn withheld_text_wait(task: &Task) -> Option<u64> {
5598    let id = task.execution_runs().last()?;
5599    let s = RunState::load(id).ok()?;
5600    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5601        .then_some(s.config.graph.answer_timeout)
5602}
5603
5604/// The quota losses `after` holds that `before` did not: what one execution
5605/// suffered, as opposed to the run's history.
5606///
5607/// Compared by value rather than by length or position because
5608/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
5609/// the vector can shrink and shift under a resume. A retried seat that hits
5610/// quota again is a `push` with a new `at`, so it shows up as new here.
5611/// Crash recovery uses the recorded pass start as its boundary when available;
5612/// legacy records without passes retain their original history-based policy.
5613fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
5614    after
5615        .iter()
5616        .filter(|q| !before.contains(q))
5617        .cloned()
5618        .collect()
5619}
5620
5621/// When the loop-wide quota cooldown should end, given this attempt's losses;
5622/// `None` when there were none. Reset-hint parsing and the cap live here.
5623fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
5624    let quota: Vec<_> = quota
5625        .iter()
5626        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
5627        .collect();
5628    if quota.is_empty() {
5629        return None;
5630    }
5631    let with_hint = quota.iter().find(|q| q.reset.is_some());
5632    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
5633    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
5634    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
5635    Some(
5636        now.checked_add(jiff::SignedDuration::from_secs(secs))
5637            .unwrap_or(Timestamp::MAX),
5638    )
5639}
5640
5641/// An explicit task count must agree with a run before any resume.
5642fn implementers_match(task: &Task, state: &RunState) -> bool {
5643    task.replacement.as_ref().map_or_else(
5644        || {
5645            task.implementers()
5646                .is_none_or(|n| n == state.config.graph.implementers)
5647        },
5648        |replacement| {
5649            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
5650                && state.config.graph.implementers == 1
5651        },
5652    )
5653}
5654
5655/// Never resume or take over candidate work built for a different seat count.
5656fn starter_with_implementers(
5657    task: &Task,
5658    previous: Option<&RunState>,
5659    proposed: Starter,
5660) -> Starter {
5661    if previous.is_some_and(|s| !implementers_match(task, s)) {
5662        task.review_of
5663            .as_ref()
5664            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
5665    } else {
5666        proposed
5667    }
5668}
5669
5670/// Apply this task's explicit count to the new attempt, without changing defaults.
5671fn apply_task_implementers(config: &mut Config, task: &Task) {
5672    if let Some(n) = task.implementers() {
5673        config.graph.implementers = n;
5674    }
5675}
5676
5677/// [`prepare`] for one task: its own `--config` and command-line overrides
5678/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
5679/// over the loop's, so handing a hand-started task to a daemon changes nothing
5680/// about what it does.
5681#[cfg(test)]
5682fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
5683    let explicit = match &task.overrides {
5684        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5685        _ => opts.config.as_deref(),
5686    };
5687    let (mut config, _) = Config::discover(repo, explicit)?;
5688    apply_options(&mut config, opts, task)?;
5689    Ok(config)
5690}
5691
5692fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
5693    if task
5694        .overrides
5695        .as_ref()
5696        .is_none_or(|o| o.inherit_daemon_options)
5697        && let Some(mode) = opts.merge.as_deref()
5698    {
5699        config.merge.mode = merge_mode(mode)?;
5700    }
5701    if let Some(o) = &task.overrides {
5702        o.apply(config);
5703    }
5704    if let Some((mode, _)) = task.build_cache_override(config) {
5705        config.verify.build_cache = mode;
5706    }
5707    Ok(())
5708}
5709
5710/// Load the config for a task's repository, with the merge override applied.
5711fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
5712    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
5713    if let Some(mode) = &opts.merge {
5714        config.merge.mode = merge_mode(mode)?;
5715    }
5716    Ok(config)
5717}
5718
5719/// Prune the shared build cache at a between-runs boundary. The detached cache
5720/// service checks authoritative task jobs first; dispatch waits for that finite
5721/// service, so scheduler replacement cannot turn a compile into idle cleanup.
5722/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
5723async fn maybe_prune_cache_between_runs(
5724    repo: &Path,
5725    opts: &Opts,
5726    home: &Path,
5727    stop: &Stop,
5728    last_checked: &mut Option<Timestamp>,
5729    now: Timestamp,
5730) {
5731    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
5732        return;
5733    }
5734    *last_checked = Some(now);
5735    let cfg = match prepare(repo, opts) {
5736        Ok(cfg) => cfg,
5737        Err(e) => {
5738            tracing::warn!("cache check: no config: {e:#}");
5739            return;
5740        }
5741    };
5742    match clean::prune_cache_if_over_limit(&cfg, home) {
5743        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
5744            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
5745            pruned.files,
5746            pruned.freed
5747        ),
5748        Ok(_) => {}
5749        Err(e) => {
5750            tracing::warn!("housekeep: prune cache: {e:#}");
5751            notices::raise_in(
5752                home,
5753                Notice::warn(
5754                    "housekeep:cache",
5755                    format!(
5756                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
5757                        e.to_string()
5758                            .lines()
5759                            .next()
5760                            .unwrap_or("unknown cleanup error")
5761                    ),
5762                ),
5763            );
5764        }
5765    }
5766}
5767
5768/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
5769/// now, given when it last did (if ever). Pure, so the cadence is asserted
5770/// directly rather than by waiting out real minutes in a test.
5771fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
5772    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
5773}
5774
5775/// The disk janitor, with its housekeeping logged rather than fatal.
5776///
5777/// Called only at the loop's idle points, for the reason the caller documents:
5778/// a prune racing a live compile would delete files mid-build. The config is
5779/// re-read on every call because the repository that just ran may not be the
5780/// daemon's own default, and the cache directory is a repository fact.
5781///
5782/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
5783/// and [`crate::run::default_worktree_root`] read here, for the same reason
5784/// [`drive`] takes its queue and status file rather than resolving them: a
5785/// test driving the loop must not reach through to the operator's real home
5786/// or worktree bay just because the janitor runs on every idle tick.
5787/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
5788/// to get wrong silently - a test's `home` was already isolated, but nothing
5789/// exercised the parameter next to it, so a real worktree bay stayed wired in
5790/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
5791/// it for real, every test in this file that drives the loop at all started
5792/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
5793async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
5794    let cfg = match prepare(repo, opts) {
5795        Ok(cfg) => cfg,
5796        Err(e) => {
5797            tracing::warn!("housekeep: no config: {e:#}");
5798            return;
5799        }
5800    };
5801    // A run's own worktree lives under `config.graph.worktree_root` when the
5802    // repository sets one - the same precedence `RunState::worktree_root`
5803    // uses - and `worktrees_root` only stands in for the *default* an
5804    // unconfigured repository resolves to (see this function's own
5805    // parameter, or the test fixture wiring one to a fake path). Housekeeping
5806    // that always swept the default regardless of this override would never
5807    // see, and so never reclaim, a single worktree for a repository that
5808    // relocated them elsewhere.
5809    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
5810    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
5811    // Reported whenever there is anything to say, not only when `folded > 0`:
5812    // the incident this exists to prevent was 90 of 93 runs skipped and 0
5813    // folded, on every single pass, for months - a report gated on `folded`
5814    // would have stayed silent through every one of them.
5815    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
5816        let mut extra = Vec::new();
5817        if out.unreadable > 0 {
5818            extra.push(format!("{} unreadable", out.unreadable));
5819        }
5820        if out.orphaned_worktrees > 0 {
5821            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
5822        }
5823        let detail = if extra.is_empty() {
5824            String::new()
5825        } else {
5826            format!(" ({})", extra.join(", "))
5827        };
5828        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
5829    }
5830    if out.external_merges_recorded > 0 {
5831        tracing::info!(
5832            "housekeep: recorded {} run(s) as merged externally",
5833            out.external_merges_recorded
5834        );
5835    }
5836    if out.stale_pr_states_repaired > 0 {
5837        tracing::info!(
5838            "housekeep: rewrote {} run record(s) whose pull request had already settled",
5839            out.stale_pr_states_repaired
5840        );
5841    }
5842    if out.cache_files > 0 {
5843        tracing::info!(
5844            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
5845            out.cache_files,
5846            out.cache_freed
5847        );
5848    }
5849    if out.questions_abandoned > 0 {
5850        tracing::info!(
5851            "housekeep: abandoned {} question(s) left open by a finished run",
5852            out.questions_abandoned
5853        );
5854    }
5855}
5856
5857/// Run [`triage::run_once`] and log whatever it did, the same "only when
5858/// there is something to say" rule [`janitor`] follows for its own report.
5859///
5860/// Called at the same idle points as [`janitor`] - once per full poll
5861/// interval, never mid-attempt - for the same reason: it is not liveness
5862/// critical, and a task's own `hold_reason` string is the one thing this
5863/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
5864/// tick for no benefit.
5865async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
5866    let questions = Questions::at(home.join("questions"));
5867    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
5868    if report.is_empty() {
5869        return;
5870    }
5871    if !report.quarantined.is_empty() {
5872        tracing::info!(
5873            "triage: held {} blocked task(s) whose blocked-on task or \
5874             question no longer exists: {}",
5875            report.quarantined.len(),
5876            report.quarantined.join(", ")
5877        );
5878    }
5879    if !report.resumed.is_empty() {
5880        tracing::info!(
5881            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
5882            report.resumed.len(),
5883            report.resumed.join(", ")
5884        );
5885    }
5886    if !report.asked.is_empty() {
5887        tracing::info!(
5888            "triage: asked about {} held task(s): {}",
5889            report.asked.len(),
5890            report.asked.join(", ")
5891        );
5892    }
5893    if !report.answered.is_empty() {
5894        tracing::info!(
5895            "triage: applied {} operator answer(s): {}",
5896            report.answered.len(),
5897            report.answered.join(", ")
5898        );
5899    }
5900}
5901
5902/// The free-space gate: what stands between this task and a new run, if
5903/// anything. `Some(reason)` holds the task; `None` lets it start.
5904///
5905/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
5906/// the operator opted out. A measurement failure is a gate, not a pass: both
5907/// sides of "cannot tell" are served by not starting.
5908pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
5909    disk_gate_at(repo, config, crate::run::home)
5910}
5911
5912pub(crate) fn disk_gate_at(
5913    repo: &Path,
5914    config: &Config,
5915    home: impl FnOnce() -> PathBuf,
5916) -> Option<String> {
5917    let measure = if crate::build_target::isolated(config) {
5918        crate::disk::managed_free_bytes
5919    } else {
5920        crate::disk::free_bytes
5921    };
5922    disk_gate_with(repo, config, home, measure)
5923}
5924
5925/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
5926/// test can assert the exact wiring `attempt` runs - config's threshold in,
5927/// task-holding reason out - without asking the real machine's disk anything.
5928fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
5929    repo: &Path,
5930    config: &Config,
5931    home: impl FnOnce() -> PathBuf,
5932    free_bytes: F,
5933) -> Option<String> {
5934    let min = config.disk.min_free_bytes;
5935    if min == 0 {
5936        return None;
5937    }
5938    let output = match config.verify.build_cache {
5939        BuildCache::Shared => config.cache_dir(),
5940        BuildCache::Isolated => Some(home()),
5941    };
5942    let default_worktree_root;
5943    let worktree_root = match config.graph.worktree_root.as_deref() {
5944        Some(root) => root,
5945        None => {
5946            default_worktree_root = crate::run::default_worktree_root();
5947            &default_worktree_root
5948        }
5949    };
5950    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
5951        .into_iter()
5952        .flatten()
5953    {
5954        let probe = if path == repo {
5955            path
5956        } else {
5957            path.ancestors().find(|p| p.exists()).unwrap_or(path)
5958        };
5959        let reason = match free_bytes(probe) {
5960            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
5961            Err(e) => Some(crate::disk::unmeasured_in(
5962                probe,
5963                &e,
5964                &config.graph.language,
5965            )),
5966        };
5967        if reason.is_some() {
5968            return reason;
5969        }
5970    }
5971    None
5972}
5973
5974/// How long to wait before offering another task when a run lost a seat to a
5975/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
5976/// could read, or carried nothing at all. Long enough that a quota outage
5977/// cannot burn through a whole backlog in the few seconds each doomed attempt
5978/// takes to fail; short enough that a quota which clears early is not left
5979/// idle for the fallback's sake.
5980const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
5981
5982/// Longest a parsed reset hint may push the wait out to. The hint comes from
5983/// the CLI's own words, not a contract, so a parsing slip that lands a day
5984/// away must not leave the loop asleep for a day.
5985const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
5986
5987/// How long [`poll`] should wait before offering the next task, after a run
5988/// lost at least one seat to a rate limit.
5989///
5990/// Pure and separate from the loop so the policy can be exercised without a
5991/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
5992/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
5993/// nothing to parse, or the parsed time has already passed; `cap` bounds how
5994/// far a parsed hint is trusted to push the wait out.
5995fn quota_wait(
5996    reset_at: Option<Timestamp>,
5997    now: Timestamp,
5998    fallback: Duration,
5999    cap: Duration,
6000) -> Duration {
6001    match reset_at {
6002        Some(at) if at > now => {
6003            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6004            Duration::from_secs(secs).min(cap)
6005        }
6006        _ => fallback,
6007    }
6008}
6009
6010/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6011///
6012/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6013/// explains why parsing it exactly "would be a bug factory" — so this only
6014/// recognises the shapes actually observed in the wild, and returns `None`
6015/// for anything else rather than guess at a format nobody has seen.
6016///
6017/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6018/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6019/// said it, not from whenever this loop happens to read it: anchoring on `now`
6020/// would push the reset later on every read and would read an already-elapsed
6021/// reset as still in the future. (A long hint is still clamped by
6022/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6023fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6024    parse_reset_hint_zoned(text, now)
6025        .or_else(|| parse_reset_hint_dated(text))
6026        .or_else(|| parse_reset_hint_relative(text, recorded))
6027}
6028
6029/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6030/// optional but at least one required, in that order. A bare number or any
6031/// unknown unit is refused.
6032fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6033    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6034    let mut rest = rest.trim();
6035    if rest.is_empty() {
6036        return None;
6037    }
6038    let mut total: i64 = 0;
6039    let mut matched = false;
6040    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6041        if let Some((digits, tail)) = rest.split_once(unit)
6042            && !digits.is_empty()
6043            && digits.bytes().all(|b| b.is_ascii_digit())
6044        {
6045            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6046            rest = tail;
6047            matched = true;
6048        }
6049    }
6050    if !rest.is_empty() || !matched {
6051        return None;
6052    }
6053    recorded
6054        .checked_add(jiff::SignedDuration::from_secs(total))
6055        .ok()
6056}
6057
6058/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6059/// case-insensitive) into a 24-hour hour and minute. Shared by every
6060/// reset-hint shape below.
6061fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6062    let clock = clock.trim().to_lowercase();
6063    let (digits, pm) = clock
6064        .strip_suffix("am")
6065        .map(|d| (d, false))
6066        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6067    let (h, m) = digits.trim().split_once(':')?;
6068    let mut hour: i8 = h.trim().parse().ok()?;
6069    let minute: i8 = m.trim().parse().ok()?;
6070    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6071        return None;
6072    }
6073    if pm && hour != 12 {
6074        hour += 12;
6075    } else if !pm && hour == 12 {
6076        hour = 0;
6077    }
6078    Some((hour, minute))
6079}
6080
6081/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6082/// and a zone, never a date. A clock reading already past today is read as
6083/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6084/// the window rolled over while nothing was watching.
6085fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6086    let open = text.find('(')?;
6087    let close = text.rfind(')')?;
6088    if close <= open {
6089        return None;
6090    }
6091    let zone = text[open + 1..close].trim();
6092    let (hour, minute) = parse_12h_clock(&text[..open])?;
6093    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6094    let candidate = now
6095        .to_zoned(tz)
6096        .with()
6097        .hour(hour)
6098        .minute(minute)
6099        .second(0)
6100        .millisecond(0)
6101        .microsecond(0)
6102        .nanosecond(0)
6103        .build()
6104        .ok()?;
6105    let mut at = candidate.timestamp();
6106    if at <= now {
6107        at += jiff::SignedDuration::from_hours(24);
6108    }
6109    Some(at)
6110}
6111
6112/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6113/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6114/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6115/// "already past today" correction to make: the year already disambiguates
6116/// it. Scanned as a five-word window so it can be pulled out of the middle
6117/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6118/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6119/// any other timestamp with no zone attached.
6120fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6121    let words: Vec<&str> = text.split_whitespace().collect();
6122    if words.len() < 5 {
6123        return None;
6124    }
6125    (0..=words.len() - 5)
6126        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6127}
6128
6129/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6130/// parenthesis right after the window is refused rather than ignored — it
6131/// reads as an explicit zone annotation on a shape that otherwise carries
6132/// none, and guessing UTC anyway would be exactly the silent misread this
6133/// module's parsing otherwise avoids.
6134fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6135    if trailing.is_some_and(|next| next.starts_with('(')) {
6136        return None;
6137    }
6138    let month = month_number(window[0])?;
6139    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6140    let day_digits = ["st", "nd", "rd", "th"]
6141        .iter()
6142        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6143    let day: i8 = day_digits.parse().ok()?;
6144    let year_token = window[2];
6145    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6146        return None;
6147    }
6148    let year: i16 = year_token.parse().ok()?;
6149    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6150    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6151    // reusing the same 12-hour clock reader the bracketed shape uses.
6152    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6153    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6154    let date = jiff::civil::Date::new(year, month, day).ok()?;
6155    let candidate = date
6156        .at(hour, minute, 0, 0)
6157        .to_zoned(jiff::tz::TimeZone::UTC)
6158        .ok()?;
6159    Some(candidate.timestamp())
6160}
6161
6162/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6163/// case-insensitively, into a 1-based month number.
6164fn month_number(name: &str) -> Option<i8> {
6165    const NAMES: [&str; 12] = [
6166        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6167    ];
6168    let lower = name.to_lowercase();
6169    NAMES
6170        .iter()
6171        .position(|n| *n == lower.as_str())
6172        .map(|i| i as i8 + 1)
6173}
6174
6175/// Test probe for the shared resume policy's review-budget exclusion.
6176#[cfg(test)]
6177fn exhausted_review_budget(state: &RunState) -> bool {
6178    // A run whose task-head publication failed has nothing left to review:
6179    // resuming it only retries the publication, so it is never "exhausted".
6180    !crate::handover::can_resume(state)
6181        && state.status == RunStatus::Blocked
6182        && !state.released()
6183        && state.retired_to.is_none()
6184}
6185
6186/// This task's *most recent* run, if resuming it would actually make
6187/// progress. `short` is only for the warning's own message.
6188///
6189/// Only ever `runs.last()` — never a search back through older history.
6190/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6191/// mint, oldest first, and every entry before the last one was already
6192/// superseded at the moment it was minted: the daemon only ever starts a new
6193/// run when the previous one was not worth resuming (unresumable, exhausted,
6194/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6195/// opens a fresh review-only run alongside an older, already-failed
6196/// competition. Searching further back would let an old run that merely
6197/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6198/// behind, say — get resumed instead of the fresh competition
6199/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6200/// nothing asked to revisit.
6201///
6202/// Two runs paid for the "prefer resuming over restarting" half of this
6203/// lesson, which is why this still checks `runs.last()` rather than always
6204/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6205/// task a moment later, duplicating two and a half hours of agent work. Then
6206/// b25f stalled on a judge that timed out and one that answered with no JSON
6207/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6208/// **one second** later, buying three fresh implementations to reach the
6209/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6210/// the second case: a stall is terminal, and its cheap recovery re-asks only
6211/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6212/// that is technically `resumable()` but provably cannot progress must not
6213/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6214/// no-op instead of the fresh competition it promises.
6215///
6216/// A load failure is warned about rather than silently read as "not
6217/// resumable": the alternative is exactly what let a schema mismatch on run
6218/// `eba2` fall through to a full re-competition with nobody told why.
6219/// `crate::conduct` is what actually offers a better answer than
6220/// `Runner::start` here (see `Recovery::Review`), once this task's next
6221/// failure shows it up as `held`/`failed` with the run state unreadable.
6222fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6223    unfinished_run_with(runs, short, RunState::load)
6224}
6225
6226/// [`unfinished_run`] with an injected state reader. Tests provide their
6227/// fixtures directly rather than touching the process-global run home.
6228pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6229where
6230    F: FnMut(&str) -> Result<RunState>,
6231{
6232    let mut id = runs.last()?.clone();
6233    let mut visited = std::collections::BTreeSet::new();
6234    let mut repo = None;
6235    loop {
6236        if !runs.contains(&id) || !visited.insert(id.clone()) {
6237            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6238            return None;
6239        }
6240        let state = match load(&id) {
6241            Ok(state) if state.id == id => state,
6242            Ok(_) => return None,
6243            Err(e) => {
6244                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6245                return None;
6246            }
6247        };
6248        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6249            return None;
6250        }
6251        repo = Some(state.repo.clone());
6252        if let Some(authority) = state.retired_to {
6253            id = authority;
6254            continue;
6255        }
6256        return (crate::handover::can_resume(&state)
6257            && state.liveness(false) != crate::run::Liveness::Live)
6258            .then_some(id);
6259    }
6260}
6261
6262/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6263/// that [`attempt`] will resume it on its own?
6264///
6265/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6266/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6267/// injected reader like its sibling. An unreadable run is not awaiting
6268/// anything: it keeps going to the conductor as before.
6269fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6270where
6271    F: FnOnce(&str) -> Result<RunState>,
6272{
6273    // `Failed` stays: a record an older build wrote for a parked run.
6274    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6275        || task.fresh_start
6276        || task.review_branch.is_some()
6277    {
6278        return false;
6279    }
6280    let Some(id) = task.execution_runs().last() else {
6281        return false;
6282    };
6283    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6284}
6285
6286/// Which of the three ways [`attempt`] can mint or continue a run this task
6287/// should use.
6288#[derive(Debug, Clone, PartialEq, Eq)]
6289enum Starter {
6290    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6291    /// and that still exists.
6292    Review(String),
6293    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6294    Resume(String),
6295    /// `crate::graph::Runner::start`: a fresh competition.
6296    Start,
6297}
6298
6299/// A second bound independent of inputs and the resettable failure counter.
6300/// Count execution and failed-startup recovery records once per run. Startup
6301/// failures can retain unrecorded preparation assets without an execution pass.
6302/// Unknown history is not evidence that a new set of worktrees is affordable.
6303fn retained_attempt_hold(
6304    task: &Task,
6305    starter: &Starter,
6306    limit: usize,
6307    mut load: impl FnMut(&str) -> Result<RunState>,
6308) -> Option<String> {
6309    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6310        return None;
6311    }
6312    let mut retained = 0;
6313    for id in task
6314        .runs
6315        .iter()
6316        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6317        .collect::<std::collections::BTreeSet<_>>()
6318    {
6319        let state = match load(id) {
6320            Ok(state) if state.id == *id => state,
6321            _ => {
6322                return Some(format!(
6323                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6324                ));
6325            }
6326        };
6327        if state.retired_to.is_some() || state.released() {
6328            continue;
6329        }
6330        // Neither a completed status nor an empty candidate array proves that
6331        // all recovery sources (including unrecorded preparation) were retired.
6332        retained += 1;
6333    }
6334    (retained >= limit).then(|| format!(
6335        "[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."
6336    ))
6337}
6338
6339/// A selected public implementation overrides every historical candidate and pin.
6340fn selected_starter(
6341    selected: &crate::pr_recovery::Selection,
6342    previous: Option<&RunState>,
6343    unfinished: Option<&str>,
6344) -> Starter {
6345    if let Some(id) = unfinished
6346        && previous.is_some_and(|r| {
6347            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6348        })
6349    {
6350        Starter::Resume(id.to_owned())
6351    } else {
6352        Starter::Review(selected.branch.clone())
6353    }
6354}
6355
6356/// The owner's answer to this branch's divergence question, consumed from the
6357/// task so a later, different divergence asks again. The runner applies it
6358/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6359fn take_divergence_answer(
6360    branch: &str,
6361    remote: &str,
6362    task: &mut Task,
6363) -> Option<crate::reconcile::Choice> {
6364    let summary = crate::reconcile::summary_for(branch, remote);
6365    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6366        (a.question == summary)
6367            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6368            .flatten()
6369            .map(|c| (i, c))
6370    })?;
6371    task.answers.remove(idx);
6372    Some(choice)
6373}
6374
6375/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6376/// this attempt should use. Pure, and separate from [`attempt`], so the
6377/// routing itself is assertable without spawning a real graph or a git
6378/// process: `attempt`'s own `crate::git::branch_exists` call has already
6379/// happened by the time this is called.
6380///
6381/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6382/// whose branch is gone falls all the way through to [`Starter::Start`], not
6383/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6384/// old (likely `Blocked`) run in the first place, and a branch that vanished
6385/// out from under that choice is not evidence resuming it would fare better.
6386fn choose_starter(
6387    review_branch: Option<&str>,
6388    branch_exists: bool,
6389    unfinished: Option<&str>,
6390) -> Starter {
6391    match review_branch {
6392        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6393        Some(_) => Starter::Start,
6394        None => match unfinished {
6395            Some(id) => Starter::Resume(id.to_owned()),
6396            None => Starter::Start,
6397        },
6398    }
6399}
6400
6401/// Reuse a compatible latest review owner instead of taking its checked-out
6402/// branch into a new run. Different branches and changed criteria still use
6403/// the ordinary review/takeover policy.
6404fn review_retry_starter(
6405    task: &Task,
6406    previous: Option<&RunState>,
6407    branch: Option<&str>,
6408    exists: bool,
6409    unfinished: Option<&str>,
6410) -> Starter {
6411    if let Some(run) = previous
6412        && unfinished == Some(run.id.as_str())
6413        && run.reviewed_commits.is_some()
6414        && branch.is_some_and(|branch| {
6415            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6416        })
6417        && may_resume_run(run, task)
6418    {
6419        return Starter::Resume(run.id.clone());
6420    }
6421    match (branch, unfinished, &task.review_of) {
6422        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6423        _ => choose_starter(branch, exists, unfinished),
6424    }
6425}
6426
6427/// A retained review is valid only while its authored criteria still match.
6428fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6429    task.review_branch
6430        .as_deref()
6431        .filter(|&branch| match &task.review_instruction {
6432            Some(authored) => *authored == task.instruction,
6433            // Legacy retained branches must agree with their prior run; only an
6434            // explicitly pinned review can proceed without recoverable provenance.
6435            None => previous.map_or_else(
6436                || task.review_of.as_deref() == Some(branch),
6437                |run| compatible_run_instruction(run, task),
6438            ),
6439        })
6440}
6441
6442/// A current explicit pin can select an otherwise incompatible run. Edits
6443/// and subsequent approvals invalidate pins selected for earlier criteria.
6444fn may_resume_run(run: &RunState, task: &Task) -> bool {
6445    if !task.assignment_accepts(run) {
6446        return false;
6447    }
6448    task.resume_override
6449        .as_ref()
6450        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6451        || compatible_run_instruction(run, task)
6452}
6453
6454/// Review scaffolding is execution context, not evidence of an operator edit.
6455pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6456    if let Some(authored) = &run.task_instruction {
6457        return compatible_instruction(authored, task);
6458    }
6459    if compatible_instruction(&run.instruction, task) {
6460        return true;
6461    }
6462    // Recognize only the existing generated review shapes on legacy runs.
6463    // Ordinary authored text with a similar heading is left intact.
6464    if run.reviewed_commits.is_some() {
6465        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6466            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6467        }
6468        if let Some(branch) = &task.review_of {
6469            let canonical = format!(
6470                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6471            );
6472            let generated = format!(
6473                "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"
6474            );
6475            return task.instruction == canonical && run.instruction.starts_with(&generated);
6476        }
6477    }
6478    false
6479}
6480
6481/// Compare authored instructions, excluding answer blocks appended by the daemon.
6482pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6483    strip_answers_block(old, task) == task.instruction
6484}
6485
6486/// Which repository a task runs in. A task that names none — the normal case
6487/// for one filed from a phone — runs in the daemon's own default.
6488fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6489    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6490        return fallback.to_path_buf();
6491    }
6492    task.repo.clone()
6493}
6494
6495/// The header [`append_answers`] appends operator answers under. Shared with
6496/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6497/// rather than grown a new block on every resume.
6498const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6499
6500/// Render the first `count` answers in the block appended to an instruction.
6501fn answers_block(task: &Task, count: usize) -> String {
6502    let mut s = ANSWERS_HEADER.to_owned();
6503    for a in &task.answers[..count] {
6504        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6505    }
6506    s
6507}
6508
6509/// Render the approval independently of transient task state, so historical
6510/// suffixes remain recognizable after another explicit release.
6511fn resumption_block(r: &crate::queue::Resumption) -> String {
6512    format!(
6513        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6514         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6515        r.generation, r.at, r.instruction, r.answers_through,
6516    )
6517}
6518
6519/// Append audit answers and the latest explicit approval to the instruction.
6520fn append_answers(base: &str, task: &Task) -> String {
6521    let mut s = base.to_owned();
6522    if !task.answers.is_empty() {
6523        s.push_str(&answers_block(task, task.answers.len()));
6524    }
6525    if let Some(r) = &task.resumption {
6526        s.push_str(&resumption_block(r));
6527    }
6528    s
6529}
6530
6531/// Drop the prior answer block only when it is exactly the suffix this task
6532/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6533/// the task author is ordinary instruction text, not a block to remove.
6534fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6535    let mut instruction = instruction;
6536    for approval in task
6537        .resumption
6538        .iter()
6539        .chain(task.resumption_history.iter().rev())
6540    {
6541        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6542            instruction = base;
6543            break;
6544        }
6545    }
6546    for count in (1..=task.answers.len()).rev() {
6547        let block = answers_block(task, count);
6548        if let Some(base) = instruction.strip_suffix(&block) {
6549            return base;
6550        }
6551    }
6552    instruction
6553}
6554
6555/// The instruction handed to `Runner::start`: the task's own text, plus any
6556/// operator answers `crate::conduct` collected for it (see
6557/// [`Task::answers`]), so a decision the operator actually made reaches the
6558/// implementers rather than only clearing the block that was waiting on it.
6559///
6560/// Appended rather than merged into [`Task::instruction`] itself, so the
6561/// task's own record stays exactly what its author wrote.
6562fn instruction_for(task: &Task) -> String {
6563    append_answers(&task.instruction, task)
6564}
6565
6566/// The instruction a resumed run should carry on with: whatever it already
6567/// had, refreshed with the task's *current* operator answers.
6568///
6569/// A resumable run's own `RunState::instruction` predates any answer
6570/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6571/// the behaviour before this function existed — silently drops the very
6572/// decision the operator made to unblock it. Re-stripping any block this
6573/// function appended on an earlier resume before re-appending the current
6574/// list (rather than blindly appending again) is what keeps a task resumed
6575/// three times over three answered questions from carrying the same answer
6576/// three times.
6577fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6578    append_answers(strip_answers_block(old_instruction, task), task)
6579}
6580
6581/// Preserve the producer's verified boundary and target, independent of prose.
6582fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6583    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6584    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6585    if let Some(cause) = task.hold_notice_cause.as_mut() {
6586        cause.target = failure.map(|f| f.target.clone());
6587    }
6588}
6589
6590#[derive(Debug, thiserror::Error)]
6591#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6592struct MissingAttachment {
6593    name: String,
6594    path: PathBuf,
6595}
6596
6597/// The task's attachments as absolute paths, each checked to still exist.
6598fn task_attachments(
6599    queue: &Queue,
6600    task: &Task,
6601) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6602    let paths = queue.attachment_paths(task);
6603    for (name, path) in task.attachments.iter().zip(&paths) {
6604        if !path.is_file() {
6605            return Err(MissingAttachment {
6606                name: name.clone(),
6607                path: path.clone(),
6608            });
6609        }
6610    }
6611    Ok(paths)
6612}
6613
6614/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
6615/// answers before handing it to `Runner` — the actual boundary between
6616/// [`choose_starter`]'s routing and the graph, factored out so it is
6617/// assertable without a real repository, git branch, or agent CLI.
6618///
6619/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
6620/// instruction from the reviewed branch's own commit log because there is no
6621/// task statement to speak of for hand-written work, and splicing operator
6622/// answers into that text would contradict the very message it sends
6623/// reviewers ("there is no task statement").
6624fn prepare_instruction(
6625    starter: &Starter,
6626    old_instruction: Option<&str>,
6627    task: &Task,
6628) -> Option<String> {
6629    match starter {
6630        Starter::Start => Some(instruction_for(task)),
6631        Starter::Resume(_) => Some(resumed_instruction(
6632            old_instruction.expect("a resumed run always has a prior instruction"),
6633            task,
6634        )),
6635        Starter::Review(_) => None,
6636    }
6637}
6638
6639/// Persist a transition. A queue write failure is logged rather than fatal: the
6640/// run already happened, and taking the daemon down would only add a lost
6641/// backlog to a full disk.
6642fn record(queue: &Queue, task: &mut Task) {
6643    if let Err(e) = queue.put(task) {
6644        tracing::error!("could not record task {}: {e:#}", task.short());
6645        let notice = Notice::error(
6646            "loop:record",
6647            format!(
6648                "Task {} state could not be saved: {}. Check the disk.",
6649                task.id,
6650                e.to_string().lines().next().unwrap_or("unknown save error")
6651            ),
6652        )
6653        .link(Link::Task {
6654            id: task.id.clone(),
6655        });
6656        // The queue lives at `<home>/queue`, so its parent is the home.
6657        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
6658            Some(home) => notices::raise_in(home, notice),
6659            None => notices::raise(notice),
6660        }
6661    }
6662}
6663
6664/// Every runnable task, in the order the loop should try them.
6665///
6666/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
6667/// tail exists so that a claim somebody else holds costs the loop the next
6668/// candidate rather than a whole poll interval of idleness.
6669fn runnable(queue: &Queue) -> Vec<Task> {
6670    let mut tasks: Vec<Task> = queue
6671        .list()
6672        .into_iter()
6673        .filter(|t| t.status.runnable())
6674        .collect();
6675    tasks.sort_unstable_by(crate::queue::dispatch_order);
6676    tasks
6677}
6678
6679/// Why a run ended where it did, in one line, for [`Task::last_error`].
6680///
6681/// A stalled run names the seats the quota took out: "out of quota" is not
6682/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
6683/// agent to replace or which plan to top up.
6684///
6685/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
6686/// purpose: unlike `label`'s other callers (an internal log line, an
6687/// already-a-bug fallback message), this string becomes `Task::last_error`
6688/// verbatim, which the phone renders in the same alarm-styled box an
6689/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
6690/// `.err` styling. A bare `verified_noop` there would read exactly like the
6691/// failure this whole feature exists to tell apart from one.
6692fn describe(state: &RunState) -> String {
6693    let p = phrases(&state.config.graph.language);
6694    let mut detail = if state.status == RunStatus::Stalled {
6695        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
6696        seats.sort_unstable();
6697        seats.dedup();
6698        if seats.is_empty() {
6699            p.quorum_lost.to_owned()
6700        } else {
6701            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
6702        }
6703    } else {
6704        format!("{}{}", p.run_ended, state.status.display_label())
6705    };
6706    if let Some(cause) = state.verification_blocking_cause() {
6707        detail.push_str(&format!(" ({cause})"));
6708    } else if let Some(last) = state.events.last() {
6709        // The review loop's "never answered" stop is the one event worth
6710        // translating; it is recognised from structured state, not by
6711        // matching the English event text (which stays as recorded).
6712        let unanswered = state
6713            .reviews
6714            .last()
6715            .filter(|r| {
6716                state.status == RunStatus::Blocked
6717                    && last.node == "review"
6718                    && r.incomplete()
6719                    && r.blocking == 0
6720                    && r.round == state.config.graph.review_rounds
6721                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
6722            })
6723            .map(|r| (r.expected - r.answered, r.round));
6724        match unanswered {
6725            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
6726                detail.push_str(&format!(
6727                    " ({}: {})",
6728                    last.node,
6729                    (p.reviewers_never_answered)(missing, rounds)
6730                ));
6731            }
6732            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
6733        }
6734    }
6735    detail.push_str(&format!(" [run {}]", state.id));
6736    detail
6737}
6738
6739/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
6740///
6741/// The task file lives in the backlog indefinitely; a diagnostic is an
6742/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
6743/// stay small regardless of how much a gate command or a candidate printed.
6744const DIAGNOSTIC_MAX: usize = 4_000;
6745
6746/// Tail kept from a single failing command's output inside a diagnostic.
6747/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
6748/// pointer for a human deciding whether to go read the full artifact by hand,
6749/// not a replacement for reading it.
6750const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
6751
6752/// Assemble a bounded diagnostic excerpt from a held task's own run, so
6753/// `magi task show` says more than the one-line reason in [`describe`].
6754///
6755/// The one-liner answers "where did the run stop"; this answers "what would a
6756/// human have found opening `artifacts/` by hand" — the point of the whole
6757/// feature is the case that one-liner actively misleads on: a run held as "no
6758/// candidate produced a change" can mean the implementer actually finished
6759/// the task (opened a PR, merged it, tagged a release) and only left a clean
6760/// local worktree behind, which reads as "nothing happened" unless someone
6761/// goes and reads what the agent actually said. `None` when the run carries
6762/// none of the three shapes this recognises — an ordinary run held for
6763/// something not diagnosable from `RunState` alone still explains itself
6764/// through `Task::last_error`.
6765fn diagnostic(state: &RunState) -> Option<String> {
6766    let mut parts: Vec<String> = Vec::new();
6767
6768    // Gate failure: which check(s), and the tail of what each printed.
6769    for o in state.gate.iter().filter(|o| !o.ok()) {
6770        parts.push(format!(
6771            "gate `{}` failed ({}):\n{}",
6772            o.command,
6773            notices::exit_status(o.code),
6774            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
6775        ));
6776    }
6777
6778    // The land loop gave up because the fixer declined while checks were
6779    // still red: the message already names them (see `land::run`).
6780    if let Some(last) = state
6781        .events
6782        .iter()
6783        .rev()
6784        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
6785    {
6786        parts.push(last.message.clone());
6787    }
6788
6789    // No viable candidate: every implementer's own final word, sanitized the
6790    // same way a judge would have read it, so a run that actually finished
6791    // the job does not read as an unexplained failure. A verified no-op is
6792    // called out ahead of its own summary and apart from an ordinary
6793    // failure's `why` — this is the one candidate shape whose diagnostic a
6794    // human is expected to actually judge, not just skim.
6795    if state.viable().is_empty() {
6796        for c in &state.candidates {
6797            if let Some(evidence) = &c.verified_noop {
6798                parts.push(format!(
6799                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
6800                    c.label
6801                ));
6802            } else if !c.summary.trim().is_empty() {
6803                parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
6804            } else if let Some(why) = &c.failed {
6805                parts.push(format!("candidate {}: {why}", c.label));
6806            }
6807        }
6808    }
6809
6810    if parts.is_empty() {
6811        return None;
6812    }
6813    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
6814    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
6815    // back slightly over. Leave it enough room to always land under the
6816    // limit.
6817    Some(crate::run::tail(
6818        &parts.join("\n\n"),
6819        DIAGNOSTIC_MAX.saturating_sub(100),
6820    ))
6821}
6822
6823/// Stable lower-case name for a run status, for an internal log line and the
6824/// "graph stopped without reaching a terminal status" bug message in
6825/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
6826/// doc for why that one reads [`RunStatus::display_label`] instead. One
6827/// definition of a status's name, on the type that owns it: this table used
6828/// to live here as a second copy, and a status renamed in one place would
6829/// have gone on reading correctly in the other.
6830fn label(status: RunStatus) -> &'static str {
6831    status.as_str()
6832}
6833
6834/// Parse a merge mode override.
6835pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
6836    match mode {
6837        "none" => Ok(MergeMode::None),
6838        "local" => Ok(MergeMode::Local),
6839        "pr" => Ok(MergeMode::Pr),
6840        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
6841    }
6842}
6843
6844/// Take the status lock, recovering from a poisoned one.
6845///
6846/// A panic elsewhere must not silently stop the heartbeat: the status is plain
6847/// data, and the worst a poisoned lock can hold is a stale timestamp.
6848fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
6849    mutex
6850        .lock()
6851        .unwrap_or_else(std::sync::PoisonError::into_inner)
6852}
6853
6854#[cfg(test)]
6855mod tests {
6856    use super::*;
6857    use crate::queue::{Source, TaskStatus};
6858    use crate::run::{Candidate, CommandOutcome};
6859    use pretty_assertions::assert_eq;
6860
6861    fn task() -> Task {
6862        Task::new(
6863            "add retries".to_owned(),
6864            "add retries".to_owned(),
6865            PathBuf::from("/repo"),
6866            Source::Human,
6867        )
6868    }
6869
6870    #[test]
6871    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
6872        let skips = DispatchSkips::from([
6873            ("a".into(), SkipReason::CoolingDown),
6874            ("b".into(), SkipReason::WaitingOnLanding),
6875            ("c".into(), SkipReason::WaitingOnLanding),
6876            ("d".into(), SkipReason::OrdinaryCapacity),
6877        ]);
6878        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
6879        assert_eq!(wait.runnable, 4);
6880        assert_eq!(
6881            wait.reasons
6882                .iter()
6883                .map(|r| (r.reason.as_str(), r.count))
6884                .collect::<Vec<_>>(),
6885            [
6886                ("waiting_on_landing", 2),
6887                ("cooling_down", 1),
6888                ("ordinary_capacity", 1)
6889            ]
6890        );
6891        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
6892        assert!(
6893            aggregate_dispatch_wait(2, &DispatchSkips::new())
6894                .unwrap()
6895                .reasons
6896                .is_empty()
6897        );
6898    }
6899
6900    #[test]
6901    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
6902        let before = vec!["a".into(), "b".into(), "c".into()];
6903        let allowed = vec![task_with_id("b")];
6904        let skips = interrupt_skips(&before, &allowed);
6905        assert_eq!(
6906            skips,
6907            DispatchSkips::from([
6908                ("a".into(), SkipReason::InterruptGate),
6909                ("c".into(), SkipReason::InterruptGate),
6910            ])
6911        );
6912        let mut previous = DispatchSkips::new();
6913        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6914        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
6915        assert!(!changed_dispatch_skips(&mut previous, skips));
6916        assert!(changed_dispatch_skips(
6917            &mut previous,
6918            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
6919        ));
6920        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
6921    }
6922
6923    #[test]
6924    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
6925        let mut value = serde_json::to_value(Status::new()).unwrap();
6926        value.as_object_mut().unwrap().remove("dispatch_wait");
6927        assert!(
6928            serde_json::from_value::<Status>(value.clone())
6929                .unwrap()
6930                .dispatch_wait
6931                .is_none()
6932        );
6933        assert!(
6934            serde_json::from_value::<Reading>(value.clone())
6935                .unwrap()
6936                .dispatch_wait
6937                .is_none()
6938        );
6939        value["dispatch_wait"] = serde_json::json!({
6940            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
6941        });
6942        let reading = serde_json::from_value::<Reading>(value).unwrap();
6943        assert_eq!(
6944            reading.dispatch_wait.unwrap().reasons[0].reason,
6945            "future_reason"
6946        );
6947    }
6948
6949    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
6950        let job = crate::worker::Job {
6951            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
6952            sequence: 1,
6953            kind: "task".into(),
6954            key: format!("task:{}", request.task),
6955            payload: serde_json::to_value(request).unwrap(),
6956            generation: "a".repeat(64),
6957            version: None,
6958            status: crate::worker::Status::Starting,
6959            result: None,
6960            pid: None,
6961            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
6962            finished_at: None,
6963        };
6964        let dir = home.join("workers/jobs").join(&job.id);
6965        std::fs::create_dir_all(&dir).unwrap();
6966        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
6967        job
6968    }
6969
6970    #[test]
6971    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
6972        let home = tempfile::tempdir().unwrap();
6973        let request = TaskWorker {
6974            opts: Opts::default(),
6975            queue: home.path().join("queue"),
6976            task: "startup".into(),
6977            lane: PermitKind::Ordinary,
6978            standalone: false,
6979        };
6980        let job = starting_task_reservation(home.path(), &request);
6981        let error = task_worker_spawn_error(
6982            home.path(),
6983            &request,
6984            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
6985        )
6986        .expect_err("our own reservation must not turn a failed spawn into a resync");
6987        let active = crate::worker::active(home.path()).unwrap();
6988        assert_eq!(active.len(), 1);
6989        assert_eq!(active[0].id, job.id);
6990        assert_eq!(active[0].status, crate::worker::Status::Starting);
6991        assert!(
6992            crate::worker::control(home.path(), &job.key)
6993                .unwrap()
6994                .is_none()
6995        );
6996        let notices = notices::Notices::at(home.path().join("notifications")).list();
6997        assert_eq!(notices.len(), 1);
6998        assert_eq!(notices[0].key, "loop:worker-startup");
6999        assert!(!notices[0].message.contains("private-error-detail"));
7000        assert!(notices[0].message.contains(&request.task));
7001        assert!(
7002            notices[0]
7003                .message
7004                .contains("could not be started or acknowledged")
7005        );
7006        assert!(notices[0].message.contains("worker.log"));
7007        assert_eq!(
7008            notices[0].link,
7009            Some(Link::Task {
7010                id: request.task.clone()
7011            })
7012        );
7013        assert!(format!("{error:#}").contains("private-error-detail"));
7014    }
7015
7016    #[test]
7017    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7018        let home = tempfile::tempdir().unwrap();
7019        let mut request = TaskWorker {
7020            opts: Opts::default(),
7021            queue: home.path().join("queue"),
7022            task: "handoff".into(),
7023            lane: PermitKind::Ordinary,
7024            standalone: true,
7025        };
7026        let job = starting_task_reservation(home.path(), &request);
7027        request.standalone = false;
7028        task_worker_spawn_error(
7029            home.path(),
7030            &request,
7031            anyhow::anyhow!("operation key is already reserved for a different request"),
7032        )
7033        .expect("a different standalone request is the handoff race, not our startup failure");
7034        let active = crate::worker::active(home.path()).unwrap();
7035        assert_eq!(active.len(), 1);
7036        assert_eq!(active[0].id, job.id);
7037        assert_eq!(active[0].payload, job.payload);
7038        assert!(
7039            notices::Notices::at(home.path().join("notifications"))
7040                .list()
7041                .is_empty()
7042        );
7043    }
7044
7045    #[test]
7046    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7047        let home = tempfile::tempdir().unwrap();
7048        let queue = Queue::at(home.path().join("queue"));
7049        let mut task = task();
7050        task.runs = vec!["previous".into()];
7051        queue.put(&mut task).unwrap();
7052        let request = TaskWorker {
7053            opts: Opts::default(),
7054            queue: home.path().join("queue"),
7055            task: task.id.clone(),
7056            lane: PermitKind::Ordinary,
7057            standalone: false,
7058        };
7059        let job = starting_task_reservation(home.path(), &request);
7060        let claims = current_work(home.path(), Timestamp::now());
7061        assert_eq!(claims.len(), 1);
7062        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7063        assert_eq!(claims[0].run, "previous");
7064        assert!(other_claims_run(&claims, "previous", None));
7065        // Only after confirming the executing caller may admission ignore
7066        // this exact projection. Cleanup continues to observe it as live.
7067        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7068        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7069    }
7070
7071    #[test]
7072    fn admission_excludes_only_the_callers_exact_reservation() {
7073        let own = Current {
7074            worker: Some("own".into()),
7075            task: "same-task".into(),
7076            run: "previous".into(),
7077        };
7078        assert!(!other_claims_run(
7079            std::slice::from_ref(&own),
7080            "previous",
7081            Some("own")
7082        ));
7083        assert!(other_claims_run(
7084            std::slice::from_ref(&own),
7085            "previous",
7086            None
7087        ));
7088        for worker in [None, Some("other".into())] {
7089            let other = Current {
7090                worker,
7091                ..own.clone()
7092            };
7093            assert!(other_claims_run(
7094                &[own.clone(), other],
7095                "previous",
7096                Some("own")
7097            ));
7098        }
7099        let legacy: Current =
7100            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7101        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7102    }
7103
7104    #[test]
7105    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7106        let mut task = task();
7107        let mut run = run_state(RunStatus::Reviewing);
7108        run.task_instruction = Some(task.instruction.clone());
7109        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7110        let branch = "magi/test/B";
7111        run.candidates.push(crate::run::Candidate {
7112            branch: branch.into(),
7113            ..candidate('B', "preserved work", false, None)
7114        });
7115        task.runs = vec![run.id.clone()];
7116        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7117        assert_eq!(
7118            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7119            Starter::Resume(run.id.clone())
7120        );
7121        assert!(matches!(
7122            review_retry_starter(
7123                &task,
7124                Some(&run),
7125                Some("different"),
7126                true,
7127                unfinished.as_deref()
7128            ),
7129            Starter::Review(_)
7130        ));
7131        assert_eq!(
7132            review_retry_starter(
7133                &task,
7134                Some(&run),
7135                Some(branch),
7136                false,
7137                unfinished.as_deref()
7138            ),
7139            Starter::Start
7140        );
7141        task.instruction.push_str(" changed criteria");
7142        assert!(matches!(
7143            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7144            Starter::Review(_)
7145        ));
7146        assert!(matches!(
7147            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7148            Starter::Review(_)
7149        ));
7150    }
7151
7152    #[test]
7153    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7154        let dir = tempfile::tempdir().unwrap();
7155        let queue = Queue::at(dir.path().join("queue"));
7156        let mut task = task();
7157        task.status = TaskStatus::Running;
7158        task.attempts = 1;
7159        queue.put(&mut task).unwrap();
7160        let live = std::collections::BTreeSet::from([task.id.clone()]);
7161        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7162        drop(queue.claim(&task.id).unwrap());
7163        let saved = queue.get(&task.id).unwrap();
7164        assert_eq!(saved.status, TaskStatus::Running);
7165        assert_eq!(saved.attempts, 1);
7166        assert!(saved.last_error.is_none());
7167    }
7168
7169    #[test]
7170    fn standalone_workers_do_not_consume_scheduler_lanes() {
7171        let request = |task: &str, lane, standalone| TaskWorker {
7172            opts: Opts::default(),
7173            queue: PathBuf::from("/queue"),
7174            task: task.to_owned(),
7175            lane,
7176            standalone,
7177        };
7178        let mut jobs = vec![
7179            request("ordinary", PermitKind::Ordinary, false),
7180            request("standalone-urgent", PermitKind::Urgent, true),
7181            request("standalone-ordinary", PermitKind::Ordinary, true),
7182            request("decision", PermitKind::None, false),
7183        ];
7184        assert_eq!(available_slots(&jobs, 2), (1, 1));
7185        jobs.push(request("urgent", PermitKind::Urgent, false));
7186        assert_eq!(available_slots(&jobs, 2), (1, 0));
7187        assert_eq!(available_slots(&jobs, 0), (0, 0));
7188    }
7189
7190    #[test]
7191    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7192        let now = Timestamp::now();
7193        let mut reading = Reading {
7194            pid: Some(std::process::id()),
7195            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7196            ..Reading::default()
7197        };
7198        assert!(!reading.running(now));
7199        assert!(legacy_scheduler_running(&reading, now, 0));
7200        reading.worker_protocol = Some(1);
7201        assert!(!legacy_scheduler_running(&reading, now, 0));
7202    }
7203
7204    #[test]
7205    fn selected_public_head_overrides_historical_resume_and_pin() {
7206        let mut t = task();
7207        let mut old = run_state(RunStatus::Blocked);
7208        let selection = crate::pr_recovery::Selection {
7209            url: "url".into(),
7210            branch: format!("magi/task-{}", t.id),
7211            head: "a".repeat(40),
7212            source_head: None,
7213            source_run: None,
7214            source_proof: None,
7215            disposition: Some(crate::pr_recovery::Disposition::Review),
7216            instruction: t.instruction.clone(),
7217            approved_at: Timestamp::now(),
7218        };
7219        t.resume_override = Some(crate::queue::OperatorResume {
7220            pinned_run: Some(old.id.clone()),
7221            question_id: "choice".into(),
7222            at: Timestamp::now(),
7223            conductor_rehold: None,
7224            forced: false,
7225        });
7226        assert_eq!(
7227            selected_starter(&selection, Some(&old), Some(&old.id)),
7228            Starter::Review(selection.branch.clone())
7229        );
7230        old.pr_recovery = Some(selection.clone());
7231        assert_eq!(
7232            selected_starter(&selection, Some(&old), Some(&old.id)),
7233            Starter::Review(selection.branch.clone())
7234        );
7235        old.reviewed_commits = Some(vec!["implementation".into()]);
7236        assert_eq!(
7237            selected_starter(&selection, Some(&old), Some(&old.id)),
7238            Starter::Resume(old.id.clone())
7239        );
7240        let mut changed = selection.clone();
7241        changed.head = "b".repeat(40);
7242        assert_eq!(
7243            selected_starter(&changed, Some(&old), Some(&old.id)),
7244            Starter::Review(changed.branch)
7245        );
7246    }
7247
7248    #[test]
7249    fn candidate_transplant_failure_is_one_actionable_hold() {
7250        let dir = tempfile::tempdir().unwrap();
7251        let q = Queue::at(dir.path().join("queue"));
7252        let mut t = task();
7253        let mut state = run_state(RunStatus::Blocked);
7254        state.event("prep", "cannot apply referenced commit: conflict");
7255        state.prep_failure = Some("conflict".into());
7256        t.start(state.id.clone());
7257        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7258        assert_eq!(t.attempts, 1);
7259        assert_eq!(t.status, TaskStatus::Held);
7260        assert!(t.operator_held());
7261        assert!(!t.status.runnable());
7262        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7263        let first = t.chat_notice_key().unwrap();
7264        t.chat_notices.push(first.clone());
7265        t.release_operator("test", None);
7266        state.id = "another-unprepared-run".into();
7267        t.start(state.id.clone());
7268        finish_attempt(
7269            3,
7270            &q,
7271            &mut t,
7272            &state,
7273            &[],
7274            Err(anyhow::anyhow!("still conflicts")),
7275        );
7276        assert_eq!(
7277            t.chat_notice_key().as_ref(),
7278            Some(&first),
7279            "no work happened"
7280        );
7281        t.release_operator("test", None);
7282        state.prep_failure = None;
7283        state.status = RunStatus::Failed;
7284        state.begin_pass();
7285        t.start(state.id.clone());
7286        finish_attempt(
7287            1,
7288            &q,
7289            &mut t,
7290            &state,
7291            &[],
7292            Err(anyhow::anyhow!("new gate failure")),
7293        );
7294        let failure = t.chat_notice_key().unwrap();
7295        assert_ne!(failure, first, "approved recovery reached a real failure");
7296        t.release_operator("test", None);
7297        state.begin_pass();
7298        t.start(state.id.clone());
7299        finish_attempt(
7300            1,
7301            &q,
7302            &mut t,
7303            &state,
7304            &[],
7305            Err(anyhow::anyhow!("new failure on resume")),
7306        );
7307        assert_ne!(
7308            t.chat_notice_key().as_ref(),
7309            Some(&failure),
7310            "a new settled pass"
7311        );
7312    }
7313
7314    #[test]
7315    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7316        for source in ["cli", "web"] {
7317            let mut t = task();
7318            let mut run = run_state(RunStatus::Blocked);
7319            run.instruction = "Run A original criteria".into();
7320            run.task_instruction = Some(run.instruction.clone());
7321            t.start(run.id.clone());
7322            t.release_operator("choice", Some("resume-question"));
7323            t.resume_override = Some(crate::queue::OperatorResume {
7324                question_id: "resume-question".into(),
7325                at: Timestamp::now(),
7326                conductor_rehold: None,
7327                forced: true,
7328                pinned_run: Some(run.id.clone()),
7329            });
7330            t.hold_machine(Some("not enough free space to start a run".into()));
7331            let mut unchanged = t.clone();
7332            unchanged
7333                .edit("title changed".into(), unchanged.instruction.clone())
7334                .unwrap();
7335            unchanged.release_operator(source, None);
7336            assert_eq!(
7337                unchanged
7338                    .resume_override
7339                    .as_ref()
7340                    .unwrap()
7341                    .pinned_run
7342                    .as_deref(),
7343                Some(run.id.as_str())
7344            );
7345            assert!(!compatible_run_instruction(&run, &unchanged));
7346            assert!(may_resume_run(&run, &unchanged));
7347
7348            t.edit(
7349                "approved recovery".into(),
7350                "Reuse measured PR head B; fix Clippy; review".into(),
7351            )
7352            .unwrap();
7353            assert!(t.resume_override.is_none());
7354            t.release_operator(source, None);
7355            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7356            assert!(reloaded.resume_override.is_none());
7357            assert!(!may_resume_run(&run, &reloaded));
7358            let unfinished =
7359                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7360                    .filter(|_| may_resume_run(&run, &reloaded));
7361            assert_eq!(
7362                choose_starter(None, false, unfinished.as_deref()),
7363                Starter::Start
7364            );
7365            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7366            assert_eq!(
7367                reloaded.resumption_history[0].question_id.as_deref(),
7368                Some("resume-question")
7369            );
7370
7371            // A revision already persisted with the old approval/pin is also
7372            // invalidated when the new operator release is recorded.
7373            unchanged.instruction = "Reuse measured PR head B".into();
7374            unchanged.hold_machine(Some("disk hold".into()));
7375            unchanged.release_operator(source, None);
7376            assert!(unchanged.resume_override.is_none());
7377            assert!(!may_resume_run(&run, &unchanged));
7378        }
7379    }
7380
7381    #[test]
7382    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7383        let mut t = task();
7384        let mut run = run_state(RunStatus::Blocked);
7385        t.review_of = Some("approved-head".into());
7386        t.instruction =
7387            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7388                .into();
7389        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();
7390        run.reviewed_commits = Some(vec!["Commit log".into()]);
7391        t.start(run.id.clone());
7392        t.hold_machine(Some("interrupted review".into()));
7393        t.release_operator("cli", None);
7394        assert!(
7395            compatible_run_instruction(&run, &t),
7396            "legacy explicit review remains resumable"
7397        );
7398        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7399            .filter(|_| compatible_run_instruction(&run, &t));
7400        assert_eq!(
7401            choose_starter(None, false, unfinished.as_deref()),
7402            Starter::Resume(run.id.clone())
7403        );
7404        run.task_instruction = Some(t.instruction.clone());
7405        assert!(compatible_run_instruction(&run, &t));
7406        let reloaded: RunState =
7407            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7408        assert!(compatible_run_instruction(&reloaded, &t));
7409        t.edit(
7410            "new approved head".into(),
7411            "Reuse measured PR head B".into(),
7412        )
7413        .unwrap();
7414        assert!(!compatible_run_instruction(&run, &t));
7415
7416        // Legacy recovery reviews retain the task criteria ahead of the log.
7417        t.review_of = None;
7418        t.instruction = "Fix Clippy on approved head".into();
7419        run.task_instruction = None;
7420        run.instruction = format!(
7421            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7422            t.instruction
7423        );
7424        assert!(compatible_run_instruction(&run, &t));
7425        t.instruction.push('\n');
7426        assert!(
7427            compatible_run_instruction(&run, &t),
7428            "legacy generated review trimmed the original criteria"
7429        );
7430        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7431        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7432        t.edit("new plan".into(), "Reuse measured PR head B".into())
7433            .unwrap();
7434        assert!(review_branch_for(&t, Some(&run)).is_none());
7435        assert!(!compatible_run_instruction(&run, &t));
7436        t.review_branch = Some("approved-head".into());
7437        t.review_instruction = None;
7438        assert!(
7439            review_branch_for(&t, Some(&run)).is_none(),
7440            "legacy retained candidate cannot replace a revised approved head"
7441        );
7442    }
7443
7444    #[test]
7445    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7446        let home = crate::run::test_home();
7447        crate::run::pin_test_home();
7448        let dir = tempfile::tempdir().unwrap();
7449        let queue = Queue::at(dir.path().join("queue"));
7450        for resume in [true, false] {
7451            let state = run_state(RunStatus::Blocked);
7452            let mut t = task();
7453            t.start(state.id.clone());
7454            let action = if resume {
7455                ask::ChoiceAction::Resume {
7456                    run: state.id.clone(),
7457                }
7458            } else {
7459                ask::ChoiceAction::Requeue
7460            };
7461            let mut q = action_question(&state.id, action);
7462            q.status = ask::QuestionStatus::Open;
7463            q.answer = None;
7464            q.answered_at = None;
7465            t.fail("run stopped with a question", 3);
7466            hold_if_runnable(&queue, &mut t);
7467            assert!(t.operator_decided_at.is_none());
7468            assert!(t.operator_held());
7469            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7470            let expected = if resume {
7471                ActionDecision::Resume(state.id.clone())
7472            } else {
7473                ActionDecision::Requeue
7474            };
7475            assert_eq!(
7476                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7477                expected
7478            );
7479            t.hold_manual(Some("later explicit hold".into()));
7480            assert_eq!(
7481                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7482                ActionDecision::Stale
7483            );
7484        }
7485    }
7486
7487    #[test]
7488    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7489        let mut t = task();
7490        t.answers.push(crate::queue::AnsweredQuestion {
7491            question: "Inspect the remote?".into(),
7492            answer: "Inspect then wait".into(),
7493        });
7494        let old = instruction_for(&t);
7495        assert!(compatible_instruction(&old, &t));
7496        t.instruction = "Reuse approved PR head and review".into();
7497        t.release_operator("cli", None);
7498        assert!(!compatible_instruction(&old, &t));
7499        let approved = instruction_for(&t);
7500        assert!(approved.contains("waiting premises are superseded"));
7501        assert!(compatible_instruction(&approved, &t));
7502        assert_eq!(resumed_instruction(&approved, &t), approved);
7503        t.release_operator("web", None);
7504        assert!(compatible_instruction(&approved, &t));
7505        assert_eq!(t.resumption_history.len(), 1);
7506        t.start("run".into());
7507        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7508    }
7509
7510    /// A run that stopped on an infrastructure wait asked no agent anything:
7511    /// the task is held by the machine under a `[resource]` reason (resumable,
7512    /// re-checked by triage), and the attempt it started is given back.
7513    #[test]
7514    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7515        let mut state = RunState::new(
7516            PathBuf::from("/repo"),
7517            "main".into(),
7518            "base".into(),
7519            "task".into(),
7520            Config::default(),
7521        );
7522        state.status = RunStatus::Landing;
7523        state.parked = true;
7524        state.pr_pushed_head = Some("head".into());
7525        state.land_unrelated = Some(
7526            serde_json::from_value(serde_json::json!({
7527                "head": "head", "question": "ci-question",
7528                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7529            }))
7530            .unwrap(),
7531        );
7532        let mut t = task();
7533        t.start(state.id.clone());
7534        let verdict = Verdict {
7535            status: RunStatus::Landing,
7536            left_pr: true,
7537            quota_hit: false,
7538            parked: true,
7539            no_viable_candidates: false,
7540        };
7541        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7542        assert_eq!(t.attempts, 0);
7543        assert_eq!(t.status, TaskStatus::Held);
7544        assert!(!t.operator_held());
7545        assert!(
7546            t.hold_reason
7547                .as_deref()
7548                .unwrap()
7549                .starts_with("[ci-unrelated]")
7550        );
7551        // A second settlement must not refund an earlier task attempt.
7552        t.attempts = 1;
7553        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7554        assert_eq!(t.attempts, 1);
7555        assert_eq!(t.passes.len(), 1);
7556        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
7557        state.pr_pushed_head = Some("new-head".into());
7558        state.parked = false;
7559        state.status = RunStatus::Blocked;
7560        let stale = Verdict {
7561            status: RunStatus::Blocked,
7562            parked: false,
7563            ..verdict
7564        };
7565        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
7566        assert_eq!(t.attempts, 1);
7567        // A new execution pass can refund its own newly charged attempt.
7568        state.begin_pass();
7569        state.begin_pass();
7570        state.status = RunStatus::Landing;
7571        state.parked = true;
7572        state.pr_pushed_head = Some("head".into());
7573        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
7574        assert_eq!(t.attempts, 0);
7575        assert_eq!(t.passes.len(), 2);
7576    }
7577
7578    #[test]
7579    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
7580        let mut state = run_state(RunStatus::Failed);
7581        state
7582            .quota
7583            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
7584        state.begin_pass();
7585        let mut t = task();
7586        t.start(state.id.clone());
7587        reclaim(&mut t, Some(state), 2, "en");
7588        assert_eq!(t.attempts, 1);
7589    }
7590
7591    #[test]
7592    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
7593        let mut state = run_state(RunStatus::Blocked);
7594        let losses: Vec<_> = ["alpha", "beta"]
7595            .into_iter()
7596            .enumerate()
7597            .map(|(i, agent)| {
7598                QuotaLoss::from_report(
7599                    format!("advisor-{i}"),
7600                    "advise",
7601                    Some(&crate::agent::Quota {
7602                        cause: crate::agent::QuotaCause::Authentication,
7603                        agent: agent.to_owned(),
7604                        reset: None,
7605                    }),
7606                )
7607            })
7608            .collect();
7609        crate::graph::block_machine_outage(&mut state, "advise", &losses);
7610        state.quota = losses;
7611        let mut t = task();
7612        t.start(state.id.clone());
7613        let verdict = Verdict {
7614            status: state.status,
7615            left_pr: false,
7616            quota_hit: true,
7617            parked: false,
7618            no_viable_candidates: true,
7619        };
7620        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
7621        assert_eq!(t.attempts, 0);
7622        assert_eq!(t.status, TaskStatus::Held);
7623        assert!(!t.operator_held());
7624        let reason = t.hold_reason.as_deref().unwrap();
7625        assert!(reason.starts_with("[authentication]"));
7626        assert!(
7627            reason.contains("alpha")
7628                && reason.contains("beta")
7629                && reason.contains("re-authenticate")
7630        );
7631        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
7632        // Orphan recovery uses the same settlement and cannot spend an attempt.
7633        let mut orphan = task();
7634        orphan.start(state.id.clone());
7635        reclaim(&mut orphan, Some(state), 2, "en");
7636        assert_eq!(orphan.attempts, 0);
7637        assert_eq!(orphan.status, TaskStatus::Held);
7638    }
7639
7640    #[test]
7641    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
7642        let mut state = RunState::new(
7643            PathBuf::from("/repo"),
7644            "main".to_owned(),
7645            "abc1234".to_owned(),
7646            "task".to_owned(),
7647            Config::default(),
7648        );
7649        state.status = RunStatus::Blocked;
7650        state.resource_block = Some(crate::run::ResourceBlock {
7651            cause: crate::run::ResourceBlockCause::Other,
7652            node: "graft".to_owned(),
7653            kind: "shared build cache".to_owned(),
7654            detail: "timed out".to_owned(),
7655            at: jiff::Timestamp::now(),
7656        });
7657        let mut t = task();
7658        t.start("20260902-000000-aaaa".to_owned());
7659        assert_eq!(t.attempts, 1);
7660        let verdict = Verdict {
7661            status: RunStatus::Blocked,
7662            left_pr: false,
7663            quota_hit: false,
7664            parked: false,
7665            no_viable_candidates: false,
7666        };
7667        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
7668        assert_eq!(t.status, TaskStatus::Held);
7669        assert_eq!(t.attempts, 0, "the attempt is refunded");
7670        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
7671        assert!(
7672            !t.operator_held(),
7673            "a machine hold, released without a human"
7674        );
7675
7676        let mut selected = task();
7677        selected.start("20260902-000000-cccc".into());
7678        selected.replacement = Some(crate::merge_decision::Replacement {
7679            question: "fixture".into(),
7680            run: "earlier".into(),
7681            pr: "https://example.invalid/pr/1".into(),
7682            agent: "selected".into(),
7683            context: "fixture".into(),
7684        });
7685        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
7686        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
7687        assert_eq!(selected.attempts, 0);
7688        assert!(
7689            !selected.operator_held(),
7690            "a selected agent also retains a machine resource hold"
7691        );
7692        assert!(
7693            selected
7694                .hold_reason
7695                .as_deref()
7696                .unwrap()
7697                .starts_with("[resource] ")
7698        );
7699
7700        // A park request outranks it: still the operator's doing.
7701        let mut p = task();
7702        p.start("20260902-000000-bbbb".to_owned());
7703        settle_and_diagnose(
7704            &mut p,
7705            Verdict {
7706                parked: true,
7707                ..verdict
7708            },
7709            "parked",
7710            2,
7711            &state,
7712        );
7713        assert_eq!(p.status, TaskStatus::Parked);
7714        assert_eq!(
7715            p.attempts, 0,
7716            "parking refunds once rather than also settling the resource hold"
7717        );
7718    }
7719
7720    #[test]
7721    fn record_failure_notice_links_the_task() {
7722        let dir = tempfile::tempdir().unwrap();
7723        // A regular file where the queue directory should be makes every
7724        // `put` fail, on every platform and whoever runs the test.
7725        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
7726        let queue = Queue::at(dir.path().join("queue"));
7727        let mut t = interrupt_task("rec-fail-1");
7728        record(&queue, &mut t);
7729
7730        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
7731        assert_eq!(found.len(), 1);
7732        assert_eq!(found[0].key, "loop:record");
7733        assert_eq!(
7734            found[0].link,
7735            Some(Link::Task {
7736                id: "rec-fail-1".to_owned()
7737            })
7738        );
7739    }
7740
7741    /// A runnable task marked to interrupt, with an id fixed for assertions
7742    /// rather than the random one [`Task::new`] mints.
7743    fn interrupt_task(id: &str) -> Task {
7744        let mut t = task();
7745        t.id = id.to_owned();
7746        t.interrupt = true;
7747        t
7748    }
7749
7750    /// An ordinary runnable task with an id fixed for assertions.
7751    fn task_with_id(id: &str) -> Task {
7752        let mut t = task();
7753        t.id = id.to_owned();
7754        t
7755    }
7756
7757    /// A runnable task marked `--urgent`, with an id fixed for assertions.
7758    fn urgent_task(id: &str) -> Task {
7759        let mut t = task();
7760        t.id = id.to_owned();
7761        t.urgent = true;
7762        t
7763    }
7764
7765    #[test]
7766    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
7767        let dir = tempfile::tempdir().unwrap();
7768        let queue = Queue::at(dir.path().join("queue"));
7769        let mut parked = task_with_id("parked");
7770        parked.start("run".into());
7771        parked.park("upgrade");
7772        parked.record_pass_at(
7773            "run",
7774            0,
7775            Some(Timestamp::now()),
7776            1,
7777            Some(crate::run::ParkCause::Upgrade {
7778                from: "old".into(),
7779                to: None,
7780            }),
7781        );
7782        let mut fresh = task_with_id("fresh");
7783        fresh.priority = 100;
7784        let mut urgent_task = urgent_task("urgent");
7785        for t in [&mut parked, &mut fresh, &mut urgent_task] {
7786            queue.put(t).unwrap();
7787        }
7788        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7789        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7790        let candidates = runnable(&queue);
7791        assert_eq!(candidates[0].id, parked.id);
7792        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
7793        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
7794        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
7795        drop(first);
7796        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
7797        let next = runnable(&queue)
7798            .into_iter()
7799            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
7800            .unwrap();
7801        assert_eq!(next.task.id, fresh.id);
7802        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
7803        drop(claimed_elsewhere);
7804        drop(next);
7805        assert!(matches!(
7806            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
7807            Err(SkipReason::CoolingDown)
7808        ));
7809    }
7810
7811    #[test]
7812    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
7813        let dir = tempfile::tempdir().unwrap();
7814        let queue = Queue::at(dir.path().join("queue"));
7815        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7816        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7817        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
7818        let mut first = task();
7819        queue.put(&mut first).unwrap();
7820        let stale_plain = queue.get(&first.id).unwrap();
7821        first.set_urgent(true).unwrap();
7822        queue.put(&mut first).unwrap();
7823        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
7824        let mut second = urgent_task("second");
7825        queue.put(&mut second).unwrap();
7826        assert!(matches!(
7827            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
7828            Err(SkipReason::UrgentCapacity)
7829        ));
7830        drop(queue.claim(&second.id).unwrap());
7831        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
7832        drop(dispatched);
7833        let stale_urgent = queue.get(&first.id).unwrap();
7834        first.set_urgent(false).unwrap();
7835        queue.put(&mut first).unwrap();
7836        assert!(matches!(
7837            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
7838            Err(SkipReason::OrdinaryCapacity)
7839        ));
7840        assert_eq!(urgent.available_permits(), 1);
7841        drop(queue.claim(&first.id).unwrap());
7842        drop(occupied);
7843    }
7844
7845    #[test]
7846    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
7847        let dir = tempfile::tempdir().unwrap();
7848        let queue = Queue::at(dir.path().join("queue"));
7849        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
7850        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
7851        let mut t = task();
7852        queue.put(&mut t).unwrap();
7853        for enabled in [true, false] {
7854            let stale = queue.get(&t.id).unwrap();
7855            t.set_urgent(enabled).unwrap();
7856            queue.put(&mut t).unwrap();
7857            assert_ne!(stale.urgent, enabled);
7858            let DispatchClaim {
7859                task: fresh,
7860                claim,
7861                permit,
7862            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
7863            assert_eq!(fresh.urgent, enabled);
7864            assert_eq!(ordinary.available_permits(), usize::from(enabled));
7865            assert_eq!(urgent.available_permits(), usize::from(!enabled));
7866            assert!(queue.claim(&t.id).is_err());
7867            assert_eq!(fresh.attempts, stale.attempts);
7868            drop((claim, permit));
7869            assert_eq!(ordinary.available_permits(), 1);
7870            assert_eq!(urgent.available_permits(), 1);
7871        }
7872        t.set_urgent(true).unwrap();
7873        queue.put(&mut t).unwrap();
7874        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
7875        assert!(matches!(
7876            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7877            Err(SkipReason::UrgentCapacity)
7878        ));
7879        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
7880        drop(queue.claim(&t.id).unwrap());
7881        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
7882        drop(occupied);
7883        assert!(matches!(
7884            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
7885            Err(SkipReason::CoolingDown)
7886        ));
7887        drop(queue.claim(&t.id).unwrap());
7888        let held = queue.claim(&t.id).unwrap();
7889        assert!(matches!(
7890            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7891            Err(SkipReason::ClaimUnavailable)
7892        ));
7893        drop(held);
7894        t.status = TaskStatus::Held;
7895        queue.put(&mut t).unwrap();
7896        assert!(matches!(
7897            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7898            Err(SkipReason::NoLongerRunnable)
7899        ));
7900        drop(queue.claim(&t.id).unwrap());
7901        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
7902        assert!(matches!(
7903            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
7904            Err(SkipReason::RereadFailed)
7905        ));
7906        drop(queue.claim(&t.id).unwrap());
7907        assert_eq!(urgent.available_permits(), 1);
7908    }
7909
7910    /// The land-resume exemption wins outright, whether or not the candidate
7911    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
7912    /// queue behind anything" guarantee cannot be weaker just because the
7913    /// same task was also filed with `--urgent`.
7914    #[test]
7915    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
7916        assert_eq!(permit_kind(true, false), PermitKind::None);
7917        assert_eq!(permit_kind(true, true), PermitKind::None);
7918    }
7919
7920    /// The one property this whole feature exists for: `--urgent` draws from
7921    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
7922    /// ordinary candidate draws from the ordinary pool exactly as before,
7923    /// untouched by the urgent slot's existence.
7924    #[test]
7925    fn permit_kind_separates_urgent_from_ordinary() {
7926        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
7927        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
7928    }
7929
7930    /// The exact wiring `attempt` runs before minting anything: a config's
7931    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
7932    /// Free space is injected rather than asked of the real disk - the point
7933    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
7934    /// is deterministic on every machine this test runs on, never dependent
7935    /// on how full the CI runner's own disk happens to be.
7936    #[test]
7937    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
7938        let cfg = Config::default();
7939        let repo = Path::new("/any/repo/path");
7940
7941        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
7942            .expect("must hold below the threshold");
7943        assert!(reason.contains("1024"), "{reason}");
7944        assert!(
7945            reason.contains(&cfg.disk.min_free_bytes.to_string()),
7946            "{reason}"
7947        );
7948
7949        assert_eq!(
7950            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
7951            None,
7952            "exactly at the floor is open"
7953        );
7954        assert_eq!(
7955            disk_gate_with(
7956                repo,
7957                &cfg,
7958                PathBuf::new,
7959                |_| Ok(cfg.disk.min_free_bytes + 1)
7960            ),
7961            None,
7962            "comfortably above the floor is open"
7963        );
7964    }
7965
7966    #[test]
7967    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
7968        let dir = tempfile::tempdir().unwrap();
7969        let repo = dir.path().join("repo");
7970        let cache = dir.path().join("cache");
7971        let worktrees = dir.path().join("worktrees");
7972        for path in [&repo, &cache, &worktrees] {
7973            std::fs::create_dir(path).unwrap();
7974        }
7975        let mut cfg = Config::default();
7976        cfg.graph.worktree_root = Some(worktrees.clone());
7977        cfg.verify.gate = vec![format!(
7978            "CARGO_TARGET_DIR='{}' cargo build",
7979            cache.display()
7980        )];
7981        for blocked in [&cache, &worktrees] {
7982            for unmeasured in [false, true] {
7983                assert!(
7984                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
7985                        if path == blocked {
7986                            if unmeasured {
7987                                Err(anyhow::anyhow!("measurement failed"))
7988                            } else {
7989                                Ok(0)
7990                            }
7991                        } else {
7992                            Ok(u64::MAX)
7993                        }
7994                    })
7995                    .is_some(),
7996                    "a blocked secondary output volume must close admission"
7997                );
7998            }
7999        }
8000        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8001    }
8002
8003    #[test]
8004    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8005        let dir = tempfile::tempdir().unwrap();
8006        let repo = dir.path().join("repo");
8007        let cache = dir.path().join("cache");
8008        let home_parent = dir.path().join("run-volume");
8009        let home = home_parent.join("new-home");
8010        for path in [&repo, &cache, &home_parent] {
8011            std::fs::create_dir(path).unwrap();
8012        }
8013        let mut cfg = Config::default();
8014        cfg.graph.worktree_root = Some(repo.clone());
8015        cfg.verify.gate = vec![format!(
8016            "CARGO_TARGET_DIR='{}' cargo build",
8017            cache.display()
8018        )];
8019        cfg.verify.build_cache = BuildCache::Isolated;
8020        let denied = |blocked: &Path| {
8021            disk_gate_with(
8022                &repo,
8023                &cfg,
8024                || home.clone(),
8025                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8026            )
8027            .is_some()
8028        };
8029        assert!(!denied(&cache));
8030        assert!(denied(&home_parent));
8031    }
8032
8033    #[test]
8034    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8035        let mut cfg = Config::default();
8036        cfg.disk.min_free_bytes = 0;
8037        let repo = Path::new("/any/repo/path");
8038        assert_eq!(
8039            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8040            None,
8041            "a zero floor never measures at all"
8042        );
8043    }
8044
8045    #[test]
8046    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8047        let cfg = Config::default();
8048        let repo = Path::new("/any/repo/path");
8049        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8050            Err(anyhow::anyhow!("no df on this box"))
8051        })
8052        .expect("a measurement failure must close the gate, not open it");
8053        assert!(reason.contains("could not measure"), "{reason}");
8054    }
8055
8056    #[test]
8057    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8058        let ordinary = task();
8059        let next = advance_interrupt(
8060            Interrupt::Idle,
8061            std::slice::from_ref(&ordinary.id),
8062            std::slice::from_ref(&ordinary),
8063        );
8064        assert_eq!(next, Interrupt::Idle);
8065    }
8066
8067    #[test]
8068    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8069        // Nothing to interrupt - this is just an ordinary candidate, and the
8070        // loop's normal dispatch will pick it up like any other.
8071        let marked = interrupt_task("marked");
8072        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8073        assert_eq!(next, Interrupt::Idle);
8074    }
8075
8076    #[test]
8077    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8078        let marked = interrupt_task("marked");
8079        let next = advance_interrupt(
8080            Interrupt::Idle,
8081            &["running".to_owned()],
8082            std::slice::from_ref(&marked),
8083        );
8084        assert_eq!(
8085            next,
8086            Interrupt::Parking {
8087                parked: vec!["running".to_owned()],
8088                interrupt_task: "marked".to_owned(),
8089            }
8090        );
8091    }
8092
8093    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8094    /// one run can be in flight when a task becomes runnable and marked.
8095    /// Parking all of them would mean `Resuming` later has more than one id
8096    /// to release back to ordinary dispatch, which cannot be made safe
8097    /// against that same setting's own extra concurrency slots letting two
8098    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8099    /// The simplification the task's own constraints ask for: do not begin
8100    /// a sequence at all until the herd settles back to exactly one.
8101    #[test]
8102    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8103        let marked = interrupt_task("marked");
8104
8105        let two = advance_interrupt(
8106            Interrupt::Idle,
8107            &["a".to_owned(), "b".to_owned()],
8108            std::slice::from_ref(&marked),
8109        );
8110        assert_eq!(two, Interrupt::Idle);
8111
8112        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8113        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8114    }
8115
8116    #[test]
8117    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8118        let state = Interrupt::Parking {
8119            parked: vec!["running".to_owned()],
8120            interrupt_task: "marked".to_owned(),
8121        };
8122        // Still in flight: no change.
8123        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8124        assert_eq!(still_going, state);
8125
8126        // Left flight, but the interrupt task has not been dispatched yet on
8127        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8128        // as long as it is still runnable.
8129        let stopped_but_not_yet_dispatched =
8130            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8131        assert_eq!(stopped_but_not_yet_dispatched, state);
8132
8133        // Left flight, and the interrupt task is now in flight itself.
8134        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8135        assert_eq!(
8136            dispatched,
8137            Interrupt::Running {
8138                parked: vec!["running".to_owned()],
8139                interrupt_task: "marked".to_owned(),
8140            }
8141        );
8142    }
8143
8144    #[test]
8145    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8146        let state = Interrupt::Running {
8147            parked: vec!["running".to_owned()],
8148            interrupt_task: "marked".to_owned(),
8149        };
8150        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8151        assert_eq!(still_running, state);
8152
8153        // Whatever it ended as - merged, failed, held - is not this
8154        // function's concern: leaving flight is the only trigger, driven
8155        // straight off the same in-flight list `poll` already reaps. It does
8156        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8157        // why that would let an unrelated task start ahead of, or alongside,
8158        // the guaranteed resume.
8159        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8160        assert_eq!(
8161            ended,
8162            Interrupt::Resuming {
8163                parked: vec!["running".to_owned()]
8164            }
8165        );
8166    }
8167
8168    #[test]
8169    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8170        let state = Interrupt::Resuming {
8171            parked: vec!["running".to_owned()],
8172        };
8173        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8174        assert_eq!(still_waiting, state);
8175
8176        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8177        assert_eq!(dispatched, Interrupt::Idle);
8178    }
8179
8180    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8181    /// or otherwise moved on by an operator with no claim standing in the
8182    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8183    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8184    /// come. The parked run still gets its resume.
8185    #[test]
8186    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8187    {
8188        let state = Interrupt::Parking {
8189            parked: vec!["running".to_owned()],
8190            interrupt_task: "marked".to_owned(),
8191        };
8192        // `marked` has been held/blocked/deleted since the sequence began:
8193        // it no longer appears in `runnable` at all.
8194        let next = advance_interrupt(state, &[], &[]);
8195        assert_eq!(
8196            next,
8197            Interrupt::Resuming {
8198                parked: vec!["running".to_owned()]
8199            },
8200            "abandoning the interrupt must not abandon the resume it owes"
8201        );
8202    }
8203
8204    /// The same abandonment, one step later: `Resuming` itself must not wait
8205    /// forever for a parked task that has since become unrunnable.
8206    #[test]
8207    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8208        let state = Interrupt::Resuming {
8209            parked: vec!["running".to_owned()],
8210        };
8211        let next = advance_interrupt(state, &[], &[]);
8212        assert_eq!(
8213            next,
8214            Interrupt::Idle,
8215            "nothing is left to wait for; the loop must not stay wedged"
8216        );
8217    }
8218
8219    #[test]
8220    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8221        let marked = interrupt_task("marked");
8222        let next = advance_interrupt_tick(
8223            false,
8224            Interrupt::Idle,
8225            &["running".to_owned()],
8226            std::slice::from_ref(&marked),
8227        );
8228        assert_eq!(
8229            next,
8230            Interrupt::Idle,
8231            "an unmarked, unconfigured daemon must behave exactly as before"
8232        );
8233    }
8234
8235    #[test]
8236    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8237        let state = Interrupt::Parking {
8238            parked: vec!["running".to_owned()],
8239            interrupt_task: "marked".to_owned(),
8240        };
8241        let candidates = vec![interrupt_task("marked"), task()];
8242        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8243        assert!(
8244            allowed.is_empty(),
8245            "nothing may dispatch - not even the interrupt task itself - \
8246             until the parked run has actually stopped"
8247        );
8248    }
8249
8250    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8251    /// grow a special case for it: an urgent candidate that is not the
8252    /// interrupt task withholds exactly like an ordinary one for as long as
8253    /// the parked run it is racing has not actually left flight. A version
8254    /// of this feature once bypassed the gate for urgent candidates, on the
8255    /// theory that a genuinely separate concurrency lane could not collide
8256    /// with 75dd's own; it could, and did - the bypassed task dispatched
8257    /// alongside a run 75dd's own state machine had only *asked* to park,
8258    /// not yet confirmed gone, which is exactly the second run
8259    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8260    /// tick during Parking/Running/Resuming where letting an extra
8261    /// candidate through is safe, urgent or not - the parked run may still
8262    /// be genuinely mid-call.
8263    #[test]
8264    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8265        for state in [
8266            Interrupt::Parking {
8267                parked: vec!["running".to_owned()],
8268                interrupt_task: "marked".to_owned(),
8269            },
8270            Interrupt::Running {
8271                parked: vec!["running".to_owned()],
8272                interrupt_task: "marked".to_owned(),
8273            },
8274            Interrupt::Resuming {
8275                parked: vec!["running".to_owned()],
8276            },
8277        ] {
8278            let candidates = vec![
8279                interrupt_task("marked"),
8280                urgent_task("hot"),
8281                task_with_id("ordinary"),
8282            ];
8283            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8284            assert!(
8285                !allowed.iter().any(|t| t.id == "hot"),
8286                "an urgent candidate must wait out the same gate as anything \
8287                 else while the run it would run alongside has not actually \
8288                 left flight, for state {state:?}: {allowed:?}"
8289            );
8290        }
8291    }
8292
8293    /// The one case where marking a task `--urgent` and `interrupt` at once
8294    /// is not redundant: once the interrupt sequence's own guaranteed
8295    /// resume/dispatch actually admits the task, it is unaffected by also
8296    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8297    /// never on the urgent flag.
8298    #[test]
8299    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8300        let state = Interrupt::Resuming {
8301            parked: vec!["hot".to_owned()],
8302        };
8303        let candidates = vec![urgent_task("hot"), task()];
8304        let allowed = interrupt_gate(&state, &[], candidates);
8305        assert_eq!(
8306            allowed.iter().filter(|t| t.id == "hot").count(),
8307            1,
8308            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8309        );
8310    }
8311
8312    #[test]
8313    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8314        let state = Interrupt::Parking {
8315            parked: vec!["running".to_owned()],
8316            interrupt_task: "marked".to_owned(),
8317        };
8318        let other = task();
8319        let candidates = vec![interrupt_task("marked"), other.clone()];
8320        let allowed = interrupt_gate(&state, &[], candidates);
8321        assert_eq!(allowed.len(), 1);
8322        assert_eq!(allowed[0].id, "marked");
8323    }
8324
8325    #[test]
8326    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8327        let state = Interrupt::Running {
8328            parked: vec!["running".to_owned()],
8329            interrupt_task: "marked".to_owned(),
8330        };
8331        let candidates = vec![task(), task()];
8332        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8333        assert!(allowed.is_empty());
8334    }
8335
8336    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8337    /// sequence began (only reachable above the default
8338    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8339    /// never both in the same tick, which is what "exactly one resume, no
8340    /// simultaneous run" actually requires structurally rather than by
8341    /// coincidence of how many ordinary slots happen to be free.
8342    #[test]
8343    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8344        let state = Interrupt::Resuming {
8345            parked: vec!["a".to_owned(), "c".to_owned()],
8346        };
8347        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8348        let allowed = interrupt_gate(&state, &[], candidates);
8349        assert_eq!(
8350            allowed.len(),
8351            1,
8352            "at most one candidate may be offered while resuming: {allowed:?}"
8353        );
8354        assert_eq!(allowed[0].id, "a");
8355    }
8356
8357    #[test]
8358    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8359        let state = Interrupt::Resuming {
8360            parked: vec!["a".to_owned()],
8361        };
8362        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8363        assert!(allowed.is_empty());
8364    }
8365
8366    /// The invariant the completion criteria ask for by name: across a whole
8367    /// simulated sequence, there is never a tick where the gate would let
8368    /// through both the parked run's resume and the interrupt task, and
8369    /// exactly one candidate resumes the instant the interrupt task's run
8370    /// ends - never zero, never more than one.
8371    #[test]
8372    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8373        let running = task(); // id: whatever `Task::new` minted
8374        let marked = interrupt_task("marked");
8375
8376        let mut state = Interrupt::Idle;
8377        // Tick 1: `running` is in flight, `marked` becomes runnable.
8378        let in_flight = vec![running.id.clone()];
8379        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8380        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8381        assert!(gated.is_empty(), "still waiting on `running` to park");
8382
8383        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8384        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8385        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8386        assert_eq!(
8387            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8388            vec!["marked"],
8389            "only the interrupt task may be offered to the dispatcher now"
8390        );
8391
8392        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8393        state = advance_interrupt_tick(
8394            true,
8395            state,
8396            &["marked".to_owned()],
8397            std::slice::from_ref(&running),
8398        );
8399        let gated = interrupt_gate(
8400            &state,
8401            &["marked".to_owned()],
8402            vec![marked.clone(), running.clone()],
8403        );
8404        assert!(
8405            gated.is_empty(),
8406            "the parked run must not be offered back while the interrupt \
8407             task is still running"
8408        );
8409
8410        // Tick 4: `marked`'s run reached a terminal status and left flight.
8411        // A higher-priority ordinary task `other` is also runnable now - it
8412        // must not be let through instead of, or alongside, `running`.
8413        let other = task_with_id("other");
8414        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8415        assert_eq!(
8416            state,
8417            Interrupt::Resuming {
8418                parked: vec![running.id.clone()]
8419            }
8420        );
8421        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8422        assert_eq!(
8423            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8424            vec![running.id.as_str()],
8425            "exactly the parked run resumes - not the unrelated task, even \
8426             though it was offered first"
8427        );
8428
8429        // Tick 5: `running` is now in flight (dispatched from tick 4's
8430        // gate). Only now does the sequence end and ordinary dispatch fully
8431        // resume.
8432        state = advance_interrupt_tick(
8433            true,
8434            state,
8435            std::slice::from_ref(&running.id),
8436            std::slice::from_ref(&other),
8437        );
8438        assert_eq!(state, Interrupt::Idle);
8439        let gated = interrupt_gate(
8440            &state,
8441            std::slice::from_ref(&running.id),
8442            vec![other.clone()],
8443        );
8444        assert_eq!(
8445            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8446            vec![other.id.as_str()],
8447            "ordinary dispatch is unrestricted again"
8448        );
8449    }
8450
8451    #[test]
8452    fn every_run_status_settles_the_task_it_came_from() {
8453        // run status, resulting task status, attempts still standing after one
8454        let table = [
8455            (RunStatus::Merged, TaskStatus::Done, 1),
8456            (RunStatus::Ready, TaskStatus::Done, 1),
8457            (RunStatus::Stalled, TaskStatus::Failed, 0),
8458            (RunStatus::Blocked, TaskStatus::Failed, 1),
8459            (RunStatus::Failed, TaskStatus::Failed, 1),
8460            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8461            (RunStatus::Prep, TaskStatus::Failed, 1),
8462            (RunStatus::Implementing, TaskStatus::Failed, 1),
8463            (RunStatus::Judging, TaskStatus::Failed, 1),
8464            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8465            (RunStatus::Voting, TaskStatus::Failed, 1),
8466            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8467            (RunStatus::Gating, TaskStatus::Failed, 1),
8468        ];
8469        for (run, want, attempts) in table {
8470            let mut t = task();
8471            t.start("20260902-000000-aaaa".to_owned());
8472            settle(
8473                &mut t,
8474                Verdict {
8475                    status: run,
8476                    left_pr: false,
8477                    parked: false,
8478                    quota_hit: matches!(run, RunStatus::Stalled),
8479                    no_viable_candidates: false,
8480                },
8481                "why",
8482                2,
8483            );
8484            assert_eq!(t.status, want, "task status after {}", label(run));
8485            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8486        }
8487    }
8488
8489    #[test]
8490    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8491        let mut stalled = task();
8492        stalled.start("20260902-000000-aaaa".to_owned());
8493        settle(
8494            &mut stalled,
8495            Verdict {
8496                status: RunStatus::Stalled,
8497                left_pr: false,
8498                parked: false,
8499                quota_hit: true,
8500                no_viable_candidates: false,
8501            },
8502            "quota",
8503            1,
8504        );
8505        assert_eq!(stalled.attempts, 0);
8506        assert!(
8507            stalled.status.runnable(),
8508            "a machine problem must leave the task in line"
8509        );
8510
8511        let mut blocked = task();
8512        blocked.start("20260902-000000-aaaa".to_owned());
8513        settle(
8514            &mut blocked,
8515            Verdict {
8516                status: RunStatus::Blocked,
8517                left_pr: false,
8518                parked: false,
8519                quota_hit: false,
8520                no_viable_candidates: false,
8521            },
8522            "findings open",
8523            1,
8524        );
8525        assert_eq!(blocked.attempts, 1);
8526        assert_eq!(
8527            blocked.status,
8528            TaskStatus::Held,
8529            "the last attempt hands the task to a human"
8530        );
8531    }
8532
8533    #[test]
8534    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8535        // Attempts to spare: without the pull request this task would go
8536        // straight back in line and run the whole competition again.
8537        let mut delivered = task();
8538        delivered.start("20260903-080619-01c2".to_owned());
8539        settle(
8540            &mut delivered,
8541            Verdict {
8542                status: RunStatus::Blocked,
8543                left_pr: true,
8544                parked: false,
8545                quota_hit: false,
8546                no_viable_candidates: false,
8547            },
8548            "no check status",
8549            4,
8550        );
8551        assert_eq!(
8552            delivered.status,
8553            TaskStatus::Held,
8554            "a pull request waiting on CI or a person is not a retryable failure"
8555        );
8556        assert!(
8557            !delivered.status.runnable(),
8558            "the loop must not pick this task up again"
8559        );
8560        assert_eq!(
8561            delivered.last_error.as_deref(),
8562            Some("no check status"),
8563            "the operator needs to be told what the gate was waiting for"
8564        );
8565
8566        // The same status without a pull request is a plain failure, and with
8567        // attempts left it is retried.
8568        let mut empty_handed = task();
8569        empty_handed.start("20260903-080619-01c2".to_owned());
8570        settle(
8571            &mut empty_handed,
8572            Verdict {
8573                status: RunStatus::Blocked,
8574                left_pr: false,
8575                parked: false,
8576                quota_hit: false,
8577                no_viable_candidates: false,
8578            },
8579            "findings open",
8580            4,
8581        );
8582        assert_eq!(empty_handed.status, TaskStatus::Failed);
8583        assert!(empty_handed.status.runnable());
8584    }
8585
8586    #[test]
8587    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
8588        // Every candidate agreed, with evidence, that nothing belonged in the
8589        // worktree. That is not a confirmed success to close automatically -
8590        // a human still has to check the claim - and it is not an ordinary
8591        // failure either, so this settles exactly like a pull request nobody
8592        // merged yet: `Held`, same as `Blocked` with a PR.
8593        let mut noop = task();
8594        noop.start("20260912-131304-391f".to_owned());
8595        settle(
8596            &mut noop,
8597            Verdict {
8598                status: RunStatus::VerifiedNoop,
8599                left_pr: false,
8600                parked: false,
8601                quota_hit: false,
8602                no_viable_candidates: true,
8603            },
8604            "candidate A: already fixed by b32cfc4, on main",
8605            4,
8606        );
8607        assert_eq!(
8608            noop.status,
8609            TaskStatus::Held,
8610            "an unverified claim is a request for a human, not a failure"
8611        );
8612        assert!(
8613            !noop.status.runnable(),
8614            "the loop must not requeue this on the same unverified claim"
8615        );
8616        // `Task::release` resets attempts to zero the moment a human looks at
8617        // the evidence and lets it run again, so it does not matter here
8618        // whether the one attempt already spent stays spent - what matters is
8619        // that nothing retries this task unattended in the meantime.
8620        assert_eq!(noop.attempts, 1);
8621    }
8622
8623    #[test]
8624    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
8625        // Parking is the operator asking for the process back - to replace the
8626        // binary, most of all. The run's work is intact on disk, so this is
8627        // not a failed attempt, and charging for it would mean a few upgrades
8628        // could exhaust a budget meant for agents that misbehaved.
8629        let mut parked = task();
8630        parked.start("20260903-183634-2d98".to_owned());
8631        settle(
8632            &mut parked,
8633            Verdict {
8634                status: RunStatus::Implementing,
8635                left_pr: false,
8636                quota_hit: false,
8637                parked: true,
8638                no_viable_candidates: false,
8639            },
8640            "parked after `implementing`",
8641            2,
8642        );
8643        assert_eq!(parked.attempts, 0, "a park is refunded");
8644        assert!(
8645            parked.status.runnable(),
8646            "and the task stays in line so the next loop resumes its run"
8647        );
8648        assert_eq!(parked.status, TaskStatus::Parked);
8649        assert_eq!(
8650            parked.park_reason.as_deref(),
8651            Some("parked after `implementing`"),
8652            "the card says where it stopped"
8653        );
8654        assert_eq!(parked.last_error, None, "nothing failed");
8655
8656        // Without the park flag the same non-terminal status is what it always
8657        // was: `execute` returning mid-flight, which is a bug and spends an
8658        // attempt so a task cannot loop on it forever.
8659        let mut broken = task();
8660        broken.start("20260903-183634-2d98".to_owned());
8661        settle(
8662            &mut broken,
8663            Verdict {
8664                status: RunStatus::Implementing,
8665                left_pr: false,
8666                quota_hit: false,
8667                parked: false,
8668                no_viable_candidates: false,
8669            },
8670            "returned mid-flight",
8671            2,
8672        );
8673        assert_eq!(broken.attempts, 1);
8674    }
8675
8676    #[test]
8677    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
8678        // Run e633: quorum lost because two judges answered with the wrong
8679        // JSON shape, `quota: []`. Refunding that takes the bound off the
8680        // retry loop, and each retry pays for a fresh hour-long implement
8681        // wave before it can fail the same way.
8682        let mut flaky = task();
8683        flaky.start("20260903-123023-e633".to_owned());
8684        settle(
8685            &mut flaky,
8686            Verdict {
8687                status: RunStatus::Stalled,
8688                left_pr: false,
8689                parked: false,
8690                quota_hit: false,
8691                no_viable_candidates: false,
8692            },
8693            "verdict rests on 1 of 3 judges",
8694            2,
8695        );
8696        assert_eq!(
8697            flaky.attempts, 1,
8698            "flakiness spends an attempt, so `max_attempts` still bounds it"
8699        );
8700        assert!(flaky.status.runnable(), "and it is still worth retrying");
8701
8702        // The same status, lost to a rate limit, is the machine's fault.
8703        let mut limited = task();
8704        limited.start("20260903-123023-e633".to_owned());
8705        settle(
8706            &mut limited,
8707            Verdict {
8708                status: RunStatus::Stalled,
8709                left_pr: false,
8710                parked: false,
8711                quota_hit: true,
8712                no_viable_candidates: false,
8713            },
8714            "judge-2, judge-3 out of quota",
8715            2,
8716        );
8717        assert_eq!(limited.attempts, 0, "a quota window is refunded");
8718        assert!(limited.status.runnable());
8719
8720        // And the bound really binds: a task that keeps stalling on flakiness
8721        // reaches a human instead of running the roster forever.
8722        let mut worn = task();
8723        for _ in 0..2 {
8724            worn.release();
8725        }
8726        worn.start("20260903-123023-e633".to_owned());
8727        worn.attempts = 2;
8728        settle(
8729            &mut worn,
8730            Verdict {
8731                status: RunStatus::Stalled,
8732                left_pr: false,
8733                parked: false,
8734                quota_hit: false,
8735                no_viable_candidates: false,
8736            },
8737            "no quorum again",
8738            2,
8739        );
8740        assert_eq!(worn.status, TaskStatus::Held);
8741        assert!(!worn.status.runnable());
8742    }
8743
8744    #[test]
8745    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
8746        // The implement wave loses every seat to the same rate limit and
8747        // `after_implement` bails with nothing viable, which surfaces as
8748        // `Failed` rather than `Stalled`. That is the same machine fact the
8749        // `Stalled`-quota row already refunds, and must be refunded the same
8750        // way, or a quota outage quietly holds every task it touches instead
8751        // of leaving them in line for the reset.
8752        let mut wiped_out = task();
8753        wiped_out.start("20260907-025000-a1b2".to_owned());
8754        settle(
8755            &mut wiped_out,
8756            Verdict {
8757                status: RunStatus::Failed,
8758                left_pr: false,
8759                parked: false,
8760                quota_hit: true,
8761                no_viable_candidates: true,
8762            },
8763            "no candidate produced a change; nothing to judge",
8764            2,
8765        );
8766        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
8767        assert!(
8768            wiped_out.status.runnable(),
8769            "a machine problem must leave the task in line"
8770        );
8771
8772        // This is the exemption that must stay narrow: a candidate that did
8773        // produce a change, and then failed for some other reason, still
8774        // spends the attempt even though a seat elsewhere hit its quota.
8775        // Otherwise every ordinary failure that happens to share a run with
8776        // an unrelated rate limit would be refunded for free.
8777        let mut partial_progress = task();
8778        partial_progress.start("20260907-025500-c3d4".to_owned());
8779        settle(
8780            &mut partial_progress,
8781            Verdict {
8782                status: RunStatus::Failed,
8783                left_pr: false,
8784                parked: false,
8785                quota_hit: true,
8786                no_viable_candidates: false,
8787            },
8788            "gate failed on the winning candidate",
8789            2,
8790        );
8791        assert_eq!(
8792            partial_progress.attempts, 1,
8793            "a candidate that actually produced a change spends the attempt \
8794             even though some other seat hit its quota"
8795        );
8796        assert!(partial_progress.status.runnable());
8797    }
8798
8799    #[test]
8800    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
8801        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
8802        // disk, and that construction must reach the same conclusion as the
8803        // one `attempt` builds from a live run, or a crash at exactly the
8804        // wrong moment gives a recovered task a different policy than one a
8805        // daemon finished settling itself.
8806        let mut t = task();
8807        t.start("20260907-025000-a1b2".to_owned());
8808        let mut state = run_state(RunStatus::Failed);
8809        state.quota.push(QuotaLoss {
8810            cause: crate::agent::QuotaCause::UsageLimit,
8811            agent: String::new(),
8812            seat: "cand-a".to_owned(),
8813            node: "implement".to_owned(),
8814            at: Timestamp::now(),
8815            reset: None,
8816        });
8817        assert!(
8818            state.viable().is_empty(),
8819            "no candidate was added, so nothing is viable"
8820        );
8821        reclaim(&mut t, Some(state), 2, "en");
8822        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
8823        assert!(t.status.runnable());
8824    }
8825
8826    #[test]
8827    fn a_held_task_is_never_offered_to_the_loop() {
8828        let dir = tempfile::tempdir().unwrap();
8829        let queue = Queue::at(dir.path().to_path_buf());
8830        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
8831            let mut t = task();
8832            t.id = format!("2026090{n}-000000-000{n}");
8833            t.priority = priority;
8834            queue.put(&mut t).unwrap();
8835        }
8836        let mut held = task();
8837        held.id = "20260909-000000-9999".to_owned();
8838        held.priority = 99;
8839        held.hold_machine(None);
8840        queue.put(&mut held).unwrap();
8841
8842        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
8843        assert_eq!(order.len(), 3);
8844        assert!(!order.contains(&held.id));
8845        assert_eq!(
8846            order.first().cloned(),
8847            queue.next_runnable().map(|t| t.id),
8848            "the loop's first candidate is exactly what the queue offers"
8849        );
8850        assert_eq!(
8851            order,
8852            vec![
8853                "20260902-000000-0002".to_owned(),
8854                "20260903-000000-0003".to_owned(),
8855                "20260901-000000-0001".to_owned(),
8856            ],
8857            "priority first, then oldest, so nothing starves"
8858        );
8859    }
8860
8861    #[test]
8862    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
8863        let dir = tempfile::tempdir().unwrap();
8864        let queue = Queue::at(dir.path().to_path_buf());
8865        let mut old = task();
8866        old.id = "20260101-000000-old0".to_owned();
8867        queue.put(&mut old).unwrap();
8868        let mut fresh = task();
8869        fresh.id = "20260101-000000-new0".to_owned();
8870        queue.put(&mut fresh).unwrap();
8871
8872        // No parseable pid at all, so age is the only signal there is to
8873        // check - unlike a real `Queue::claim`, which always names a real,
8874        // and therefore alive, pid this test cannot fake as dead.
8875        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
8876        std::thread::sleep(Duration::from_millis(60));
8877        let live = queue.claim(&fresh.id).unwrap();
8878
8879        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8880        assert_eq!(swept, vec![old.id.clone()]);
8881        assert!(
8882            queue.claim(&old.id).is_ok(),
8883            "an unparseable lock older than the threshold is swept"
8884        );
8885        assert!(
8886            queue.claim(&fresh.id).is_err(),
8887            "a live pid protects its lock regardless of age"
8888        );
8889        drop(live);
8890    }
8891
8892    #[test]
8893    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
8894        // A live worker's claim remains authoritative even beyond the sweep's
8895        // age limit. Sweeping it would permit a second competing attempt.
8896        let dir = tempfile::tempdir().unwrap();
8897        let queue = Queue::at(dir.path().to_path_buf());
8898        let mut t = task();
8899        t.id = "20260101-000000-live".to_owned();
8900        queue.put(&mut t).unwrap();
8901
8902        let claim = queue.claim(&t.id).unwrap();
8903        std::thread::sleep(Duration::from_millis(60));
8904
8905        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
8906        assert!(
8907            swept.is_empty(),
8908            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
8909        );
8910        assert!(
8911            queue.claim(&t.id).is_err(),
8912            "the lock still protects its task"
8913        );
8914        drop(claim);
8915    }
8916
8917    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
8918    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
8919    fn injected_dead_pid() -> u32 {
8920        std::process::id().checked_add(1).unwrap_or(1)
8921    }
8922
8923    #[test]
8924    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
8925        let dir = tempfile::tempdir().unwrap();
8926        let queue = Queue::at(dir.path().to_path_buf());
8927        let mut t = task();
8928        t.id = "20260101-000000-dead".to_owned();
8929        queue.put(&mut t).unwrap();
8930        let dead_pid = injected_dead_pid();
8931
8932        // Written directly rather than through `Queue::claim`, which would
8933        // stamp this test process's own very much alive pid and defeat the
8934        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
8935        // like moments after it died, not six hours later.
8936        std::fs::write(
8937            dir.path().join(format!("{}.lock", t.id)),
8938            dead_pid.to_string(),
8939        )
8940        .unwrap();
8941
8942        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8943            pid != dead_pid
8944        });
8945        assert_eq!(
8946            swept,
8947            vec![t.id.clone()],
8948            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
8949        );
8950        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
8951    }
8952
8953    #[test]
8954    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
8955        let dir = tempfile::tempdir().unwrap();
8956        let queue = Queue::at(dir.path().to_path_buf());
8957        let mut t = task();
8958        t.id = "20260101-000000-late".to_owned();
8959        queue.put(&mut t).unwrap();
8960        let dead_pid = injected_dead_pid();
8961
8962        // Tick one, standing in for the sweep `poll` already runs at
8963        // startup: nothing to find yet.
8964        assert!(
8965            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
8966            "nothing has claimed the task yet"
8967        );
8968
8969        // A second daemon claims the task and dies before it ever writes
8970        // `running`, well after this loop's own startup sweep already ran.
8971        std::fs::write(
8972            dir.path().join(format!("{}.lock", t.id)),
8973            dead_pid.to_string(),
8974        )
8975        .unwrap();
8976
8977        // Tick two, standing in for a poll long into this daemon's uptime:
8978        // the same function, called again, notices what only just appeared -
8979        // proving the sweep is not a one-shot startup check.
8980        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
8981            pid != dead_pid
8982        });
8983        assert_eq!(swept, vec![t.id.clone()]);
8984    }
8985
8986    #[test]
8987    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
8988        // `reclaim_orphaned_running` looks up the task's last run, which
8989        // touches `run::home()`; the first call anywhere in this binary wins,
8990        // so this is a no-op if another test already pinned one, and either
8991        // way the run id below is never written under it.
8992        crate::run::pin_test_home();
8993        let dir = tempfile::tempdir().unwrap();
8994        let queue = Queue::at(dir.path().to_path_buf());
8995        let mut t = task();
8996        t.id = "20260101-000000-crsh".to_owned();
8997        t.status = TaskStatus::Running;
8998        t.attempts = 1;
8999        // No `run.json` behind this id: standing in for a run this test does
9000        // not need to make readable, since the point is the lock, not the
9001        // recovery table `reclaim` already has its own tests for.
9002        t.runs.push("20260904-000000-4043".to_owned());
9003        queue.put(&mut t).unwrap();
9004        let dead_pid = injected_dead_pid();
9005
9006        // The crashed daemon's own claim, naming a pid nothing on the
9007        // machine holds anymore.
9008        std::fs::write(
9009            dir.path().join(format!("{}.lock", t.id)),
9010            dead_pid.to_string(),
9011        )
9012        .unwrap();
9013
9014        // Before the lock is swept the task looks claimed, and
9015        // `reclaim_orphaned_running` must leave it alone - this is exactly
9016        // the bug: a `running` task stranded behind a dead daemon's lock,
9017        // invisible to the claim-as-proof check because the lock outlived
9018        // the process that wrote it.
9019        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9020        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9021
9022        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9023            pid != dead_pid
9024        });
9025        assert_eq!(swept, vec![t.id.clone()]);
9026
9027        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9028        assert_eq!(reclaimed, vec![t.id.clone()]);
9029        let after = queue.get(&t.id).unwrap();
9030        assert_eq!(
9031            after.status,
9032            TaskStatus::Held,
9033            "no run.json to recover from, so a human is asked"
9034        );
9035        assert_eq!(
9036            after.runs,
9037            vec!["20260904-000000-4043".to_owned()],
9038            "the crashed run's id is kept as evidence, not discarded"
9039        );
9040    }
9041
9042    #[test]
9043    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9044        let dir = tempfile::tempdir().unwrap();
9045        let queue = Queue::at(dir.path().to_path_buf());
9046        let mut t = task();
9047        t.id = "20260101-000000-unknown".to_owned();
9048        queue.put(&mut t).unwrap();
9049        let dead_pid = injected_dead_pid();
9050        std::fs::write(
9051            dir.path().join(format!("{}.lock", t.id)),
9052            dead_pid.to_string(),
9053        )
9054        .unwrap();
9055
9056        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9057        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9058        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9059    }
9060
9061    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9062        let mut s = run_state(status);
9063        s.config.graph.language = language.to_owned();
9064        s
9065    }
9066
9067    fn unstarted_verdict(status: RunStatus) -> Verdict {
9068        Verdict {
9069            status,
9070            left_pr: false,
9071            quota_hit: false,
9072            parked: false,
9073            no_viable_candidates: false,
9074        }
9075    }
9076
9077    #[test]
9078    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9079        let mut t = task();
9080        t.attempts = 1;
9081        settle_in(
9082            &mut t,
9083            unstarted_verdict(RunStatus::AlreadyInBase),
9084            "already in main",
9085            1,
9086            phrases("en"),
9087        );
9088        assert_eq!(t.status, TaskStatus::Done);
9089        assert_eq!(t.attempts, 0);
9090    }
9091
9092    #[test]
9093    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9094        let reason = |language: &str| {
9095            let mut t = task();
9096            settle_in(
9097                &mut t,
9098                unstarted_verdict(RunStatus::Judging),
9099                "boom",
9100                1,
9101                phrases(language),
9102            );
9103            t.last_error.or(t.hold_reason).unwrap_or_default()
9104        };
9105        assert!(
9106            reason("en").starts_with("the graph stopped at `"),
9107            "{}",
9108            reason("en")
9109        );
9110        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9111        assert!(reason("日本語").contains("boom"));
9112        assert_eq!(reason("fr"), reason("en"));
9113    }
9114
9115    #[test]
9116    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9117        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9118        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9119        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9120        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9121        assert!(ja.contains("[run "), "{ja}");
9122        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9123        assert!(ended.starts_with("run 終了: "), "{ended}");
9124        let mut de = run_state_in(RunStatus::Failed, "de");
9125        let mut en = run_state_in(RunStatus::Failed, "en");
9126        de.id = "same".to_owned();
9127        en.id = "same".to_owned();
9128        assert_eq!(describe(&de), describe(&en));
9129    }
9130
9131    #[test]
9132    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9133        use crate::handover::Refused;
9134        let cases = [
9135            Refused::Foreign {
9136                branch: "b".into(),
9137                path: "/w/x".into(),
9138                why: "made by hand".into(),
9139            },
9140            Refused::Unsafe {
9141                branch: "b".into(),
9142                path: "/w/x".into(),
9143                why: "its worktree has uncommitted changes (a.rs)".into(),
9144            },
9145            Refused::ReleaseFailed {
9146                branch: "b".into(),
9147                path: "/w/x".into(),
9148                run: "ab12".into(),
9149            },
9150        ];
9151        for r in &cases {
9152            let en = (phrases("en").handover_refused)(r);
9153            assert_eq!(en, r.to_string());
9154            let ja = (phrases("ja").handover_refused)(r);
9155            assert!(
9156                !ja.contains("is checked out") && !ja.contains("try again"),
9157                "{ja}"
9158            );
9159            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9160            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9161                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9162            }
9163        }
9164        assert!(phrases("en").handover_hint.contains("release the task"));
9165        assert!(phrases("ja").handover_hint.contains("解放"));
9166    }
9167
9168    #[test]
9169    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9170        let build = |lang: &str| {
9171            let mut s = run_state_in(RunStatus::Blocked, lang);
9172            s.id = "same".to_owned();
9173            s.config.graph.review_rounds = 3;
9174            let mut r = review_round(3);
9175            r.expected = 3;
9176            r.answered = 1;
9177            s.reviews.push(r);
9178            s.event(
9179                "review",
9180                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9181            );
9182            s
9183        };
9184        let en = describe(&build("en"));
9185        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9186        let ja = describe(&build("ja"));
9187        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9188        assert!(!ja.contains("never answered"), "{ja}");
9189        assert!(ja.contains("[run "), "{ja}");
9190
9191        // An incomplete panel whose verification failed is a different stop:
9192        // the real event must survive in ja too.
9193        let mut failed = build("ja");
9194        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9195            command: "cargo test".to_owned(),
9196            code: Some(1),
9197            output_tail: String::new(),
9198            duration_ms: 0,
9199            resource_blocked: false,
9200        });
9201        failed.event("review", "stopped; e2e failed: cargo test");
9202        let ja = describe(&failed);
9203        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9204        assert!(!ja.contains("席のレビュアー"), "{ja}");
9205    }
9206
9207    #[test]
9208    fn refusals_and_recovery_prose_follow_the_language() {
9209        let home = crate::run::test_home();
9210        let t = held_task_with("r1");
9211        let q = action_question(
9212            "r1",
9213            ask::ChoiceAction::Resume {
9214                run: "r1".to_owned(),
9215            },
9216        );
9217        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9218            ActionDecision::Refuse(s) => s,
9219            other => panic!("{other:?}"),
9220        };
9221        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9222        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9223        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9224
9225        let mut held = task();
9226        reclaim(&mut held, None, 2, "ja");
9227        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9228        let mut held = task();
9229        reclaim(&mut held, None, 2, "xx");
9230        assert!(held.hold_reason.unwrap().contains("held for a human"));
9231    }
9232
9233    fn run_state(status: RunStatus) -> RunState {
9234        let mut state = RunState::new(
9235            PathBuf::from("/repo"),
9236            "main".to_owned(),
9237            "abc1234def".to_owned(),
9238            "add retries".to_owned(),
9239            Config::default(),
9240        );
9241        state.status = status;
9242        state
9243    }
9244
9245    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9246        Candidate {
9247            index: 0,
9248            label,
9249            agent: "claude".to_owned(),
9250            branch: format!("magi/x/{label}"),
9251            worktree: PathBuf::from("/repo"),
9252            summary: summary.to_owned(),
9253            stat: String::new(),
9254            files: 0,
9255            commits: usize::from(!empty),
9256            empty,
9257            failed: failed.map(str::to_owned),
9258            verified_noop: None,
9259            duration_ms: 0,
9260            folded: false,
9261        }
9262    }
9263
9264    #[test]
9265    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9266        let mut state = run_state(RunStatus::Blocked);
9267        state.gate = vec![
9268            CommandOutcome {
9269                command: "cargo make check".to_owned(),
9270                code: Some(0),
9271                output_tail: "ok".to_owned(),
9272                duration_ms: 0,
9273                resource_blocked: false,
9274            },
9275            CommandOutcome {
9276                command: "cargo test".to_owned(),
9277                code: Some(101),
9278                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9279                duration_ms: 0,
9280                resource_blocked: false,
9281            },
9282        ];
9283        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9284        assert!(d.contains("cargo test"), "{d}");
9285        assert!(
9286            !d.contains("cargo make check"),
9287            "a passing check is not a diagnostic: {d}"
9288        );
9289        assert!(d.contains("assertion failed"), "{d}");
9290    }
9291
9292    #[test]
9293    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9294        let mut state = run_state(RunStatus::Blocked);
9295        state.event(
9296            "land",
9297            "stopped: the fixer produced no commit while 2 check(s) were failing \
9298             (build, lint); stopping instead of looping on an unchanged tree",
9299        );
9300        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9301        assert!(d.contains("build"), "{d}");
9302        assert!(d.contains("lint"), "{d}");
9303        assert!(d.contains("fixer produced no commit"), "{d}");
9304    }
9305
9306    #[test]
9307    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9308        // `describe`'s output becomes `Task::last_error` verbatim, and the
9309        // phone renders that in the same alarm-styled box an ordinary
9310        // failure gets. A bare `verified_noop` there would read exactly like
9311        // the failure this status exists to be told apart from.
9312        let state = run_state(RunStatus::VerifiedNoop);
9313        let d = describe(&state);
9314        assert!(
9315            d.contains("agent-verified no-op"),
9316            "expected the display label, not the wire spelling: {d}"
9317        );
9318        assert!(!d.contains("verified_noop"), "{d}");
9319    }
9320
9321    #[test]
9322    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9323        let mut state = run_state(RunStatus::Failed);
9324        state.gate.push(crate::run::CommandOutcome {
9325            command: "cargo test".into(),
9326            code: Some(101),
9327            output_tail: format!(
9328                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9329                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9330            ),
9331            duration_ms: 1,
9332            resource_blocked: false,
9333        });
9334        let d = diagnostic(&state).unwrap();
9335        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9336        assert!(d.contains("assertion failed: widget missing"));
9337        assert!(d.contains("widget log"));
9338    }
9339
9340    #[test]
9341    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9342        // The whole point of the feature: a run held as "no candidate produced
9343        // a change" can mean the implementer actually finished the task and
9344        // only left a clean local tree behind - see AGENTS.md on this exact
9345        // failure mode. The diagnostic has to carry what the agent actually
9346        // said, not just the fact that nothing was there to judge.
9347        let mut state = run_state(RunStatus::Failed);
9348        state.candidates = vec![candidate(
9349            'A',
9350            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9351            true,
9352            None,
9353        )];
9354        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9355        assert!(d.contains("candidate A"), "{d}");
9356        assert!(d.contains("tagged v1.2.3"), "{d}");
9357    }
9358
9359    #[test]
9360    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9361        let mut state = run_state(RunStatus::Failed);
9362        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9363        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9364        assert!(d.contains("candidate A"), "{d}");
9365        assert!(d.contains("agent timed out"), "{d}");
9366    }
9367
9368    #[test]
9369    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9370        // A viable candidate existed, the gate never ran, and nothing land
9371        // said matches - `Task::last_error` is left to explain this one alone.
9372        let mut state = run_state(RunStatus::Failed);
9373        state.candidates = vec![candidate('A', "did the work", false, None)];
9374        assert!(diagnostic(&state).is_none());
9375    }
9376
9377    #[test]
9378    fn diagnostic_is_bounded_however_much_a_run_printed() {
9379        let mut state = run_state(RunStatus::Blocked);
9380        state.gate = vec![
9381            CommandOutcome {
9382                command: "cargo test".to_owned(),
9383                code: Some(101),
9384                output_tail: "x".repeat(50_000),
9385                duration_ms: 0,
9386                resource_blocked: false,
9387            },
9388            CommandOutcome {
9389                command: "cargo clippy".to_owned(),
9390                code: Some(1),
9391                output_tail: "y".repeat(50_000),
9392                duration_ms: 0,
9393                resource_blocked: false,
9394            },
9395        ];
9396        state.candidates = vec![
9397            candidate('A', &"z".repeat(50_000), true, None),
9398            candidate('B', &"w".repeat(50_000), true, None),
9399        ];
9400        let d = diagnostic(&state).expect("plenty here to diagnose");
9401        assert!(
9402            d.len() <= DIAGNOSTIC_MAX,
9403            "diagnostic grew to {} bytes, unbounded",
9404            d.len()
9405        );
9406    }
9407
9408    #[test]
9409    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9410        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9411            let mut t = task();
9412            let mut state = run_state(status);
9413            t.pr_recovery = Some(crate::pr_recovery::Selection {
9414                url: "url".into(),
9415                branch: format!("magi/task-{}", t.id),
9416                head: "a".repeat(40),
9417                source_head: None,
9418                source_run: None,
9419                source_proof: None,
9420                disposition: Some(crate::pr_recovery::Disposition::Land),
9421                instruction: t.instruction.clone(),
9422                approved_at: Timestamp::now(),
9423            });
9424            state.pr_recovery = t.pr_recovery.clone();
9425            t.start(state.id.clone());
9426            settle_and_diagnose(
9427                &mut t,
9428                Verdict {
9429                    status,
9430                    left_pr: false,
9431                    quota_hit: false,
9432                    parked: false,
9433                    no_viable_candidates: false,
9434                },
9435                "delivery stopped",
9436                5,
9437                &state,
9438            );
9439            assert_eq!(t.status, TaskStatus::Held);
9440            let reason = t.hold_reason.as_deref().unwrap();
9441            if status == RunStatus::Ready {
9442                assert!(reason.contains("Selected PR delivery is incomplete"));
9443                assert!(t.recovery_budget.is_none());
9444            } else {
9445                assert!(reason.contains("Selected recovery stopped"));
9446                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9447            }
9448            assert!(t.pr_recovery.is_some());
9449        }
9450    }
9451
9452    #[test]
9453    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9454        let mut state = run_state(RunStatus::Voting);
9455        state.base_sync = Some(crate::run::BaseSync {
9456            tip: "base-tip".into(),
9457            behind: 3,
9458            attempts: 4,
9459            conflict: Some("base stopped".into()),
9460            already_in: None,
9461        });
9462        state.record_base_sync_stop("candidate-head");
9463        let mut t = task();
9464        t.start(state.id.clone());
9465        let verdict = Verdict {
9466            status: RunStatus::Blocked,
9467            left_pr: false,
9468            quota_hit: false,
9469            parked: false,
9470            no_viable_candidates: false,
9471        };
9472        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9473        assert_eq!(
9474            t.status,
9475            TaskStatus::Held,
9476            "unspent task attempts cannot start another competition"
9477        );
9478        let at = t.held_at;
9479        let cause = t.hold_notice_cause.clone();
9480        state.begin_pass();
9481        t.release_operator("test-resume", None);
9482        t.start(state.id.clone());
9483        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9484        assert_eq!(t.status, TaskStatus::Held);
9485        assert_eq!(t.held_at, at);
9486        assert_eq!(t.hold_notice_cause, cause);
9487    }
9488
9489    #[test]
9490    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9491        let mut state = run_state(RunStatus::Blocked);
9492        state.gate = vec![CommandOutcome {
9493            command: "cargo test".to_owned(),
9494            code: Some(101),
9495            output_tail: "assertion failed".to_owned(),
9496            duration_ms: 0,
9497            resource_blocked: false,
9498        }];
9499        let verdict = Verdict {
9500            status: RunStatus::Blocked,
9501            left_pr: false,
9502            quota_hit: false,
9503            parked: false,
9504            no_viable_candidates: false,
9505        };
9506
9507        // Attempt one of two still has a retry coming: no diagnostic yet, the
9508        // task is going to run again and this run's evidence would go stale.
9509        let mut t = task();
9510        t.start("run-1".to_owned());
9511        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9512        assert_eq!(t.status, TaskStatus::Failed);
9513        assert!(t.diagnostic.is_none());
9514
9515        // Attempt two exhausts the budget: now it is held, and the
9516        // diagnostic is what `magi task show` has to say more than one line.
9517        t.start("run-2".to_owned());
9518        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
9519        assert_eq!(t.status, TaskStatus::Held);
9520        let d = t.diagnostic.expect("a held task must carry its diagnostic");
9521        assert!(d.contains("cargo test"), "{d}");
9522    }
9523
9524    #[test]
9525    fn a_held_task_names_the_open_question_it_is_waiting_on() {
9526        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
9527        // `magi ask` question settled Held with `hold_reason: null`, so the
9528        // notification said nothing actionable. `note_open_question` should
9529        // append the question id to whatever `handed_off` already wrote.
9530        crate::run::pin_test_home();
9531        let home = crate::run::home();
9532        let state = run_state(RunStatus::VerifiedNoop);
9533        let mut q = ask::Question::new(
9534            state.id.clone(),
9535            "implement".to_owned(),
9536            "impl-A".to_owned(),
9537            "is this really a no-op?".to_owned(),
9538            String::new(),
9539            Vec::new(),
9540        );
9541        Questions::at(home.join("questions")).put(&mut q).unwrap();
9542
9543        let verdict = Verdict {
9544            status: RunStatus::VerifiedNoop,
9545            left_pr: false,
9546            quota_hit: false,
9547            parked: false,
9548            no_viable_candidates: false,
9549        };
9550        let mut t = task();
9551        t.start(state.id.clone());
9552        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9553
9554        assert_eq!(t.status, TaskStatus::Held);
9555        let reason = t.hold_reason.expect("a held task must record why");
9556        assert!(
9557            reason.starts_with("run ended agent-verified no-op"),
9558            "the original settle reason must survive unchanged: {reason}"
9559        );
9560        assert!(
9561            reason.contains(q.short()),
9562            "the open question's id must be named so the notice is actionable: {reason}"
9563        );
9564    }
9565
9566    #[test]
9567    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
9568        crate::run::pin_test_home();
9569        let state = run_state(RunStatus::VerifiedNoop);
9570
9571        let verdict = Verdict {
9572            status: RunStatus::VerifiedNoop,
9573            left_pr: false,
9574            quota_hit: false,
9575            parked: false,
9576            no_viable_candidates: false,
9577        };
9578        let mut t = task();
9579        t.start(state.id.clone());
9580        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
9581
9582        assert_eq!(t.status, TaskStatus::Held);
9583        assert_eq!(
9584            t.hold_reason.as_deref(),
9585            Some("run ended agent-verified no-op"),
9586            "nothing to append when the question was already answered or never asked"
9587        );
9588    }
9589
9590    #[test]
9591    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
9592        crate::run::pin_test_home();
9593        let mut first = run_state(RunStatus::Blocked);
9594        first.id = "20260101-000000-sup1".to_owned();
9595        first.save().unwrap();
9596        let mut second = run_state(RunStatus::Merged);
9597        second.id = "20260101-000000-sup2".to_owned();
9598        second.save().unwrap();
9599
9600        let mut t = task();
9601        t.runs = vec![first.id.clone(), second.id.clone()];
9602        t.status = TaskStatus::Done;
9603
9604        supersede_prior_runs(&t, &crate::run::home());
9605
9606        assert_eq!(
9607            RunState::load(&first.id).unwrap().status,
9608            RunStatus::Superseded,
9609            "the first attempt's Blocked no longer needs anyone's attention"
9610        );
9611        assert_eq!(
9612            RunState::load(&second.id).unwrap().status,
9613            RunStatus::Merged,
9614            "the run that actually succeeded is left exactly as it was"
9615        );
9616    }
9617
9618    #[test]
9619    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
9620        // `is_working_on` alone only proves a *daemon* claim; a `magi run
9621        // --resume` invoked by hand outside the daemon never touches
9622        // `daemon.json` at all, so it would look identical to a genuinely
9623        // idle run without also consulting `RunState::liveness`, which reads
9624        // this run's own recorded `driver_pid` instead.
9625        crate::run::pin_test_home();
9626        let mut first = run_state(RunStatus::Blocked);
9627        first.id = "20260101-000000-sup9".to_owned();
9628        // This test process's own pid: guaranteed alive without needing a
9629        // real second process or daemon.
9630        first.driver_pid = Some(std::process::id());
9631        first.driver_started_at = Some(
9632            crate::proc::process_started_at(std::process::id())
9633                .expect("this test process's own start time must be queryable"),
9634        );
9635        first.save().unwrap();
9636        let mut second = run_state(RunStatus::Merged);
9637        second.id = "20260101-000000-supa".to_owned();
9638        second.save().unwrap();
9639
9640        let mut t = task();
9641        t.runs = vec![first.id.clone(), second.id.clone()];
9642        t.status = TaskStatus::Done;
9643
9644        supersede_prior_runs(&t, &crate::run::home());
9645
9646        assert_eq!(
9647            RunState::load(&first.id).unwrap().status,
9648            RunStatus::Blocked,
9649            "a live driver_pid means something is still actually working this run, \
9650             even though no daemon claims it - rewriting under it would just be \
9651             undone the next time that process saves"
9652        );
9653    }
9654
9655    #[test]
9656    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
9657        // The first resweep must skip a still-live attempt exactly like
9658        // `supersede_prior_runs` itself does; a later resweep, once that
9659        // process is no longer actually driving it, is what closes the gap
9660        // `supersede_prior_runs` alone leaves - a task only ever reaches
9661        // `Done` once, so nothing else would ever look at this run again.
9662        let dir = tempfile::tempdir().unwrap();
9663        let home = dir.path().to_path_buf();
9664        let queue = Queue::at(dir.path().join("queue"));
9665
9666        let mut first = run_state(RunStatus::Blocked);
9667        first.id = "20260101-000000-supd".to_owned();
9668        first.driver_pid = Some(std::process::id());
9669        first.driver_started_at = Some(
9670            crate::proc::process_started_at(std::process::id())
9671                .expect("this test process's own start time must be queryable"),
9672        );
9673        first.save_under(&home).unwrap();
9674        let mut second = run_state(RunStatus::Merged);
9675        second.id = "20260101-000000-supe".to_owned();
9676        second.save_under(&home).unwrap();
9677
9678        let mut t = task();
9679        t.runs = vec![first.id.clone(), second.id.clone()];
9680        t.status = TaskStatus::Done;
9681        queue.put(&mut t).unwrap();
9682
9683        resweep_superseded_attempts(&queue, &home);
9684        assert_eq!(
9685            RunState::load_under(&first.id, &home).unwrap().status,
9686            RunStatus::Blocked,
9687            "still live on the first pass, so still untouched"
9688        );
9689
9690        // Stand in for the manual process no longer being the one driving
9691        // this run: same pid (this test process really is still alive), but
9692        // an identity marker that no longer matches it - see
9693        // `RunState::liveness`'s own doc for why a mismatched
9694        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
9695        let mut stale = RunState::load_under(&first.id, &home).unwrap();
9696        stale.driver_started_at = Some("1".to_owned());
9697        stale.save_under(&home).unwrap();
9698
9699        resweep_superseded_attempts(&queue, &home);
9700        assert_eq!(
9701            RunState::load_under(&first.id, &home).unwrap().status,
9702            RunStatus::Superseded,
9703            "the second pass catches up what the first one correctly skipped"
9704        );
9705    }
9706
9707    #[test]
9708    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
9709        crate::run::pin_test_home();
9710        let mut first = run_state(RunStatus::Blocked);
9711        first.id = "20260101-000000-sup3".to_owned();
9712        first.save().unwrap();
9713        let mut second = run_state(RunStatus::Blocked);
9714        second.id = "20260101-000000-sup4".to_owned();
9715        second.save().unwrap();
9716
9717        let mut t = task();
9718        t.runs = vec![first.id.clone(), second.id.clone()];
9719        // Still retrying: nothing about this task's story is settled yet, so
9720        // neither Blocked run may be relabelled, even though a later attempt
9721        // already exists.
9722        t.status = TaskStatus::Failed;
9723
9724        supersede_prior_runs(&t, &crate::run::home());
9725
9726        assert_eq!(
9727            RunState::load(&first.id).unwrap().status,
9728            RunStatus::Blocked
9729        );
9730        assert_eq!(
9731            RunState::load(&second.id).unwrap().status,
9732            RunStatus::Blocked
9733        );
9734    }
9735
9736    #[test]
9737    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
9738        // `magi task done` (or the API's equivalent) can close a task with no
9739        // run of its own ever having succeeded - there is nothing here that
9740        // counts as "the attempt that finished it", so nothing is rewritten.
9741        crate::run::pin_test_home();
9742        let mut first = run_state(RunStatus::Blocked);
9743        first.id = "20260101-000000-sup5".to_owned();
9744        first.save().unwrap();
9745
9746        let mut t = task();
9747        t.runs = vec![first.id.clone()];
9748        t.status = TaskStatus::Done;
9749
9750        supersede_prior_runs(&t, &crate::run::home());
9751
9752        assert_eq!(
9753            RunState::load(&first.id).unwrap().status,
9754            RunStatus::Blocked,
9755            "a single-attempt task has no earlier run to supersede"
9756        );
9757    }
9758
9759    #[test]
9760    fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
9761        // `magi task done` (or the web/conductor equivalents) can close a
9762        // task in any status, including one whose *last* recorded attempt is
9763        // itself still `Blocked`/`Failed` - a manual merge magi's own loop
9764        // never watched, say. `runs.last()` being `Done`-adjacent is not
9765        // proof it actually succeeded, so nothing earlier may be relabelled
9766        // on its say-so alone.
9767        crate::run::pin_test_home();
9768        let mut first = run_state(RunStatus::Blocked);
9769        first.id = "20260101-000000-supb".to_owned();
9770        first.save().unwrap();
9771        let mut second = run_state(RunStatus::Failed);
9772        second.id = "20260101-000000-supc".to_owned();
9773        second.save().unwrap();
9774
9775        let mut t = task();
9776        t.runs = vec![first.id.clone(), second.id.clone()];
9777        t.status = TaskStatus::Done;
9778
9779        supersede_prior_runs(&t, &crate::run::home());
9780
9781        assert_eq!(
9782            RunState::load(&first.id).unwrap().status,
9783            RunStatus::Blocked,
9784            "the task's last attempt never landed, so there is nothing here \
9785             actually superseding it"
9786        );
9787    }
9788
9789    #[test]
9790    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
9791        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
9792        // to look" - `Failed` and `VerifiedNoop` are already their own
9793        // terminal answers and must not be relabelled into a third one.
9794        crate::run::pin_test_home();
9795        let mut failed = run_state(RunStatus::Failed);
9796        failed.id = "20260101-000000-sup6".to_owned();
9797        failed.save().unwrap();
9798        let mut noop = run_state(RunStatus::VerifiedNoop);
9799        noop.id = "20260101-000000-sup7".to_owned();
9800        noop.save().unwrap();
9801        let mut winner = run_state(RunStatus::Ready);
9802        winner.id = "20260101-000000-sup8".to_owned();
9803        winner.save().unwrap();
9804
9805        let mut t = task();
9806        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
9807        t.status = TaskStatus::Done;
9808
9809        supersede_prior_runs(&t, &crate::run::home());
9810
9811        assert_eq!(
9812            RunState::load(&failed.id).unwrap().status,
9813            RunStatus::Failed
9814        );
9815        assert_eq!(
9816            RunState::load(&noop.id).unwrap().status,
9817            RunStatus::VerifiedNoop
9818        );
9819    }
9820
9821    fn approval_question(run: &str) -> ask::Question {
9822        ask::Question::new(
9823            run.to_owned(),
9824            land::APPROVAL_NODE.to_owned(),
9825            "land".to_owned(),
9826            "merge?".to_owned(),
9827            String::new(),
9828            vec!["merge".to_owned(), "hold".to_owned()],
9829        )
9830    }
9831
9832    #[test]
9833    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
9834        crate::run::pin_test_home();
9835        let mut state = run_state(RunStatus::Landing);
9836        state.id = "20260101-000000-fre1".to_owned();
9837        state.parked = true;
9838        state.save().unwrap();
9839        ask::Questions::open()
9840            .put(&mut approval_question(&state.id))
9841            .unwrap();
9842
9843        let mut t = task();
9844        t.runs.push(state.id.clone());
9845        assert_eq!(
9846            land_resume_state(&t),
9847            LandResume::StillWaiting,
9848            "nobody has answered and the timeout has not passed"
9849        );
9850    }
9851
9852    #[test]
9853    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
9854        crate::run::pin_test_home();
9855        let mut state = run_state(RunStatus::Gating);
9856        state.id = "20260101-000000-gt01".to_owned();
9857        state.parked = true;
9858        state.config.graph.answer_timeout = 60;
9859        state.github_text = Some(crate::run::GithubTextAsk {
9860            rewrite: None,
9861            fingerprint: "f".into(),
9862            title: true,
9863            body: false,
9864            categories: vec!["title-language".into()],
9865            question: None,
9866            asks: 1,
9867            resolved: false,
9868            chosen_title: None,
9869            choice: None,
9870            publication: None,
9871        });
9872        state.save().unwrap();
9873        let store = ask::Questions::open();
9874        let mut q = ask::Question::new(
9875            state.id.clone(),
9876            crate::github_text::ASK_NODE.to_owned(),
9877            crate::github_text::ASK_SEAT.to_owned(),
9878            "s".into(),
9879            String::new(),
9880            vec!["use fallback".into()],
9881        );
9882        store.put(&mut q).unwrap();
9883        let mut t = task();
9884        t.runs.push(state.id.clone());
9885        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
9886        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9887        store.put(&mut q).unwrap();
9888        assert_eq!(land_resume_state(&t), LandResume::Ready);
9889        assert!(!store.get(&q.id).unwrap().status.open());
9890        // Once decided, a parked run is an ordinary candidate again.
9891        state.github_text.as_mut().unwrap().resolved = true;
9892        state.save().unwrap();
9893        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
9894    }
9895
9896    #[test]
9897    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
9898        // `ask::ask_and_wait`'s own deadline used to retire a question
9899        // nobody answered; land's approval bypasses that wait (see
9900        // `land::approval_gate`), so this is now the only place
9901        // `graph.answer_timeout` is enforced for a land approval at all.
9902        crate::run::pin_test_home();
9903        let mut state = run_state(RunStatus::Landing);
9904        state.id = "20260101-000000-exp1".to_owned();
9905        state.parked = true;
9906        state.config.graph.answer_timeout = 60;
9907        state.save().unwrap();
9908
9909        let store = ask::Questions::open();
9910        let mut q = approval_question(&state.id);
9911        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
9912        store.put(&mut q).unwrap();
9913
9914        let mut t = task();
9915        t.runs.push(state.id.clone());
9916        assert_eq!(
9917            land_resume_state(&t),
9918            LandResume::Ready,
9919            "an expired question must not be waited on forever"
9920        );
9921
9922        let after = store.get(&q.id).unwrap();
9923        assert!(
9924            !after.status.open(),
9925            "the question is abandoned, not silently ignored"
9926        );
9927        assert!(
9928            after.resolution().is_none(),
9929            "an abandoned question is not read as a decision"
9930        );
9931    }
9932
9933    #[test]
9934    fn reclaim_settles_a_running_task_against_its_last_run() {
9935        let mut t = task();
9936        t.start("20260904-000000-4043".to_owned());
9937        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
9938        assert_eq!(
9939            t.status,
9940            TaskStatus::Done,
9941            "a run that actually finished must not stay `running` forever"
9942        );
9943    }
9944
9945    #[test]
9946    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
9947        let dir = tempfile::tempdir().unwrap();
9948        let queue = Queue::at(dir.path().join("queue"));
9949        let mut task = task();
9950        let mut run = run_state(RunStatus::Blocked);
9951        run.reserve_under(dir.path()).unwrap();
9952        run.driver_exited = true;
9953        run.save_under(dir.path()).unwrap();
9954        queue.put(&mut task).unwrap();
9955        let stale = task.clone();
9956        task.resume_override = Some(crate::queue::OperatorResume {
9957            question_id: "pending-resume".into(),
9958            at: Timestamp::now(),
9959            conductor_rehold: None,
9960            forced: true,
9961            pinned_run: Some(run.id.clone()),
9962        });
9963        task.start(run.id.clone());
9964        queue.put(&mut task).unwrap();
9965        // Discard every in-memory handoff, as a worker death before execute does.
9966        let mut recovered = queue.get(&task.id).unwrap();
9967        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
9968        reclaim(&mut recovered, Some(disk), 2, "en");
9969        queue.put(&mut recovered).unwrap();
9970        assert!(recovered.resume_override.is_none());
9971        assert_eq!(
9972            recovered.dispatched_resumes.get("pending-resume"),
9973            Some(&run.id)
9974        );
9975        let mut stale = stale;
9976        queue.put(&mut stale).unwrap();
9977        assert_eq!(
9978            stale.dispatched_resumes, recovered.dispatched_resumes,
9979            "a stale task writer cannot erase dispatch ownership"
9980        );
9981        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
9982        assert!(resumed.decision_starts.is_empty());
9983        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
9984        assert!(
9985            resumed.decision_starts.is_empty(),
9986            "handoff is not execution proof"
9987        );
9988        resumed.begin_pass();
9989        resumed.save_under(dir.path()).unwrap();
9990        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
9991        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
9992        disk.carry_dispatched_resumes(&recovered);
9993        disk.begin_pass();
9994        assert_eq!(
9995            disk.decision_starts.get("pending-resume"),
9996            Some(&0),
9997            "later execution must preserve the original pass receipt"
9998        );
9999    }
10000
10001    #[test]
10002    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10003        let mut t = task();
10004        t.start("20260904-000000-4043".to_owned());
10005        t.last_error = Some("earlier trouble".to_owned());
10006        let mut state = run_state(RunStatus::Judging);
10007        state.parked = true;
10008        reclaim(&mut t, Some(state), 1, "en");
10009        assert_eq!(t.status, TaskStatus::Parked);
10010        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10011        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10012        assert!(t.park_reason.is_some());
10013        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10014        assert!(!t.fresh_start);
10015        assert!(t.status.runnable());
10016    }
10017
10018    #[test]
10019    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10020        let mut t = task();
10021        t.start("20260904-000000-4043".to_owned());
10022        t.last_error = Some("earlier trouble".to_owned());
10023        settle(
10024            &mut t,
10025            Verdict {
10026                status: RunStatus::Judging,
10027                left_pr: false,
10028                quota_hit: false,
10029                parked: true,
10030                no_viable_candidates: false,
10031            },
10032            "parked after `judging`",
10033            1,
10034        );
10035        assert_eq!(t.status, TaskStatus::Parked);
10036        assert_eq!(t.attempts, 0);
10037        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10038        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10039        assert_eq!(t.schema, crate::queue::SCHEMA);
10040        assert!(
10041            crate::notices::task_held(&t).is_none(),
10042            "a park is not news"
10043        );
10044        t.start("20260904-000000-4043".to_owned());
10045        assert_eq!(t.park_reason, None);
10046    }
10047
10048    #[test]
10049    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10050        // A blocked run with attempts left goes back to `Failed`, exactly as
10051        // it would from `attempt` itself - `reclaim` must not invent a second
10052        // policy for a task a daemon merely stopped without reporting.
10053        let mut t = task();
10054        t.start("20260904-000000-4043".to_owned());
10055        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10056        assert_eq!(t.status, TaskStatus::Failed);
10057        assert!(t.status.runnable());
10058    }
10059
10060    #[test]
10061    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10062        let mut t = task();
10063        t.start("20260904-000000-4043".to_owned());
10064        assert_eq!(t.attempts, 1);
10065        let mut run = run_state(RunStatus::Implementing);
10066        run.id = "20260904-000000-4043".to_owned();
10067        run.begin_pass();
10068        let cause = crate::run::ParkCause::Upgrade {
10069            from: "0.121.0".to_owned(),
10070            to: Some("0.121.1".to_owned()),
10071        };
10072        run.end_pass_parked(cause.clone());
10073        run.parked = true;
10074        let verdict = Verdict {
10075            status: run.status,
10076            left_pr: false,
10077            quota_hit: false,
10078            parked: true,
10079            no_viable_candidates: false,
10080        };
10081        // A crash after the checkpoint but before queue settlement must
10082        // recover exactly the same scheduling evidence and refund.
10083        let mut orphan = t.clone();
10084        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10085        assert_eq!(orphan.status, TaskStatus::Parked);
10086        assert_eq!(orphan.attempts, 0);
10087        assert_eq!(
10088            orphan.upgrade_resume_key(),
10089            Some((run.passes[0].started_at, orphan.id.as_str()))
10090        );
10091        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10092        assert_eq!(t.attempts, 0);
10093        assert_eq!(t.passes.len(), 1);
10094        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10095        assert_eq!(t.passes[0].parked, Some(cause));
10096        assert_eq!(t.passes[0].pass_index, 0);
10097        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10098        assert!(t.upgrade_resume_key().is_some());
10099
10100        // A resumed pass that then fails spends its attempt, and the earlier
10101        // pass's entry is untouched.
10102        t.start("20260904-000000-4043".to_owned());
10103        run.begin_pass();
10104        run.status = RunStatus::Failed;
10105        let verdict = Verdict {
10106            status: RunStatus::Failed,
10107            left_pr: false,
10108            quota_hit: false,
10109            parked: false,
10110            no_viable_candidates: false,
10111        };
10112        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10113        assert_eq!(t.passes.len(), 2);
10114        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10115        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10116        assert_eq!(t.passes[1].pass_index, 1);
10117        assert_eq!(t.attempts, 1);
10118    }
10119
10120    #[test]
10121    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10122        let mut t = task();
10123        t.start("20260904-000000-4043".to_owned());
10124        reclaim(&mut t, None, 2, "en");
10125        assert_eq!(t.status, TaskStatus::Held);
10126        assert!(
10127            t.last_error
10128                .as_deref()
10129                .is_some_and(|e| e.contains("running")),
10130            "the operator needs to know why this task was held"
10131        );
10132    }
10133
10134    #[test]
10135    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10136        let dir = tempfile::tempdir().unwrap();
10137        let queue = Queue::at(dir.path().to_path_buf());
10138
10139        // No run recorded, so this never has to touch `RunState::load`.
10140        let mut orphaned = task();
10141        orphaned.id = "20260904-000000-orph".to_owned();
10142        orphaned.status = TaskStatus::Running;
10143        orphaned.attempts = 1;
10144        queue.put(&mut orphaned).unwrap();
10145
10146        let mut alive = task();
10147        alive.id = "20260904-000000-live".to_owned();
10148        alive.status = TaskStatus::Running;
10149        alive.attempts = 1;
10150        queue.put(&mut alive).unwrap();
10151        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10152
10153        let mut queued = task();
10154        queued.id = "20260904-000000-wait".to_owned();
10155        queue.put(&mut queued).unwrap();
10156
10157        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10158        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10159
10160        assert_eq!(
10161            queue.get(&orphaned.id).unwrap().status,
10162            TaskStatus::Held,
10163            "nothing was driving it and there was no run to recover"
10164        );
10165        assert_eq!(
10166            queue.get(&alive.id).unwrap().status,
10167            TaskStatus::Running,
10168            "a live claim must protect the task it belongs to"
10169        );
10170        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10171    }
10172
10173    /// Read a run.json back from an explicit `home`, the same way
10174    /// `reclaim_abandoned_runs` itself does - never through the
10175    /// process-global `RunState::load`, which this test's own `home` (an
10176    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10177    /// use at all.
10178    fn read_run_under(home: &Path, id: &str) -> RunState {
10179        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10180        serde_json::from_str(&body).unwrap()
10181    }
10182
10183    #[test]
10184    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10185        let dir = tempfile::tempdir().unwrap();
10186        let home = dir.path().to_path_buf();
10187        let now = Timestamp::now();
10188        let overrun_seat = || crate::run::ActiveSeat {
10189            node: "implement".to_owned(),
10190            started_at: now - jiff::SignedDuration::new(21_000, 0),
10191            timeout_secs: 3_600,
10192            attempt: 0,
10193            task: None,
10194            command: None,
10195            index: None,
10196            total: None,
10197        };
10198
10199        let mut dead = run_state(RunStatus::Implementing);
10200        dead.id = "20260101-000000-dead".to_owned();
10201        dead.active.insert("impl-A".to_owned(), overrun_seat());
10202        // A `driver_pid` the injected query below confirms gone outright —
10203        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10204        dead.driver_pid = Some(4242);
10205        dead.save_under(&home).unwrap();
10206
10207        // Same shape, but a live daemon's heartbeat names it: must be left
10208        // exactly alone, however far past its own timeout the seat sits.
10209        let mut alive = run_state(RunStatus::Implementing);
10210        alive.id = "20260101-000000-aliv".to_owned();
10211        alive.active.insert("impl-A".to_owned(), overrun_seat());
10212        alive.save_under(&home).unwrap();
10213        let mut status = Status::new();
10214        status.current = vec![Current {
10215            worker: None,
10216            task: "20260101-000000-task".to_owned(),
10217            run: alive.id.clone(),
10218        }];
10219        write_status_to(&home.join("daemon.json"), &status).unwrap();
10220
10221        // The abandoned seat left an open question behind: nobody is left to
10222        // read an answer once the run is failed, and this must not wait for
10223        // some later daemon startup's own sweep to notice that.
10224        let questions = Questions::at(home.join("questions"));
10225        let mut q = ask::Question::new(
10226            dead.id.clone(),
10227            "implement".to_owned(),
10228            "impl-A".to_owned(),
10229            "Which storage backend?".to_owned(),
10230            String::new(),
10231            vec!["SQLite".to_owned(), "Redis".to_owned()],
10232        );
10233        questions.put(&mut q).unwrap();
10234
10235        let abandoned = reclaim_abandoned_runs_with(
10236            &home,
10237            now,
10238            |pid| if pid == 4242 { Some(false) } else { None },
10239            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10240        );
10241        assert_eq!(abandoned, vec![dead.id.clone()]);
10242
10243        let reloaded = read_run_under(&home, &dead.id);
10244        assert_eq!(reloaded.status, RunStatus::Failed);
10245        assert!(reloaded.active.is_empty());
10246        assert!(
10247            !questions.get(&q.id).unwrap().status.open(),
10248            "the failed run's own open question must be settled in the same pass"
10249        );
10250
10251        let still_alive = read_run_under(&home, &alive.id);
10252        assert_eq!(
10253            still_alive.status,
10254            RunStatus::Implementing,
10255            "a live daemon's claim protects it"
10256        );
10257        assert!(!still_alive.active.is_empty());
10258    }
10259
10260    /// The exact shape a review round flagged as broken: `magi serve` running
10261    /// in this same `home` scans *every* run on disk, including a manual
10262    /// `magi review` / `magi run` this daemon never started and that
10263    /// therefore claims no heartbeat of its own. Before this scan asked
10264    /// `liveness` rather than just `is_working_on`, a manual run whose active
10265    /// seat merely ran a little past its own timeout — the CLI finishing up,
10266    /// its result still being collected — got wiped and failed by a daemon
10267    /// that had nothing to do with it, out from under a process that was
10268    /// still very much running.
10269    #[test]
10270    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10271        let dir = tempfile::tempdir().unwrap();
10272        let home = dir.path().to_path_buf();
10273        let now = Timestamp::now();
10274
10275        let mut manual = run_state(RunStatus::Reviewing);
10276        manual.id = "20260101-000000-manl".to_owned();
10277        manual.active.insert(
10278            "review-1".to_owned(),
10279            crate::run::ActiveSeat {
10280                node: "review".to_owned(),
10281                started_at: now - jiff::SignedDuration::new(21_000, 0),
10282                timeout_secs: 3_600,
10283                attempt: 0,
10284                task: None,
10285                command: None,
10286                index: None,
10287                total: None,
10288            },
10289        );
10290        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10291        // but a real, still-running process: `liveness` must corroborate this
10292        // as `Live`, not read the missing daemon claim as death.
10293        manual.driver_pid = Some(4242);
10294        manual.driver_started_at = Some("1790000000".to_owned());
10295        manual.save_under(&home).unwrap();
10296
10297        let abandoned = reclaim_abandoned_runs_with(
10298            &home,
10299            now,
10300            |pid| if pid == 4242 { Some(true) } else { None },
10301            |pid| {
10302                if pid == 4242 {
10303                    Some("1790000000".to_owned())
10304                } else {
10305                    None
10306                }
10307            },
10308        );
10309        assert!(
10310            abandoned.is_empty(),
10311            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10312        );
10313
10314        let reloaded = read_run_under(&home, &manual.id);
10315        assert_eq!(reloaded.status, RunStatus::Reviewing);
10316        assert!(!reloaded.active.is_empty());
10317    }
10318
10319    #[test]
10320    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10321        let dir = tempfile::tempdir().unwrap();
10322        let queue = Queue::at(dir.path().to_path_buf());
10323        let mut only = task();
10324        queue.put(&mut only).unwrap();
10325
10326        let _elsewhere = queue.claim(&only.id).unwrap();
10327        let candidates = runnable(&queue);
10328        assert_eq!(candidates.len(), 1, "the task is still runnable");
10329        assert!(
10330            queue.claim(&candidates[0].id).is_err(),
10331            "the loop cannot take a claim somebody else holds"
10332        );
10333
10334        let after = queue.get(&only.id).unwrap();
10335        assert_eq!(after.status, TaskStatus::Queued);
10336        assert_eq!(
10337            after.attempts, 0,
10338            "losing the race is not an attempt at the task"
10339        );
10340        assert_eq!(after.last_error, None);
10341    }
10342
10343    #[test]
10344    fn the_status_file_round_trips_and_its_heartbeat_advances() {
10345        let dir = tempfile::tempdir().unwrap();
10346        let path = dir.path().join("daemon.json");
10347
10348        let mut status = Status::new();
10349        status.idle = false;
10350        status.completed = 7;
10351        status.current = vec![Current {
10352            worker: None,
10353            task: "20260902-000000-t111".to_owned(),
10354            run: "20260902-000001-r111".to_owned(),
10355        }];
10356        write_status_to(&path, &status).unwrap();
10357        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10358        assert_eq!(first.schema, SCHEMA);
10359        assert_eq!(first.pid, std::process::id());
10360        assert!(!first.idle);
10361        assert_eq!(first.completed, 7);
10362        assert_eq!(first.current, status.current);
10363        assert!(
10364            !path.with_extension("json.tmp").exists(),
10365            "the temp file is renamed, not left behind"
10366        );
10367
10368        std::thread::sleep(Duration::from_millis(5));
10369        status.updated_at = Timestamp::now();
10370        status.polls = 3;
10371        write_status_to(&path, &status).unwrap();
10372        let second: Status =
10373            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
10374        assert!(
10375            second.updated_at > first.updated_at,
10376            "a reader can only detect staleness if the heartbeat moves"
10377        );
10378        assert_eq!(
10379            second.started_at, first.started_at,
10380            "the start time is not a heartbeat"
10381        );
10382        assert_eq!(second.polls, 3);
10383    }
10384
10385    #[test]
10386    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
10387        let dir = tempfile::tempdir().unwrap();
10388
10389        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
10390
10391        let mut status = Status::new();
10392        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
10393        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10394        let stale = read_status(dir.path()).unwrap();
10395        assert!(
10396            !stale.running(Timestamp::now()),
10397            "a minute without a heartbeat is a dead daemon, not a busy one"
10398        );
10399        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
10400
10401        status.updated_at = Timestamp::now();
10402        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10403        let fresh = read_status(dir.path()).unwrap();
10404        assert!(fresh.running(Timestamp::now()));
10405    }
10406
10407    #[test]
10408    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
10409        let dir = tempfile::tempdir().unwrap();
10410        let now = Timestamp::now();
10411        let mine = "20260903-080619-01c2";
10412
10413        assert!(
10414            !is_working_on(dir.path(), mine, now),
10415            "no status file means nobody is working on anything"
10416        );
10417
10418        let mut status = Status::new();
10419        status.current = vec![Current {
10420            worker: None,
10421            task: "20260903-080340-0167".to_owned(),
10422            run: mine.to_owned(),
10423        }];
10424        status.updated_at = now;
10425        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10426        assert!(is_working_on(dir.path(), mine, now));
10427        assert!(
10428            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
10429            "a daemon busy with one run is not working on another"
10430        );
10431
10432        // A killed daemon stops writing heartbeats but leaves the file behind
10433        // naming the run it died in. That run must not be undeletable forever.
10434        status.updated_at = now - jiff::SignedDuration::from_secs(600);
10435        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10436        assert!(
10437            !is_working_on(dir.path(), mine, now),
10438            "a stale heartbeat is a dead daemon, so its run is a leftover"
10439        );
10440    }
10441
10442    #[test]
10443    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
10444        let dir = tempfile::tempdir().unwrap();
10445        let now = Timestamp::now();
10446
10447        assert!(
10448            !is_working_on_short(dir.path(), "01c2", now),
10449            "no status file means nobody is working on anything"
10450        );
10451
10452        let mut status = Status::new();
10453        status.current = vec![Current {
10454            worker: None,
10455            task: "20260903-080340-0167".to_owned(),
10456            run: "20260903-080619-01c2".to_owned(),
10457        }];
10458        status.updated_at = now;
10459        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
10460        assert!(
10461            is_working_on_short(dir.path(), "01c2", now),
10462            "the run's short id is the last block of its full id"
10463        );
10464        assert!(
10465            !is_working_on_short(dir.path(), "3cbf", now),
10466            "a daemon busy with one worktree bay is not working on another"
10467        );
10468    }
10469
10470    #[test]
10471    fn a_newer_status_file_still_yields_a_reading() {
10472        let dir = tempfile::tempdir().unwrap();
10473        // A field this build has never heard of must not turn the reading into
10474        // nothing at all; that is the whole reason the reader is permissive.
10475        std::fs::write(
10476            dir.path().join("daemon.json"),
10477            serde_json::json!({
10478                "schema": 2,
10479                "updated_at": Timestamp::now().to_string(),
10480                "idle": true,
10481                "surprise": { "nested": [1, 2, 3] },
10482            })
10483            .to_string(),
10484        )
10485        .unwrap();
10486
10487        let reading = read_status(dir.path()).expect("a forward-compatible read");
10488        assert!(reading.running(Timestamp::now()));
10489        assert!(reading.idle);
10490        assert!(reading.current.is_empty());
10491    }
10492
10493    #[test]
10494    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
10495        // A daemon started before `current` became a list keeps writing this
10496        // shape on every heartbeat until it is restarted. A rolling upgrade
10497        // - a newer `magi web` or `magi doctor` reading an older `magi
10498        // serve`'s heartbeat - must still see the run it is on, not "no
10499        // daemon" from a type mismatch failing the whole struct.
10500        let dir = tempfile::tempdir().unwrap();
10501        std::fs::write(
10502            dir.path().join("daemon.json"),
10503            serde_json::json!({
10504                "schema": 1,
10505                "pid": 4242,
10506                "updated_at": Timestamp::now().to_string(),
10507                "idle": false,
10508                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
10509                "completed": 3,
10510                "polls": 9,
10511            })
10512            .to_string(),
10513        )
10514        .unwrap();
10515
10516        let reading = read_status(dir.path()).expect("an older shape must still parse");
10517        assert!(reading.running(Timestamp::now()));
10518        assert_eq!(
10519            reading.current,
10520            vec![Current {
10521                worker: None,
10522                task: "20260902-140501-aaaa".to_owned(),
10523                run: "20260902-140502-bbbb".to_owned(),
10524            }]
10525        );
10526    }
10527
10528    #[test]
10529    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
10530        let dir = tempfile::tempdir().unwrap();
10531        std::fs::write(
10532            dir.path().join("daemon.json"),
10533            serde_json::json!({
10534                "schema": 1,
10535                "updated_at": Timestamp::now().to_string(),
10536                "idle": true,
10537                "current": null,
10538            })
10539            .to_string(),
10540        )
10541        .unwrap();
10542        let with_null = read_status(dir.path()).expect("null must still parse");
10543        assert!(with_null.current.is_empty());
10544
10545        std::fs::write(
10546            dir.path().join("daemon.json"),
10547            serde_json::json!({
10548                "schema": 1,
10549                "updated_at": Timestamp::now().to_string(),
10550                "idle": true,
10551            })
10552            .to_string(),
10553        )
10554        .unwrap();
10555        let absent = read_status(dir.path()).expect("a missing field must still parse");
10556        assert!(absent.current.is_empty());
10557    }
10558
10559    #[test]
10560    fn a_task_without_a_repository_runs_in_the_daemons_default() {
10561        let fallback = Path::new("/default");
10562        let mut blank = task();
10563        blank.repo = PathBuf::new();
10564        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
10565        let mut dot = task();
10566        dot.repo = PathBuf::from(".");
10567        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
10568        assert_eq!(
10569            repo_for(&task(), fallback),
10570            PathBuf::from("/repo"),
10571            "a task that names a repository keeps it"
10572        );
10573    }
10574
10575    #[test]
10576    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
10577        let dir = tempfile::tempdir().unwrap();
10578        let repo = dir.path();
10579        let path = repo.join("explicit.toml");
10580        std::fs::write(
10581            &path,
10582            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
10583        )
10584        .unwrap();
10585        let opts = Opts {
10586            config: Some(path),
10587            ..Opts::default()
10588        };
10589        let queue = Queue::at(repo.join("queue"));
10590        let mut new = task();
10591        queue.put(&mut new).unwrap();
10592        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
10593        assert_eq!(
10594            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
10595            BuildCache::Isolated
10596        );
10597
10598        let mut old = task();
10599        old.schema = 22;
10600        queue.put(&mut old).unwrap();
10601        let mut old = queue.get(&old.id).unwrap();
10602        let config = resolved(&old);
10603        assert_eq!(config.verify.build_cache, BuildCache::Shared);
10604        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
10605        old.hold_manual(Some("wait".into()));
10606        queue.put(&mut old).unwrap();
10607
10608        let mut saved = queue.get(&old.id).unwrap();
10609        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
10610        saved
10611            .overrides
10612            .as_mut()
10613            .unwrap()
10614            .merge_over(&crate::queue::RunOverrides {
10615                build_cache: Some(BuildCache::Isolated),
10616                ..Default::default()
10617            });
10618        queue.put(&mut saved).unwrap();
10619        assert_eq!(
10620            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
10621            BuildCache::Isolated
10622        );
10623    }
10624
10625    #[test]
10626    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
10627        let dir = tempfile::tempdir().unwrap();
10628        let path = dir.path().join("explicit.toml");
10629        let write = |verify: &str| {
10630            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
10631        };
10632        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
10633        let opts = Opts {
10634            config: Some(path.clone()),
10635            ..Opts::default()
10636        };
10637        let mut task = task();
10638        task.set_urgent(true).unwrap();
10639        let resolved = |task: &Task| {
10640            prepare_for(dir.path(), &opts, task)
10641                .unwrap()
10642                .verify
10643                .build_cache
10644        };
10645        assert_eq!(resolved(&task), BuildCache::Isolated);
10646        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
10647        assert_eq!(resolved(&task), BuildCache::Shared);
10648        task.change_build_cache(None).unwrap();
10649        assert_eq!(resolved(&task), BuildCache::Isolated);
10650        task.set_urgent(false).unwrap();
10651        assert_eq!(resolved(&task), BuildCache::Shared);
10652
10653        // Urgent work must never be the one stopped by isolation: with no
10654        // shared cache to wait behind, or with a verification command isolated
10655        // mode cannot run, an urgent task keeps the configured mode.
10656        task.set_urgent(true).unwrap();
10657        write("e2e = [\"npm test\"]\n");
10658        assert_eq!(resolved(&task), BuildCache::Shared);
10659        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
10660        assert_eq!(resolved(&task), BuildCache::Shared);
10661        // An explicit choice stays strict and is applied as asked.
10662        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
10663        assert_eq!(resolved(&task), BuildCache::Isolated);
10664    }
10665
10666    #[test]
10667    fn task_implementers_edit_inherits_daemon_config_and_merge() {
10668        let dir = tempfile::tempdir().unwrap();
10669        let path = dir.path().join("explicit.toml");
10670        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
10671        let opts = Opts {
10672            config: Some(path),
10673            merge: Some("none".into()),
10674            ..Default::default()
10675        };
10676        let mut t = task();
10677        t.set_implementers(
10678            2,
10679            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10680                .unwrap(),
10681        )
10682        .unwrap();
10683        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10684        assert_eq!(cfg.graph.implementers, 2);
10685        assert_eq!(cfg.graph.judges, 1);
10686        assert_eq!(cfg.merge.mode, MergeMode::None);
10687        t.set_implementers(1, &cfg).unwrap();
10688        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
10689        apply_task_implementers(&mut cfg, &t);
10690        assert_eq!(cfg.graph.implementers, 1);
10691        assert_eq!(cfg.graph.judges, 1);
10692        assert_eq!(cfg.merge.mode, MergeMode::None);
10693    }
10694
10695    #[test]
10696    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
10697        let dir = tempfile::tempdir().unwrap();
10698        let repo = dir.path().join("repo");
10699        std::fs::create_dir(&repo).unwrap();
10700        std::fs::write(
10701            repo.join("magi.toml"),
10702            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
10703        )
10704        .unwrap();
10705        let daemon_config = dir.path().join("daemon.toml");
10706        std::fs::write(
10707            &daemon_config,
10708            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
10709        )
10710        .unwrap();
10711        let opts = Opts {
10712            config: Some(daemon_config),
10713            merge: Some("pr".into()),
10714            ..Default::default()
10715        };
10716        let q = Queue::at(dir.path().join("queue"));
10717        let validation: Config =
10718            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10719                .unwrap();
10720        // No provenance field on legacy direct tasks: both shapes stay isolated.
10721        for record in ["{}", r#"{"candidates":2}"#] {
10722            let overrides = serde_json::from_str(record).unwrap();
10723            let filing = crate::direct::Filing {
10724                instruction: "work".into(),
10725                title: "direct".into(),
10726                repo: repo.clone(),
10727                source: crate::queue::Source::Human,
10728                solo: false,
10729                overrides,
10730                review_of: None,
10731                sources: Default::default(),
10732            };
10733            let filed =
10734                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
10735            let crate::direct::Filed::Standalone {
10736                mut task,
10737                claim: _claim,
10738            } = filed
10739            else {
10740                panic!("local filing")
10741            };
10742            let before = prepare_for(&repo, &opts, &task).unwrap();
10743            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
10744            assert_eq!(
10745                before.merge.mode,
10746                MergeMode::None,
10747                "daemon --merge must not leak"
10748            );
10749            for n in [2, 1, 2] {
10750                task.set_implementers(n, &validation).unwrap();
10751                q.put(&mut task).unwrap();
10752                task = q.get(&task.id).unwrap();
10753                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
10754                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
10755                apply_task_implementers(&mut cfg, &task);
10756                assert_eq!(cfg.graph.implementers, usize::from(n));
10757                assert_eq!(cfg.graph.judges, 2);
10758                assert_eq!(cfg.merge.mode, MergeMode::None);
10759            }
10760        }
10761    }
10762
10763    #[test]
10764    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
10765        let cfg: Config =
10766            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10767                .unwrap();
10768        let mut t = task();
10769        t.review_of = Some("review-target".into());
10770        t.hold_manual(Some("retry".into()));
10771        let mut previous = RunState::new(
10772            PathBuf::from("/repo"),
10773            "main".into(),
10774            "abc1234".into(),
10775            "review".into(),
10776            cfg.clone(),
10777        );
10778        previous.config.graph.implementers = 2;
10779        for count in [1, 3] {
10780            t.set_implementers(count, &cfg).unwrap();
10781            t.release();
10782            assert_eq!(t.review_of.as_deref(), Some("review-target"));
10783            for proposed in [
10784                Starter::Resume(previous.id.clone()),
10785                Starter::Review("recovery-target".into()),
10786            ] {
10787                assert_eq!(
10788                    starter_with_implementers(&t, Some(&previous), proposed),
10789                    Starter::Review("review-target".into())
10790                );
10791            }
10792            let mut configured = cfg.clone();
10793            apply_task_implementers(&mut configured, &t);
10794            assert_eq!(configured.graph.implementers, usize::from(count));
10795            assert_eq!(previous.config.graph.implementers, 2);
10796        }
10797    }
10798
10799    #[test]
10800    fn task_implementers_dispatch_and_resume_agree() {
10801        let mut t = task();
10802        let cfg: crate::config::Config =
10803            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
10804                .unwrap();
10805        let mut run = RunState::new(
10806            PathBuf::from("/repo"),
10807            "main".into(),
10808            "abc1234".into(),
10809            "work".into(),
10810            cfg.clone(),
10811        );
10812        run.config.graph.implementers = 2;
10813        for n in [2, 1, 3, 2] {
10814            t.set_implementers(n, &cfg).unwrap();
10815            let mut dispatched = cfg.clone();
10816            apply_task_implementers(&mut dispatched, &t);
10817            assert_eq!(dispatched.graph.implementers, usize::from(n));
10818            assert_eq!(implementers_match(&t, &run), n == 2);
10819            for proposed in [
10820                Starter::Resume(run.id.clone()),
10821                Starter::Review("old-branch".into()),
10822            ] {
10823                let expected = if n == 2 {
10824                    proposed.clone()
10825                } else {
10826                    Starter::Start
10827                };
10828                assert_eq!(
10829                    starter_with_implementers(&t, Some(&run), proposed),
10830                    expected
10831                );
10832            }
10833            assert_eq!(
10834                run.config.graph.implementers, 2,
10835                "history must not be rewritten"
10836            );
10837        }
10838        t.solo = false;
10839        t.overrides = None;
10840        assert!(implementers_match(&t, &run));
10841    }
10842
10843    #[test]
10844    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
10845        // Three seats said out loud. What `solo` promises is one candidate
10846        // *whatever the config asks for*, so the contrast has to be a number
10847        // this test owns - it used to be `Config::default()`'s, which became
10848        // 1 when one implementation became the default and left the two
10849        // halves of this test asserting the same thing.
10850        let mut solo_cfg = Config::default();
10851        solo_cfg.graph.implementers = 3;
10852        let mut solo_task = task();
10853        solo_task.solo = true;
10854        apply_task_implementers(&mut solo_cfg, &solo_task);
10855        assert_eq!(solo_cfg.graph.implementers, 1);
10856
10857        let mut plain_cfg = Config::default();
10858        plain_cfg.graph.implementers = 3;
10859        let plain_task = task();
10860        assert!(!plain_task.solo);
10861        apply_task_implementers(&mut plain_cfg, &plain_task);
10862        assert_eq!(
10863            plain_cfg.graph.implementers, 3,
10864            "a task that did not ask to run alone keeps the config's candidates"
10865        );
10866    }
10867
10868    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
10869        QuotaLoss {
10870            cause: crate::agent::QuotaCause::UsageLimit,
10871            agent: String::new(),
10872            seat: seat.into(),
10873            node: "judge".into(),
10874            at: at.parse().unwrap(),
10875            reset: reset.map(str::to_string),
10876        }
10877    }
10878
10879    #[test]
10880    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
10881        let now = Timestamp::now();
10882        for reset in [None, Some("in 1h")] {
10883            let auth = crate::agent::Quota {
10884                cause: crate::agent::QuotaCause::Authentication,
10885                agent: "alpha".into(),
10886                reset: reset.map(str::to_owned),
10887            };
10888            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
10889            assert_eq!(cooldown_until(&[loss], now), None);
10890        }
10891    }
10892
10893    #[test]
10894    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
10895        let old: Vec<QuotaLoss> = (1..=4)
10896            .map(|i| {
10897                loss(
10898                    &format!("judge-{i}"),
10899                    "2026-09-23T05:23:00Z",
10900                    Some("2:40pm (Asia/Tokyo)"),
10901                )
10902            })
10903            .collect();
10904        let fresh = losses_this_attempt(&old, &old);
10905        assert!(fresh.is_empty());
10906        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
10907        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
10908    }
10909
10910    #[test]
10911    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
10912        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
10913        let now = Timestamp::now();
10914        let mut after = old.clone();
10915        after.push(loss("judge-2", &now.to_string(), None));
10916        let fresh = losses_this_attempt(&old, &after);
10917        assert_eq!(fresh, vec![after[1].clone()]);
10918        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
10919        assert_eq!(
10920            until,
10921            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
10922        );
10923    }
10924
10925    #[test]
10926    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
10927        // `recover_stall` removes judge-1's loss and the retry then hits quota
10928        // again: the vector is the same length, so an index diff sees nothing.
10929        let before = vec![
10930            loss("judge-1", "2026-09-23T05:23:00Z", None),
10931            loss("judge-2", "2026-09-23T05:24:00Z", None),
10932        ];
10933        let after = vec![
10934            loss("judge-2", "2026-09-23T05:24:00Z", None),
10935            loss("judge-1", "2026-09-24T01:00:00Z", None),
10936        ];
10937        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
10938    }
10939
10940    #[test]
10941    fn merge_overrides_are_parsed_or_refused() {
10942        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
10943        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
10944        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
10945        assert!(merge_mode("squash").is_err());
10946    }
10947
10948    #[test]
10949    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
10950        let now = Timestamp::now();
10951        let fallback = Duration::from_secs(300);
10952        let cap = Duration::from_secs(1800);
10953
10954        // No reset hint at all: the fallback.
10955        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
10956
10957        // A reset ten minutes out, well inside the cap: waited for exactly.
10958        let soon = now + jiff::SignedDuration::from_secs(600);
10959        assert_eq!(
10960            quota_wait(Some(soon), now, fallback, cap),
10961            Duration::from_secs(600)
10962        );
10963
10964        // A reset already in the past is not trusted: the fallback, not a
10965        // zero or negative wait that would spin the loop right back around.
10966        let past = now - jiff::SignedDuration::from_secs(60);
10967        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
10968
10969        // A reset further out than the cap is trusted for direction but not
10970        // for magnitude: a parsing slip must not sleep the loop for a day.
10971        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
10972        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
10973    }
10974
10975    #[test]
10976    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
10977        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
10978
10979        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
10980        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
10981
10982        // Same clock reading, but it has already gone by today: read as
10983        // tomorrow's, since the CLI would not still be reporting a limit past
10984        // its own stated reset.
10985        let already_past =
10986            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
10987        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
10988
10989        assert!(
10990            parse_reset_hint("session limit reached", now, now).is_none(),
10991            "free text with no recognised shape is not guessed at"
10992        );
10993        assert!(
10994            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
10995            "an unresolvable zone name is not guessed at either"
10996        );
10997    }
10998
10999    #[test]
11000    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11001        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11002
11003        let at = parse_reset_hint(
11004            "You've hit your usage limit. Visit \
11005             https://chatgpt.com/codex/settings/usage to purchase more \
11006             credits or try again at Sep 19th, 2026 5:10 PM.",
11007            now,
11008            now,
11009        )
11010        .expect("the codex reset wording is a recognised shape");
11011        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11012
11013        // The month is explicit, so a date already earlier in the same
11014        // sentence-implied year than `now` is trusted as written rather than
11015        // rolled forward a year the way the bracketed shape rolls a
11016        // same-day clock reading to tomorrow.
11017        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11018            .expect("an explicit year needs no rollover");
11019        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11020
11021        assert!(
11022            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11023            "a two-digit year is not the documented shape and is not guessed at"
11024        );
11025        assert!(
11026            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11027            "a four-letter month name is not the documented three-letter abbreviation"
11028        );
11029        assert!(
11030            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11031            "an explicit zone on the dated shape is a format nobody has \
11032             documented, and is refused rather than guessed at as UTC"
11033        );
11034    }
11035
11036    #[test]
11037    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11038        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11039        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11040
11041        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11042        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11043
11044        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11045        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11046
11047        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11048            assert!(
11049                parse_reset_hint(bad, now, recorded).is_none(),
11050                "{bad:?} must not be guessed at"
11051            );
11052        }
11053    }
11054
11055    /// A loop whose queue lives in a temp tree and whose poll interval is far
11056    /// longer than the test's patience, so anything that waits out a poll
11057    /// instead of noticing the stop fails rather than merely being slow.
11058    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11059        let config = dir.join("magi.toml");
11060        std::fs::write(
11061            &config,
11062            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11063        )
11064        .unwrap();
11065        let opts = Opts {
11066            poll: Duration::from_secs(30),
11067            config: Some(config),
11068            // The explicit fixture config keeps startup cleanup from reading
11069            // machine configuration. This fictional repository likewise
11070            // keeps any best-effort git cleanup away from this checkout.
11071            repo: dir.join("repo"),
11072            ..Opts::default()
11073        };
11074        // The status file goes in a directory that does not exist yet, so its
11075        // creation is itself evidence the loop published one. `worktrees`
11076        // must be just as fictional: the janitor reclaims worktrees under it
11077        // for real, and a test that let it fall through to
11078        // `crate::run::default_worktree_root()` would have it reclaim
11079        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11080        // which is exactly what happened before this function took the
11081        // parameter at all.
11082        let home = dir.join("home");
11083        // These control-only fixtures do not launch native workers. Give the
11084        // independently tested maintenance services a fresh cadence receipt.
11085        let stamps = home.join("service-ticks");
11086        std::fs::create_dir_all(&stamps).unwrap();
11087        for service in ["waiter", "deputies", "release-watch"] {
11088            std::fs::write(
11089                stamps.join(service),
11090                Timestamp::now().as_second().to_string(),
11091            )
11092            .unwrap();
11093        }
11094        for operation in [
11095            "conductor",
11096            "maintenance",
11097            "housekeeping",
11098            "disk-pressure",
11099            "cache",
11100            "fetch",
11101            "chat-goals",
11102        ] {
11103            std::fs::write(
11104                stamps.join(format!("daemon-{operation}")),
11105                serde_json::to_vec(&Timestamp::now()).unwrap(),
11106            )
11107            .unwrap();
11108        }
11109        let worktrees = dir.join("wt");
11110        (
11111            opts,
11112            Queue::at(dir.join("queue")),
11113            home.join("daemon.json"),
11114            home,
11115            worktrees,
11116        )
11117    }
11118
11119    #[tokio::test]
11120    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11121        let dir = tempfile::tempdir().unwrap();
11122        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11123        let mut waiting = task();
11124        waiting.repo = opts.repo.clone();
11125        waiting.hold_machine(crate::disk::gate(1, 100));
11126        waiting.mark_disk_capacity();
11127        waiting.attempts = 2;
11128        queue.put(&mut waiting).unwrap();
11129        let mut busy = task();
11130        busy.status = TaskStatus::Running;
11131        queue.put(&mut busy).unwrap();
11132        let payload = serde_json::to_value(ServiceWorker {
11133            opts,
11134            queue: queue.root().to_owned(),
11135            worktrees_root: worktrees,
11136            operation: "maintenance".into(),
11137        })
11138        .unwrap();
11139        run_service_worker(&home, payload.clone()).await.unwrap();
11140        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11141        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11142        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11143        run_service_worker(&home, payload).await.unwrap();
11144        assert!(
11145            crate::worker::active(&home).unwrap().is_empty(),
11146            "monitoring only queues; normal dispatch owns launches"
11147        );
11148        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11149    }
11150
11151    #[tokio::test]
11152    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11153        let dir = tempfile::tempdir().unwrap();
11154        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11155        let cfg = Config::default();
11156        start_service(
11157            &home,
11158            &opts,
11159            &queue,
11160            &worktrees,
11161            "housekeeping",
11162            Some(&cfg),
11163            true,
11164        )
11165        .await
11166        .unwrap();
11167        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11168        let read = |path: &Path| -> serde_json::Value {
11169            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11170        };
11171        assert_eq!(read(&receipt)["detail"], "cadence not due");
11172        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11173        start_service(
11174            &home,
11175            &opts,
11176            &queue,
11177            &worktrees,
11178            "housekeeping",
11179            Some(&cfg),
11180            true,
11181        )
11182        .await
11183        .unwrap();
11184        assert_eq!(
11185            read(&receipt)["detail"],
11186            "active work or runnable task queue"
11187        );
11188        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11189        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11190        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11191        start_service(
11192            &home,
11193            &opts,
11194            &queue,
11195            &worktrees,
11196            "disk-pressure",
11197            Some(&cfg),
11198            false,
11199        )
11200        .await
11201        .unwrap();
11202        assert_eq!(
11203            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11204            "no active work; idle housekeeping owns scan"
11205        );
11206        assert!(crate::worker::active(&home).unwrap().is_empty());
11207    }
11208
11209    #[tokio::test]
11210    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11211        let dir = tempfile::tempdir().unwrap();
11212        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11213        let queue = Queue::at(home.join("queue"));
11214        let mut task = task();
11215        task.repo = opts.repo.clone();
11216        task.chat = Some("decision-chat".into());
11217        task.hold_machine(Some("waiting for a decision".into()));
11218        queue.put(&mut task).unwrap();
11219        let questions = Questions::at(home.join("questions"));
11220        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11221        question.node = crate::conduct::NODE.into();
11222        question.status = ask::QuestionStatus::Open;
11223        question.answer = None;
11224        question.answered_at = None;
11225        questions.put(&mut question).unwrap();
11226        questions
11227            .update(&question.id, |q| {
11228                q.answer(ask::Answer::Choice("resume で続行する".into()))
11229            })
11230            .unwrap();
11231
11232        let talks = crate::talk::Talks::at(home.join("talks"));
11233        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11234        decision_chat.pending = "Keep this unsent status question".into();
11235        talks.put(&mut decision_chat).unwrap();
11236        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11237        talk.goals.push(serde_json::from_value(serde_json::json!({
11238            "id":"goal","purpose":"follow the retained job","scope":"one task",
11239            "condition":{"description":"land the result","kind":"runs_merged"},
11240            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11241            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11242            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11243        })).unwrap());
11244        talks.put(&mut talk).unwrap();
11245
11246        // A retained service lease models an observation still waiting on its
11247        // external dependency. Admission must neither await nor repeat it.
11248        let directory = home.join("workers/jobs/abcdef");
11249        std::fs::create_dir_all(&directory).unwrap();
11250        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11251        crate::pr_head::try_lock_file(&lease).unwrap();
11252        let mut job = crate::worker::Job {
11253            id: "abcdef".into(),
11254            sequence: 1,
11255            kind: "daemon-service".into(),
11256            key: "service:daemon-chat-goals".into(),
11257            payload: serde_json::Value::Null,
11258            generation: "fixture".into(),
11259            version: None,
11260            status: crate::worker::Status::Running,
11261            result: None,
11262            pid: Some(std::process::id()),
11263            created_at: Timestamp::now().as_second() as u64,
11264            finished_at: None,
11265        };
11266        let record = directory.join("job.json");
11267        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11268        let status = Arc::new(Mutex::new(Status::new()));
11269        let stop = Stop::new();
11270        let mut dispatch = Box::pin(poll(
11271            &opts,
11272            &queue,
11273            &status,
11274            &home,
11275            &worktrees,
11276            &stop,
11277            DispatchLimits {
11278                max_concurrent: 1,
11279                pause_for_interrupts: false,
11280                recovery_cfg: None,
11281            },
11282        ));
11283        std::future::poll_fn(|cx| {
11284            assert!(dispatch.as_mut().poll(cx).is_pending());
11285            std::task::Poll::Ready(())
11286        })
11287        .await;
11288        assert!(lock(&status).polls > 0);
11289        let saved = queue.get(&task.id).unwrap();
11290        assert_eq!(saved.status, TaskStatus::Done);
11291        assert!(saved.action_applied(&question.id));
11292        assert!(
11293            talks
11294                .get("decision-chat")
11295                .unwrap()
11296                .pending
11297                .contains("Keep this unsent status question")
11298        );
11299        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11300        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11301        assert_eq!(
11302            goal.started,
11303            Some(1),
11304            "only the observation worker may reconcile its goal"
11305        );
11306        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11307
11308        stop.stop();
11309        dispatch.await.unwrap();
11310        job.status = crate::worker::Status::Finished;
11311        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11312        drop(lease);
11313    }
11314
11315    #[test]
11316    fn a_stop_is_idempotent_and_once_set_stays_set() {
11317        let stop = Stop::new();
11318        assert!(!stop.stopped());
11319
11320        stop.stop();
11321        assert!(stop.stopped());
11322        stop.stop();
11323        assert!(stop.stopped(), "a second stop is not a toggle");
11324
11325        let shared = stop.clone();
11326        assert!(
11327            shared.stopped(),
11328            "a clone is the same stop; that is how the loop and its caller share one"
11329        );
11330    }
11331
11332    #[tokio::test]
11333    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11334        for operation in ["conductor", "maintenance", "housekeeping"] {
11335            let dir = tempfile::tempdir().unwrap();
11336            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11337            opts.once = true;
11338            opts.poll = Duration::from_millis(1);
11339            let mut task = task();
11340            task.runs.push("fixture-run".into());
11341            queue.put(&mut task).unwrap();
11342            let claim = queue.claim(&task.id).unwrap();
11343
11344            // Model a live service holding the task's claim across the
11345            // scheduler's dispatch scan. No real subprocess or timed race.
11346            let directory = home.join("workers/jobs/abcdef");
11347            std::fs::create_dir_all(&directory).unwrap();
11348            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11349            crate::pr_head::try_lock_file(&lease).unwrap();
11350            let mut job = crate::worker::Job {
11351                id: "abcdef".into(),
11352                sequence: 1,
11353                kind: "daemon-service".into(),
11354                key: format!("service:daemon-{operation}"),
11355                payload: serde_json::Value::Null,
11356                generation: "fixture".into(),
11357                version: None,
11358                status: crate::worker::Status::Running,
11359                result: None,
11360                pid: Some(std::process::id()),
11361                created_at: Timestamp::now().as_second() as u64,
11362                finished_at: None,
11363            };
11364            let record = directory.join("job.json");
11365            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11366
11367            let status = Arc::new(Mutex::new(Status::new()));
11368            let stop = Stop::new();
11369            let mut drain = Box::pin(poll(
11370                &opts,
11371                &queue,
11372                &status,
11373                &home,
11374                &worktrees,
11375                &stop,
11376                DispatchLimits {
11377                    max_concurrent: 1,
11378                    pause_for_interrupts: false,
11379                    recovery_cfg: None,
11380                },
11381            ));
11382            std::future::poll_fn(|cx| {
11383                use std::future::Future;
11384                assert!(
11385                    drain.as_mut().poll(cx).is_pending(),
11386                    "--once must wait for {operation} to release its queue claim"
11387                );
11388                std::task::Poll::Ready(())
11389            })
11390            .await;
11391            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
11392
11393            // An answer arrives while the service still owns the claim. A
11394            // fresh scheduling pass must apply it before declaring idle.
11395            let questions = Questions::at(home.join("questions"));
11396            let mut q = action_question("fixture-run", ask::ChoiceAction::Done);
11397            questions.put(&mut q).unwrap();
11398            drop(claim);
11399            // Model services that took longer than their cadence, without a
11400            // wall-clock sleep. The final scans must not respawn them even
11401            // though their receipts now permit another periodic invocation.
11402            let expired =
11403                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
11404            for service in [operation, "housekeeping"] {
11405                std::fs::write(
11406                    home.join("service-ticks").join(format!("daemon-{service}")),
11407                    &expired,
11408                )
11409                .unwrap();
11410            }
11411            job.status = crate::worker::Status::Finished;
11412            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11413            drop(lease);
11414            tokio::time::timeout(Duration::from_secs(2), drain)
11415                .await
11416                .expect("the settled service must allow the drain to finish")
11417                .unwrap();
11418            let after = queue.get(&task.id).unwrap();
11419            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
11420            assert!(after.action_applied(&q.id));
11421            for service in [operation, "housekeeping"] {
11422                assert_eq!(
11423                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
11424                        .unwrap(),
11425                    expired,
11426                    "the final once rescan must not restart {service}"
11427                );
11428            }
11429        }
11430    }
11431
11432    #[test]
11433    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
11434        let stop = Stop::new();
11435        stop.busy.store(1, Ordering::SeqCst);
11436        assert!(
11437            !stop.finishing(),
11438            "a busy loop nobody has asked to stop is just running"
11439        );
11440
11441        stop.stop();
11442        assert!(
11443            stop.finishing(),
11444            "a stop asked for mid-run has not landed until the run is settled"
11445        );
11446
11447        stop.busy.store(0, Ordering::SeqCst);
11448        assert!(
11449            !stop.finishing(),
11450            "once the run is settled the stop has landed and there is nothing to finish"
11451        );
11452    }
11453
11454    #[test]
11455    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
11456        let stop = Stop::new();
11457        stop.busy.store(2, Ordering::SeqCst);
11458        stop.stop();
11459        assert!(stop.finishing(), "two runs still in flight");
11460
11461        stop.busy.store(1, Ordering::SeqCst);
11462        assert!(
11463            stop.finishing(),
11464            "one run finished, but a sibling is still working"
11465        );
11466
11467        stop.busy.store(0, Ordering::SeqCst);
11468        assert!(
11469            !stop.finishing(),
11470            "the last run out is what actually lands the stop"
11471        );
11472    }
11473
11474    #[tokio::test]
11475    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
11476        let dir = tempfile::tempdir().unwrap();
11477        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11478        let stop = Stop::new();
11479        stop.stop();
11480
11481        let began = std::time::Instant::now();
11482        tokio::time::timeout(
11483            Duration::from_secs(2),
11484            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11485        )
11486        .await
11487        .expect("a stopped loop must return, not sit out its poll interval")
11488        .expect("the loop's own setup and teardown must not fail");
11489        assert!(
11490            began.elapsed() < opts.poll,
11491            "returned only after {:?}, which is a poll interval, not a stop",
11492            began.elapsed()
11493        );
11494    }
11495
11496    #[tokio::test]
11497    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
11498        let dir = tempfile::tempdir().unwrap();
11499        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11500        let stop = Stop::new();
11501
11502        // Asked for after the loop is already parked on its empty queue, which
11503        // is the case an operator tapping stop on a phone actually hits.
11504        let asker = {
11505            let stop = stop.clone();
11506            tokio::spawn(async move {
11507                tokio::time::sleep(Duration::from_millis(20)).await;
11508                stop.stop();
11509            })
11510        };
11511
11512        let began = std::time::Instant::now();
11513        tokio::time::timeout(
11514            Duration::from_secs(2),
11515            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11516        )
11517        .await
11518        .expect("a stop asked for while idle must wake the wait")
11519        .expect("the loop's own setup and teardown must not fail");
11520        asker.await.unwrap();
11521        assert!(
11522            began.elapsed() < opts.poll,
11523            "returned only after {:?}, so the stop waited on the sleep",
11524            began.elapsed()
11525        );
11526    }
11527
11528    #[tokio::test]
11529    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
11530        let dir = tempfile::tempdir().unwrap();
11531        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
11532        let stop = Stop::new();
11533        stop.stop();
11534
11535        tokio::time::timeout(
11536            Duration::from_secs(2),
11537            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
11538        )
11539        .await
11540        .expect("a stopped loop must return")
11541        .expect("the loop's own setup and teardown must not fail");
11542
11543        assert!(
11544            home.is_dir(),
11545            "the loop did publish a status file, so its removal is the teardown and not an absence"
11546        );
11547        assert!(
11548            !status_file.exists(),
11549            "a stopped loop clears its status file"
11550        );
11551        assert!(
11552            read_status(&home).is_none(),
11553            "a reader must see no daemon at all, not a heartbeat that merely stopped"
11554        );
11555    }
11556
11557    #[tokio::test]
11558    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
11559        let dir = tempfile::tempdir().unwrap();
11560        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11561
11562        let mut settled = RunState::new(
11563            dir.path().join("repo"),
11564            "main".to_owned(),
11565            "abc1234".to_owned(),
11566            "fixture".to_owned(),
11567            Config::default(),
11568        );
11569        settled.status = RunStatus::Ready;
11570        let run_dir = home.join("runs").join(&settled.id);
11571        std::fs::create_dir_all(&run_dir).unwrap();
11572        std::fs::write(
11573            run_dir.join("run.json"),
11574            serde_json::to_string_pretty(&settled).unwrap(),
11575        )
11576        .unwrap();
11577        let questions = Questions::at(home.join("questions"));
11578        let mut question = ask::Question::new(
11579            settled.id.clone(),
11580            "review".to_owned(),
11581            "reviewer-1".to_owned(),
11582            "Continue?".to_owned(),
11583            String::new(),
11584            Vec::new(),
11585        );
11586        questions.put(&mut question).unwrap();
11587
11588        run_service_worker(
11589            &home,
11590            serde_json::to_value(ServiceWorker {
11591                opts,
11592                queue: queue.root().to_path_buf(),
11593                worktrees_root: worktrees,
11594                operation: "housekeeping".to_owned(),
11595            })
11596            .unwrap(),
11597        )
11598        .await
11599        .unwrap();
11600
11601        assert_eq!(
11602            questions.get(&question.id).unwrap().status,
11603            ask::QuestionStatus::Abandoned,
11604            "the independent housekeeping worker settles ended-run questions"
11605        );
11606    }
11607
11608    #[test]
11609    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
11610        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11611
11612        assert!(
11613            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
11614            "never checked before: due at once"
11615        );
11616
11617        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
11618        assert!(
11619            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
11620            "well inside the interval: not due yet"
11621        );
11622
11623        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
11624        assert!(
11625            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
11626            "exactly at the edge: not yet due, same convention as `clean::due`"
11627        );
11628
11629        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11630        assert!(
11631            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
11632            "past the interval: due again"
11633        );
11634    }
11635
11636    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
11637    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
11638    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
11639    /// and the congestion test below both need, and must not drift apart.
11640    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
11641        let config = dir.join("magi.toml");
11642        // A literal (single-quoted) TOML string, not a basic one: the cache
11643        // path is a Windows path full of backslashes, and a basic string
11644        // would have TOML try to interpret `\U` (from `\Users\...`) as a
11645        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
11646        // `{{ vars.cache }}` rendering documents.
11647        std::fs::write(
11648            &config,
11649            format!(
11650                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
11651                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
11652                cache_dir.display()
11653            ),
11654        )
11655        .unwrap();
11656        Opts {
11657            config: Some(config),
11658            repo: dir.join("repo"),
11659            ..Opts::default()
11660        }
11661    }
11662
11663    #[tokio::test]
11664    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
11665        let dir = tempfile::tempdir().unwrap();
11666        let home = dir.path().join("home");
11667        let cache_dir = dir.path().join("cache");
11668        std::fs::create_dir_all(&cache_dir).unwrap();
11669        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11670        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11671
11672        // Nobody has asked this daemon to stop, which is the ordinary case;
11673        // the skip that a stop buys is asserted by its own test below.
11674        let running = Stop::new();
11675        let mut last_checked = None;
11676        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11677        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
11678            .await;
11679        assert_eq!(
11680            crate::disk::dir_size(&cache_dir),
11681            0,
11682            "over the cap on the first check ever: pruned at once, no idle queue required"
11683        );
11684        assert_eq!(last_checked, Some(t0));
11685
11686        // A fresh oversized file lands, but the next check is not due yet.
11687        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
11688        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
11689        maybe_prune_cache_between_runs(
11690            &opts.repo,
11691            &opts,
11692            &home,
11693            &running,
11694            &mut last_checked,
11695            too_soon,
11696        )
11697        .await;
11698        assert_eq!(
11699            crate::disk::dir_size(&cache_dir),
11700            10,
11701            "too soon since the last check: left alone rather than rescanned every call"
11702        );
11703        assert_eq!(
11704            last_checked,
11705            Some(t0),
11706            "an idle check does not reset the clock"
11707        );
11708
11709        // Once the interval elapses, the same oversized cache is caught again.
11710        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
11711        maybe_prune_cache_between_runs(
11712            &opts.repo,
11713            &opts,
11714            &home,
11715            &running,
11716            &mut last_checked,
11717            due_again,
11718        )
11719        .await;
11720        assert_eq!(
11721            crate::disk::dir_size(&cache_dir),
11722            0,
11723            "due again: pruned back under the cap"
11724        );
11725    }
11726
11727    /// A stop must not queue behind housekeeping. The prune below is a
11728    /// synchronous walk of the whole cache with no await point in it, so a
11729    /// loop that entered it could not get back to its own `stopped()` test
11730    /// until the walk finished - and because no run is in flight at this
11731    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
11732    /// the stop had already landed. The idle branch has always made this same
11733    /// check before reaching `janitor`; the between-runs path makes it too.
11734    #[tokio::test]
11735    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
11736        let dir = tempfile::tempdir().unwrap();
11737        let home = dir.path().join("home");
11738        let cache_dir = dir.path().join("cache");
11739        std::fs::create_dir_all(&cache_dir).unwrap();
11740        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
11741        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
11742
11743        let stop = Stop::new();
11744        stop.stop();
11745        assert!(
11746            !stop.finishing(),
11747            "no run is in flight at a between-runs boundary, so nothing else \
11748             would tell the operator this stop had not taken effect yet"
11749        );
11750
11751        let mut last_checked = None;
11752        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
11753        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
11754            .await;
11755        assert_eq!(
11756            crate::disk::dir_size(&cache_dir),
11757            10,
11758            "over its cap, and due for the first check ever, but a stop outranks \
11759             it: the cap is a standing policy the next start measures again"
11760        );
11761        assert_eq!(
11762            last_checked, None,
11763            "a check that never happened must not claim the interval"
11764        );
11765    }
11766
11767    /// A backlog must not starve cache pruning. The finite cache worker runs
11768    /// independently of queue drain and must not consume any task attempts.
11769    #[tokio::test]
11770    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
11771        let dir = tempfile::tempdir().unwrap();
11772        let cache_dir = dir.path().join("cache");
11773        std::fs::create_dir_all(&cache_dir).unwrap();
11774        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
11775
11776        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
11777        opts.poll = Duration::from_millis(20);
11778        opts.max_attempts = 1_000;
11779
11780        let queue = Queue::at(dir.path().join("queue"));
11781        for i in 0..128 {
11782            let mut task = Task::new(
11783                format!("queued work {i}"),
11784                format!("queued work {i}"),
11785                opts.repo.clone(),
11786                Source::Human,
11787            );
11788            queue.put(&mut task).unwrap();
11789        }
11790
11791        let home = dir.path().join("home");
11792        let worktrees = dir.path().join("wt");
11793        run_service_worker(
11794            &home,
11795            serde_json::to_value(ServiceWorker {
11796                opts,
11797                queue: queue.root().to_path_buf(),
11798                worktrees_root: worktrees,
11799                operation: "cache".to_owned(),
11800            })
11801            .unwrap(),
11802        )
11803        .await
11804        .unwrap();
11805        let after = queue.list();
11806        assert_eq!(after.len(), 128);
11807        assert!(
11808            after
11809                .iter()
11810                .all(|task| task.status.runnable() && task.attempts == 0)
11811        );
11812
11813        assert_eq!(
11814            crate::disk::dir_size(&cache_dir),
11815            0,
11816            "an oversized cache must not be left to grow unboundedly just because the \
11817             queue kept the loop busy the whole time"
11818        );
11819    }
11820
11821    #[test]
11822    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
11823        let dir = tempfile::tempdir().unwrap();
11824        let queue = Queue::at(dir.path().join("queue"));
11825        let questions = Questions::at(dir.path().join("questions"));
11826        let mut task = task();
11827        queue.put(&mut task).unwrap();
11828
11829        let mut task_question = ask::Question::new(
11830            task.id.clone(),
11831            crate::conduct::NODE.to_owned(),
11832            "conduct".to_owned(),
11833            "Which backend?".to_owned(),
11834            String::new(),
11835            Vec::new(),
11836        );
11837        questions.put(&mut task_question).unwrap();
11838        task.block(vec![task_question.id.clone()], None);
11839        queue.put(&mut task).unwrap();
11840
11841        let mut run_question = ask::Question::new(
11842            "20260101-000000-run1".to_owned(),
11843            "review".to_owned(),
11844            "reviewer-1".to_owned(),
11845            "Run question".to_owned(),
11846            String::new(),
11847            Vec::new(),
11848        );
11849        questions.put(&mut run_question).unwrap();
11850
11851        // A question from another node whose `run` happens to equal this
11852        // task's id — the same field, filled in for an unrelated reason. Only
11853        // `crate::conduct::NODE` questions use `run` as a task id; this one
11854        // must never be touched by this reconciliation, even after release.
11855        let mut coincidental = ask::Question::new(
11856            task.id.clone(),
11857            "review".to_owned(),
11858            "reviewer-1".to_owned(),
11859            "Unrelated review question".to_owned(),
11860            String::new(),
11861            Vec::new(),
11862        );
11863        questions.put(&mut coincidental).unwrap();
11864
11865        reconcile_task_questions(&queue, &questions);
11866        assert!(questions.get(&task_question.id).unwrap().status.open());
11867        assert!(questions.get(&run_question.id).unwrap().status.open());
11868        assert!(questions.get(&coincidental.id).unwrap().status.open());
11869
11870        task.release();
11871        queue.put(&mut task).unwrap();
11872        reconcile_task_questions(&queue, &questions);
11873        assert_eq!(
11874            questions.get(&task_question.id).unwrap().status,
11875            ask::QuestionStatus::Abandoned
11876        );
11877        assert!(
11878            questions.get(&run_question.id).unwrap().status.open(),
11879            "run questions remain the run janitor's responsibility"
11880        );
11881        assert!(
11882            questions.get(&coincidental.id).unwrap().status.open(),
11883            "a non-conductor question must not be abandoned just because its \
11884             run id coincides with a task id"
11885        );
11886    }
11887
11888    #[test]
11889    fn a_freshly_started_running_task_is_never_stalled() {
11890        let dir = tempfile::tempdir().unwrap();
11891        let mut t = task();
11892        t.start("run-1".to_owned());
11893        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
11894        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
11895        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
11896    }
11897
11898    #[test]
11899    fn a_long_running_task_with_no_live_daemon_is_stalled() {
11900        let dir = tempfile::tempdir().unwrap();
11901        let mut t = task();
11902        t.start("run-1".to_owned());
11903        t.updated_at = Timestamp::now()
11904            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11905        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
11906        assert_eq!(
11907            stalled_tasks(
11908                &Queue::at(dir.path().join("q")),
11909                dir.path(),
11910                Timestamp::now()
11911            )
11912            .len(),
11913            0,
11914            "the task was never written to this queue"
11915        );
11916    }
11917
11918    #[test]
11919    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
11920        let dir = tempfile::tempdir().unwrap();
11921        let mut t = task();
11922        t.id = "20260903-080340-0167".to_owned();
11923        t.start("20260903-080619-01c2".to_owned());
11924        t.updated_at = Timestamp::now()
11925            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
11926
11927        let mut status = Status::new();
11928        status.current = vec![Current {
11929            worker: None,
11930            task: t.id.clone(),
11931            run: "20260903-080619-01c2".to_owned(),
11932        }];
11933        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11934
11935        assert!(
11936            !is_stalled(&t, dir.path(), Timestamp::now()),
11937            "a live daemon's own heartbeat rules out stalled, however long the task has run"
11938        );
11939    }
11940
11941    /// Rewrite a task's `updated_at` on disk directly, bypassing
11942    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
11943    /// a fixture look like it has genuinely been `running` for a while.
11944    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
11945        let path = queue.path_of(id);
11946        let body = std::fs::read_to_string(&path).unwrap();
11947        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
11948        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
11949        v["updated_at"] = serde_json::Value::String(old.to_string());
11950        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
11951    }
11952
11953    #[test]
11954    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
11955        // The realistic `poll()` ordering, not `is_stalled` in isolation:
11956        // `reclaim_orphaned_running` runs first, on every poll, and settles
11957        // any `running` task whose claim it can actually take. For most
11958        // crashes that is immediate - a dead pid is proof enough for
11959        // `sweep_stale_claims` to drop the lock the same tick, and the very
11960        // next claim attempt succeeds. But a lock whose pid cannot be parsed
11961        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
11962        // `sweep_stale_claims`'s own doc), so the lock - and the claim
11963        // failure behind it - can legitimately outlive many polls. This is
11964        // exactly the gap `stalled_tasks` exists to surface well before that
11965        // six-hour sweep would: reclaim leaves the task `running`, and it
11966        // must still reach the conductor as stalled.
11967        let dir = tempfile::tempdir().unwrap();
11968        let queue = Queue::at(dir.path().join("queue"));
11969        let home = dir.path().join("home");
11970
11971        let mut t = task();
11972        t.id = "20260101-000001-lock".to_owned();
11973        t.start("run-1".to_owned());
11974        queue.put(&mut t).unwrap();
11975        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
11976        std::fs::write(
11977            dir.path().join("queue").join(format!("{}.lock", t.id)),
11978            "not a pid",
11979        )
11980        .unwrap();
11981
11982        let now = Timestamp::now();
11983        assert!(
11984            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
11985            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
11986             and reclaim must leave the task alone"
11987        );
11988        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
11989
11990        let stalled = stalled_tasks(&queue, &home, now);
11991        assert_eq!(
11992            stalled.len(),
11993            1,
11994            "reclaim's inability to claim it yet must not hide it from the conductor"
11995        );
11996        assert_eq!(stalled[0].id, t.id);
11997    }
11998
11999    #[test]
12000    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12001        let dir = tempfile::tempdir().unwrap();
12002        crate::run::set_home(dir.path().join("run-home"));
12003        let queue = Queue::at(dir.path().join("queue"));
12004        let home = dir.path().join("home");
12005        let questions = Questions::at(dir.path().join("questions"));
12006
12007        let mut t = task();
12008        t.id = "20260101-000003-dead".to_owned();
12009        t.start("missing-run".to_owned());
12010        queue.put(&mut t).unwrap();
12011        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12012
12013        // This is the real poll ordering: retain the deterministic stalled
12014        // input before a claim proves the owner is gone and reclaims it.
12015        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12016        assert_eq!(
12017            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12018            [&t.id]
12019        );
12020        assert_eq!(
12021            reclaim_orphaned_running(&queue, 2, &Default::default()),
12022            [t.id.clone()]
12023        );
12024        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12025
12026        // Reclaim drops its guard before conductor decisions are applied, so
12027        // the decision for the captured stalled input has a real write path.
12028        crate::conduct::apply(
12029            &queue,
12030            &questions,
12031            &crate::conduct::Verdict {
12032                decisions: vec![crate::conduct::Decision {
12033                    id: t.id.clone(),
12034                    recovery: Some(crate::conduct::Recovery::Requeue),
12035                    ..crate::conduct::Decision::default()
12036                }],
12037            },
12038        )
12039        .unwrap();
12040        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12041    }
12042
12043    #[test]
12044    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12045        let dir = tempfile::tempdir().unwrap();
12046        let queue = Queue::at(dir.path().join("queue"));
12047        let home = dir.path().join("home");
12048
12049        let mut fresh = task();
12050        fresh.id = "20260101-000001-aaaa".to_owned();
12051        fresh.start("run-1".to_owned());
12052        queue.put(&mut fresh).unwrap();
12053
12054        let mut old = task();
12055        old.id = "20260101-000002-bbbb".to_owned();
12056        old.start("run-2".to_owned());
12057        queue.put(&mut old).unwrap();
12058        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12059
12060        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12061        assert_eq!(stalled.len(), 1);
12062        assert_eq!(stalled[0].id, old.id);
12063    }
12064
12065    #[test]
12066    fn queued_and_finished_task_views_partition_by_status() {
12067        let dir = tempfile::tempdir().unwrap();
12068        let queue = Queue::at(dir.path().join("queue"));
12069
12070        let mut queued = task();
12071        queued.id = "20260101-000001-aaaa".to_owned();
12072        queue.put(&mut queued).unwrap();
12073
12074        let mut failed = task();
12075        failed.id = "20260101-000002-bbbb".to_owned();
12076        failed.start("run-1".to_owned());
12077        failed.fail("gate red", 5);
12078        queue.put(&mut failed).unwrap();
12079
12080        let mut held = task();
12081        held.id = "20260101-000003-cccc".to_owned();
12082        held.hold_machine(None);
12083        queue.put(&mut held).unwrap();
12084
12085        let mut running = task();
12086        running.id = "20260101-000004-dddd".to_owned();
12087        running.start("run-2".to_owned());
12088        queue.put(&mut running).unwrap();
12089
12090        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12091        assert_eq!(queued_ids, [queued.id.clone()]);
12092
12093        let mut finished_ids: Vec<String> =
12094            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12095        finished_ids.sort_unstable();
12096        let mut want = vec![failed.id.clone(), held.id.clone()];
12097        want.sort_unstable();
12098        assert_eq!(finished_ids, want);
12099    }
12100
12101    #[test]
12102    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12103        for short in [false, true] {
12104            let dir = tempfile::tempdir().unwrap();
12105            let queue = Queue::at(dir.path().join("queue"));
12106            let questions = ask::Questions::at(dir.path().join("questions"));
12107            let mut running = task();
12108            running.id = "20261013-192213-feb2".into();
12109            running.start("existing-run".into());
12110            queue.put(&mut running).unwrap();
12111            let mut middle = task();
12112            middle.id = "20261013-193611-ca5b".into();
12113            middle.block(
12114                vec![if short {
12115                    "feb2".into()
12116                } else {
12117                    running.id.clone()
12118                }],
12119                None,
12120            );
12121            queue.put(&mut middle).unwrap();
12122            let mut waiting = task();
12123            waiting.id = "20261013-202849-ee37".into();
12124            waiting.block(
12125                vec![if short {
12126                    "ca5b".into()
12127                } else {
12128                    middle.id.clone()
12129                }],
12130                Some("wait for implementation".into()),
12131            );
12132            queue.put(&mut waiting).unwrap();
12133            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12134            let inv = crate::blockers::Inventory::load(&queue, &questions);
12135            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12136            assert!(inv.stuck().is_empty());
12137            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12138            assert!(report.quarantined.is_empty());
12139            assert!(report.asked.is_empty());
12140            resolve_blockers(&queue, &questions);
12141            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12142            assert!(questions.list().is_empty());
12143            // Finishing the transitive prerequisite alone does not satisfy
12144            // the task's direct dependency.
12145            running.succeed();
12146            queue.put(&mut running).unwrap();
12147            resolve_blockers(&queue, &questions);
12148            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12149            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12150            middle = queue.get(&middle.id).unwrap();
12151            middle.succeed();
12152            queue.put(&mut middle).unwrap();
12153            resolve_blockers(&queue, &questions);
12154            let after = queue.get(&waiting.id).unwrap();
12155            assert_eq!(after.status, TaskStatus::Queued);
12156            assert!(after.blocked_by.is_empty());
12157            assert_eq!(after.instruction, waiting.instruction);
12158        }
12159    }
12160
12161    #[test]
12162    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12163        for future_schema in [false, true] {
12164            let name = "20261013-193611-ca5b";
12165            let mut future = task();
12166            future.id = name.into();
12167            future.schema = crate::queue::SCHEMA + 1;
12168            let contents = if future_schema {
12169                serde_json::to_string(&future).unwrap()
12170            } else {
12171                "corrupt".into()
12172            };
12173            let dir = tempfile::tempdir().unwrap();
12174            let queue = Queue::at(dir.path().join("queue"));
12175            let questions = ask::Questions::at(dir.path().join("questions"));
12176            let mut waiting = task();
12177            waiting.id = "20261013-202849-ee37".into();
12178            waiting.block(vec!["ca5b".into()], None);
12179            queue.put(&mut waiting).unwrap();
12180            std::fs::write(queue.path_of(name), contents).unwrap();
12181            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12182            assert!(
12183                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12184            );
12185            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12186            assert!(report.asked.is_empty());
12187            resolve_blockers(&queue, &questions);
12188            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12189            assert!(questions.list().is_empty());
12190        }
12191        let dir = tempfile::tempdir().unwrap();
12192        let queue = Queue::at(dir.path().join("queue"));
12193        let questions = ask::Questions::at(dir.path().join("questions"));
12194        let mut waiting = task();
12195        waiting.id = "20261013-202849-ee37".into();
12196        waiting.block(vec!["ca5b".into()], None);
12197        queue.put(&mut waiting).unwrap();
12198        let mut done = task();
12199        done.id = "20261013-193611-ca5b".into();
12200        done.succeed();
12201        queue.put(&mut done).unwrap();
12202        // An unreadable second match must not disappear from uniqueness
12203        // checks just because Queue::list skips it.
12204        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12205        assert!(queue.get("ca5b").is_err());
12206        assert_eq!(
12207            crate::queue::dependency(&queue, &questions, "ca5b"),
12208            crate::queue::Dependency::Ambiguous
12209        );
12210        resolve_blockers(&queue, &questions);
12211        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12212        assert!(report.asked.is_empty());
12213        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12214        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12215    }
12216
12217    #[test]
12218    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12219        for held in [false, true] {
12220            for question in [false, true] {
12221                for reference in ["ca5b", "20261013-193611-ca5b"] {
12222                    let dir = tempfile::tempdir().unwrap();
12223                    let queue = Queue::at(dir.path().join("queue"));
12224                    let questions = ask::Questions::at(dir.path().join("questions"));
12225                    let mut prerequisite = task();
12226                    prerequisite.id = "20261013-193611-ca5b".into();
12227                    prerequisite.start("existing-run".into());
12228                    queue.put(&mut prerequisite).unwrap();
12229                    let mut waiting = task();
12230                    waiting.id = "20261013-202849-ee37".into();
12231                    if held {
12232                        waiting.hold_machine(Some("waiting for separate consent".into()));
12233                    }
12234                    queue.put(&mut waiting).unwrap();
12235                    let reason = "Deleting saved data requires separate owner consent";
12236                    crate::conduct::apply(
12237                        &queue,
12238                        &questions,
12239                        &crate::conduct::Verdict {
12240                            decisions: vec![crate::conduct::Decision {
12241                                id: waiting.id.clone(),
12242                                blocked_by: vec![reference.into()],
12243                                question: question.then(|| "May the saved data be deleted?".into()),
12244                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12245                                reason: Some(reason.into()),
12246                                ..crate::conduct::Decision::default()
12247                            }],
12248                        },
12249                    )
12250                    .unwrap();
12251                    let before = queue.get(&waiting.id).unwrap();
12252                    if question {
12253                        assert_eq!(before.status, TaskStatus::Blocked);
12254                        let q = questions.get(&before.blocked_by[0]).unwrap();
12255                        assert_eq!(q.summary, "May the saved data be deleted?");
12256                        assert!(q.status.open());
12257                    } else {
12258                        assert_eq!(before.status, TaskStatus::Held);
12259                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12260                        assert!(recorded_reason.starts_with(reason));
12261                        if held {
12262                            assert!(recorded_reason.contains("waiting for separate consent"));
12263                        }
12264                    }
12265                    prerequisite.succeed();
12266                    queue.put(&mut prerequisite).unwrap();
12267                    resolve_blockers(&queue, &questions);
12268                    let after = queue.get(&waiting.id).unwrap();
12269                    assert_eq!(after.status, before.status);
12270                    assert_eq!(after.blocked_by, before.blocked_by);
12271                    assert_eq!(after.hold_reason, before.hold_reason);
12272                    assert_eq!(after.instruction, waiting.instruction);
12273                    if question {
12274                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12275                    }
12276                    assert!(
12277                        queue.next_runnable().is_none(),
12278                        "dependency completion is not consent"
12279                    );
12280                }
12281            }
12282        }
12283    }
12284
12285    #[test]
12286    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12287        let dir = tempfile::tempdir().unwrap();
12288        let queue = Queue::at(dir.path().join("queue"));
12289        let questions = ask::Questions::at(dir.path().join("questions"));
12290
12291        let mut dep = task();
12292        dep.id = "20260101-000001-dep0".to_owned();
12293        dep.succeed();
12294        queue.put(&mut dep).unwrap();
12295
12296        let mut still_going = task();
12297        still_going.id = "20260101-000002-dep1".to_owned();
12298        queue.put(&mut still_going).unwrap();
12299
12300        let mut blocked = task();
12301        blocked.id = "20260101-000003-main".to_owned();
12302        blocked.block(
12303            vec![dep.id.clone(), still_going.id.clone()],
12304            Some("waits on both".to_owned()),
12305        );
12306        queue.put(&mut blocked).unwrap();
12307
12308        resolve_blockers(&queue, &questions);
12309
12310        let after = queue.get(&blocked.id).unwrap();
12311        assert_eq!(
12312            after.status,
12313            TaskStatus::Blocked,
12314            "one dependency is still outstanding"
12315        );
12316        assert_eq!(after.blocked_by, [still_going.id.clone()]);
12317    }
12318
12319    #[test]
12320    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
12321        let dir = tempfile::tempdir().unwrap();
12322        let queue = Queue::at(dir.path().join("queue"));
12323        let questions = ask::Questions::at(dir.path().join("questions"));
12324
12325        let mut q = crate::ask::Question::new(
12326            "20260101-000001-main".to_owned(),
12327            crate::conduct::NODE.to_owned(),
12328            "conduct".to_owned(),
12329            "Which backend?".to_owned(),
12330            String::new(),
12331            Vec::new(),
12332        );
12333        questions.put(&mut q).unwrap();
12334        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
12335            .unwrap();
12336        questions.put(&mut q).unwrap();
12337
12338        let mut blocked = task();
12339        blocked.id = "20260101-000001-main".to_owned();
12340        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
12341        queue.put(&mut blocked).unwrap();
12342
12343        resolve_blockers(&queue, &questions);
12344
12345        let after = queue.get(&blocked.id).unwrap();
12346        assert_eq!(
12347            after.status,
12348            TaskStatus::Queued,
12349            "the only blocker resolved"
12350        );
12351        assert_eq!(after.answers.len(), 1);
12352        assert_eq!(after.answers[0].question, "Which backend?");
12353        assert_eq!(after.answers[0].answer, "SQLite");
12354
12355        // And the run this task starts next is told about it.
12356        let instruction = instruction_for(&after);
12357        assert!(instruction.contains("Which backend?"));
12358        assert!(instruction.contains("SQLite"));
12359    }
12360
12361    #[test]
12362    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
12363        let dir = tempfile::tempdir().unwrap();
12364        let queue = Queue::at(dir.path().join("queue"));
12365        let questions = ask::Questions::at(dir.path().join("questions"));
12366
12367        let mut q = crate::ask::Question::new(
12368            "20260101-000001-main".to_owned(),
12369            crate::conduct::NODE.to_owned(),
12370            "conduct".to_owned(),
12371            "Is the setup done?".to_owned(),
12372            String::new(),
12373            Vec::new(),
12374        );
12375        q.abandon("no answer within 60s of asking");
12376        questions.put(&mut q).unwrap();
12377
12378        let mut blocked = task();
12379        blocked.id = "20260101-000001-main".to_owned();
12380        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
12381        queue.put(&mut blocked).unwrap();
12382
12383        resolve_blockers(&queue, &questions);
12384
12385        let after = queue.get(&blocked.id).unwrap();
12386        assert_eq!(
12387            after.status,
12388            TaskStatus::Held,
12389            "never left blocked on nothing"
12390        );
12391        assert!(!after.operator_held(), "a machine hold, for triage");
12392        assert!(
12393            after
12394                .hold_reason
12395                .as_deref()
12396                .unwrap_or_default()
12397                .contains("went unanswered")
12398        );
12399    }
12400
12401    #[test]
12402    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
12403        // Reproduces the reported bug (task 3958): a task held out of
12404        // attempts, blocked on a `crate::conduct` follow-up question, must
12405        // come back `held` once that question is answered - never `queued`,
12406        // whatever the answer said - or it silently re-enters the
12407        // competition queue with its attempts already exhausted.
12408        let dir = tempfile::tempdir().unwrap();
12409        let queue = Queue::at(dir.path().join("queue"));
12410        let questions = ask::Questions::at(dir.path().join("questions"));
12411
12412        let mut q = crate::ask::Question::new(
12413            "20260101-000001-main".to_owned(),
12414            crate::conduct::NODE.to_owned(),
12415            "conduct".to_owned(),
12416            "How should this be handled?".to_owned(),
12417            String::new(),
12418            Vec::new(),
12419        );
12420        questions.put(&mut q).unwrap();
12421        q.answer(crate::ask::Answer::Text(
12422            "leave it held, a human will look at it later".to_owned(),
12423        ))
12424        .unwrap();
12425        questions.put(&mut q).unwrap();
12426
12427        let mut held = task();
12428        held.id = "20260101-000001-main".to_owned();
12429        held.hold_machine(Some("out of attempts".to_owned()));
12430        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
12431        queue.put(&mut held).unwrap();
12432
12433        resolve_blockers(&queue, &questions);
12434
12435        let after = queue.get(&held.id).unwrap();
12436        assert_eq!(after.status, TaskStatus::Held);
12437        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
12438        assert_eq!(
12439            after.answers[0].answer,
12440            "leave it held, a human will look at it later"
12441        );
12442    }
12443
12444    #[test]
12445    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
12446        let dir = tempfile::tempdir().unwrap();
12447        let queue = Queue::at(dir.path().join("queue"));
12448        let questions = ask::Questions::at(dir.path().join("questions"));
12449        let mut dep = task();
12450        dep.id = "20260101-000001-gone".to_owned();
12451        queue.put(&mut dep).unwrap();
12452        let mut blocked = task();
12453        blocked.id = "20260101-000003-main".to_owned();
12454        blocked.block(vec![dep.id.clone()], None);
12455        queue.put(&mut blocked).unwrap();
12456
12457        // Claimed, so `remove` cannot rewrite it and the resolver must.
12458        let claim = queue.claim(&blocked.id).unwrap();
12459        queue.remove(&dep.id, false, &questions).unwrap();
12460        drop(claim);
12461        resolve_blockers(&queue, &questions);
12462
12463        let after = queue.get(&blocked.id).unwrap();
12464        assert_eq!(after.status, TaskStatus::Queued);
12465        assert!(after.blocked_by.is_empty());
12466    }
12467
12468    #[test]
12469    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
12470        // Reproduces the reported bug: a task blocked on a task id that was
12471        // removed (`magi task rm`, or deleted by hand) can never see that id
12472        // reach `Done`, so the ordinary per-id loop has nothing to notice and
12473        // would otherwise leave the task `blocked` forever with no way for an
12474        // operator to find out why.
12475        let dir = tempfile::tempdir().unwrap();
12476        let queue = Queue::at(dir.path().join("queue"));
12477        let questions = ask::Questions::at(dir.path().join("questions"));
12478
12479        let mut still_going = task();
12480        still_going.id = "20260101-000002-dep1".to_owned();
12481        queue.put(&mut still_going).unwrap();
12482
12483        let mut blocked = task();
12484        blocked.id = "20260101-000003-main".to_owned();
12485        blocked.block(
12486            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
12487            Some("waits on both".to_owned()),
12488        );
12489        queue.put(&mut blocked).unwrap();
12490
12491        resolve_blockers(&queue, &questions);
12492
12493        let after = queue.get(&blocked.id).unwrap();
12494        assert_eq!(
12495            after.status,
12496            TaskStatus::Held,
12497            "a missing dependency must not leave the task blocked forever"
12498        );
12499        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
12500        assert!(after.blocked_by.is_empty());
12501        let reason = after.hold_reason.as_deref().unwrap_or_default();
12502        assert!(
12503            reason.contains("20260101-000001-gone"),
12504            "the missing id must be named so an operator can tell what happened: {reason}"
12505        );
12506        assert!(
12507            reason.contains(&still_going.id),
12508            "the still-valid dependency must not silently vanish from the record: {reason}"
12509        );
12510    }
12511
12512    #[test]
12513    fn instruction_for_is_unchanged_without_any_answers() {
12514        let t = task();
12515        assert_eq!(instruction_for(&t), t.instruction);
12516    }
12517
12518    #[test]
12519    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
12520        let dir = tempfile::tempdir().unwrap();
12521        let q = Queue::at(dir.path().join("queue"));
12522        let src = dir.path().join("shot.png");
12523        std::fs::write(&src, "x").unwrap();
12524        let mut t = task();
12525        q.attach(&mut t, &[src]).unwrap();
12526        let paths = task_attachments(&q, &t).unwrap();
12527        assert_eq!(paths.len(), 1);
12528        assert!(paths[0].is_absolute() && paths[0].is_file());
12529        std::fs::remove_file(&paths[0]).unwrap();
12530        let err = task_attachments(&q, &t).unwrap_err().to_string();
12531        assert!(err.contains("shot.png"), "{err}");
12532    }
12533
12534    #[tokio::test]
12535    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
12536        let dir = tempfile::tempdir().unwrap();
12537        let queue_path = dir.path().join("queue");
12538        let queue = Queue::at(queue_path.clone());
12539        let mut t = task();
12540        t.source = Source::Agent {
12541            run: "originating-chat".into(),
12542            node: crate::queue::CHAT_NODE.into(),
12543        };
12544        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
12545            stage: "config-fetch",
12546            target: "origin/main".into(),
12547        });
12548        record_config_failure(&mut t, &fetch);
12549        t.hold_machine(Some(format!("{fetch:#}")));
12550        let fetch_key = t.chat_notice_due().unwrap();
12551        t.chat_notices.push(fetch_key.clone());
12552        queue.put(&mut t).unwrap();
12553
12554        let queue = Queue::at(queue_path);
12555        let mut t = queue.get(&t.id).unwrap();
12556        let a = dir.path().join("a.toml");
12557        let b = dir.path().join("b.toml");
12558        for (path, text, new_cause) in [
12559            (&a, "[graph", true),
12560            (&a, "[verify", false),
12561            (&a, "[graph]\nimplementers = 'invalid-type'", true),
12562            (&b, "[graph]\nimplementers = 'invalid-type'", true),
12563        ] {
12564            t.release_operator("test", None);
12565            std::fs::write(path, text).unwrap();
12566            let error = Config::discover_fetched(dir.path(), Some(path))
12567                .await
12568                .unwrap_err();
12569            record_config_failure(&mut t, &error);
12570            t.hold_machine(Some(format!("{error:#}")));
12571            let due = t.chat_notice_due();
12572            assert_eq!(due.is_some(), new_cause, "{error:#}");
12573            if let Some(key) = due {
12574                assert_ne!(key, fetch_key);
12575                t.chat_notices.push(key);
12576            }
12577        }
12578        t.succeed();
12579        assert_eq!(t.chat_notice_due().as_deref(), Some("done"));
12580    }
12581
12582    #[test]
12583    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
12584        let dir = tempfile::tempdir().unwrap();
12585        let queue_path = dir.path().join("queue");
12586        let queue = Queue::at(queue_path.clone());
12587        let mut t = task();
12588        t.source = crate::queue::Source::Agent {
12589            run: "originating-chat".into(),
12590            node: crate::queue::CHAT_NODE.into(),
12591        };
12592        let a = dir.path().join("a.png");
12593        let b = dir.path().join("b.png");
12594        std::fs::write(&a, "a").unwrap();
12595        std::fs::write(&b, "b").unwrap();
12596        queue.attach(&mut t, &[a, b]).unwrap();
12597        let paths = task_attachments(&queue, &t).unwrap();
12598        for path in &paths {
12599            std::fs::remove_file(path).unwrap();
12600        }
12601        let missing = task_attachments(&queue, &t).unwrap_err();
12602        t.attempts += 1;
12603        let reason = missing.to_string();
12604        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12605        let first = t.chat_notice_due().expect("first attachment notice");
12606        t.chat_notices.push(first.clone());
12607        queue.put(&mut t).unwrap();
12608
12609        let queue = Queue::at(queue_path.clone());
12610        let mut t = queue.get(&t.id).unwrap();
12611        assert!(t.chat_notice_due().is_none(), "restart does not replay");
12612        t.release_operator("test", None);
12613        t.attempts += 1;
12614        let missing = task_attachments(&queue, &t).unwrap_err();
12615        t.fail_startup_target(
12616            "startup-attachments",
12617            missing.name,
12618            "same missing attachment with regenerated wording",
12619            1,
12620        );
12621        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
12622
12623        std::fs::write(&paths[0], "restored").unwrap();
12624        t.release_operator("test", None);
12625        t.attempts += 1;
12626        let missing = task_attachments(&queue, &t).unwrap_err();
12627        let reason = missing.to_string();
12628        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
12629        let second = t
12630            .chat_notice_due()
12631            .expect("different attachment must notify");
12632        assert_ne!(first, second);
12633        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
12634    }
12635
12636    #[test]
12637    fn resumed_instruction_is_unchanged_without_any_answers() {
12638        let t = task();
12639        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
12640    }
12641
12642    #[test]
12643    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
12644        let mut t = task();
12645        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12646        // The run's own instruction on disk predates the answer: it is the
12647        // plain original text `Runner::start` saved before the operator was
12648        // ever asked anything.
12649        let old = t.instruction.clone();
12650
12651        let refreshed = resumed_instruction(&old, &t);
12652        assert!(refreshed.starts_with(&old), "the original text is kept");
12653        assert!(refreshed.contains("Which backend?"));
12654        assert!(refreshed.contains("SQLite"));
12655    }
12656
12657    #[test]
12658    fn resumed_instruction_keeps_an_original_answers_heading() {
12659        let mut t = task();
12660        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
12661        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12662
12663        let refreshed = resumed_instruction(&t.instruction, &t);
12664
12665        assert!(
12666            refreshed.starts_with(&t.instruction),
12667            "an answers heading in the original instruction is not the appended block"
12668        );
12669        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
12670        assert!(refreshed.contains("Which backend?"));
12671        assert!(refreshed.contains("SQLite"));
12672
12673        let repeated = resumed_instruction(&refreshed, &t);
12674        assert_eq!(
12675            repeated, refreshed,
12676            "only the final appended block is refreshed"
12677        );
12678    }
12679
12680    #[test]
12681    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
12682        let mut t = task();
12683        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12684
12685        // A first resume appends the block; a second resume of the same run,
12686        // with no new answer in between, must reproduce exactly the same
12687        // text rather than appending the block a second time.
12688        let once = resumed_instruction(&t.instruction, &t);
12689        let twice = resumed_instruction(&once, &t);
12690        assert_eq!(once, twice);
12691        assert_eq!(once.matches("Which backend?").count(), 1);
12692
12693        // A later answer replaces the block wholesale rather than growing it.
12694        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
12695        let refreshed = resumed_instruction(&once, &t);
12696        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
12697        assert!(refreshed.contains("Which backend?"));
12698        assert!(refreshed.contains("Which cache?"));
12699    }
12700
12701    #[test]
12702    fn prepare_instruction_covers_all_three_starters() {
12703        let mut t = task();
12704        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
12705
12706        // Start: a fresh run gets the task text plus every answer so far —
12707        // exactly `instruction_for`.
12708        assert_eq!(
12709            prepare_instruction(&Starter::Start, None, &t),
12710            Some(instruction_for(&t))
12711        );
12712
12713        // Resume: the run's prior instruction is refreshed with the answer,
12714        // not discarded and not left stale.
12715        let old = t.instruction.clone();
12716        assert_eq!(
12717            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
12718            Some(resumed_instruction(&old, &t))
12719        );
12720
12721        // Review: a review-only pass builds its own instruction from the
12722        // branch's history in `crate::graph`, with no task statement at all -
12723        // this boundary must leave it alone.
12724        assert_eq!(
12725            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
12726            None
12727        );
12728    }
12729
12730    #[test]
12731    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
12732        assert_eq!(
12733            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
12734            Starter::Review("magi/eba2/A".to_owned())
12735        );
12736    }
12737
12738    #[test]
12739    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
12740        assert_eq!(
12741            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
12742            Starter::Start,
12743            "a vanished review branch must not fall back to resuming the old run either"
12744        );
12745    }
12746
12747    #[test]
12748    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
12749        let mut t = task();
12750        t.start("old-run".to_owned());
12751        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
12752        t.release();
12753        let branch = t.review_branch.take();
12754        assert_eq!(
12755            choose_starter(branch.as_deref(), true, Some("old-run")),
12756            Starter::Review("magi/eba2/A".to_owned()),
12757            "a review wins over resuming the old run"
12758        );
12759    }
12760
12761    #[test]
12762    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
12763        assert_eq!(
12764            choose_starter(None, false, Some("some-run")),
12765            Starter::Resume("some-run".to_owned())
12766        );
12767        assert_eq!(choose_starter(None, false, None), Starter::Start);
12768    }
12769
12770    #[test]
12771    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
12772        let mut released = task();
12773        released.start("stalled-run".to_owned());
12774        released.requeue();
12775        let unfinished = (!released.fresh_start)
12776            .then(|| Some("stalled-run".to_owned()))
12777            .flatten();
12778        assert_eq!(
12779            choose_starter(None, false, unfinished.as_deref()),
12780            Starter::Start,
12781            "release keeps run history but must not resume it"
12782        );
12783        assert_eq!(released.runs, ["stalled-run"]);
12784    }
12785
12786    #[test]
12787    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
12788        let dir = tempfile::tempdir().unwrap();
12789        let queue = Queue::at(dir.path().join("queue"));
12790        let mut state = run_state(RunStatus::Blocked);
12791        state.merge_decision = Some(crate::merge_decision::Decision {
12792            question: "hold-inquiry".into(),
12793            target: crate::merge_decision::Target {
12794                pr: "https://example.test/pull/1".into(),
12795                head: "reviewed-head".into(),
12796                language: "en".into(),
12797            },
12798            choice: land::HOLD.into(),
12799            closed: false,
12800            replacement_run: None,
12801            replacement_pr: None,
12802        });
12803        let mut t = task();
12804        t.start(state.id.clone());
12805        settle_and_diagnose(
12806            &mut t,
12807            Verdict {
12808                status: RunStatus::Blocked,
12809                left_pr: true,
12810                quota_hit: false,
12811                parked: false,
12812                no_viable_candidates: false,
12813            },
12814            "held",
12815            2,
12816            &state,
12817        );
12818        queue.put(&mut t).unwrap();
12819        t.release_operator("chat", None);
12820        t.edit("revised".into(), "revised instruction".into())
12821            .unwrap();
12822        queue.put(&mut t).unwrap();
12823        drop(state);
12824        assert_eq!(
12825            queue
12826                .get(&t.id)
12827                .unwrap()
12828                .decision_effects
12829                .get("hold-inquiry"),
12830            Some(&format!("decision: {}", land::HOLD))
12831        );
12832    }
12833
12834    fn stopped_public_run(status: RunStatus) -> RunState {
12835        let mut state = run_state(status);
12836        state.driver_exited = true;
12837        state.config.graph.land = true;
12838        state.config.graph.review_rounds = 1;
12839        state.reviews = vec![review_round(1)];
12840        state.merge = Some(crate::run::MergeOutcome {
12841            mode: MergeMode::Pr,
12842            ok: false,
12843            detail: "landing stopped".into(),
12844            empty: false,
12845        });
12846        state.pr = Some(crate::run::PrRecord {
12847            url: "https://example.test/pull/1".into(),
12848            number: 1,
12849            state: "open".into(),
12850            checks: "red".into(),
12851            round: 1,
12852            rounds: 1,
12853            red_at_merge: Vec::new(),
12854        });
12855        state
12856    }
12857
12858    #[test]
12859    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
12860        for status in [RunStatus::Blocked, RunStatus::Gating] {
12861            let home = tempfile::tempdir().unwrap();
12862            let mut state = stopped_public_run(status);
12863            state.save_under(home.path()).unwrap();
12864            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
12865            assert!(!exhausted_review_budget(&state));
12866            let mut task = held_task_with(&state.id);
12867            task.release();
12868            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
12869            assert_eq!(
12870                choose_starter(None, false, unfinished.as_deref()),
12871                Starter::Resume(state.id.clone())
12872            );
12873            let question = action_question(&state.id, resume_action(&state.id));
12874            assert_eq!(
12875                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12876                    state.clone()
12877                )),
12878                ActionDecision::Resume(state.id.clone())
12879            );
12880            // The control-plane command uses this same preflight before pinning.
12881            assert_eq!(
12882                crate::resume::validate(home.path(), &state.id).unwrap().id,
12883                state.id
12884            );
12885            let queue = Queue::at(home.path().join("queue"));
12886            let mut controlled = Task::new(
12887                "resume land".into(),
12888                state.instruction.clone(),
12889                state.repo.clone(),
12890                Source::Agent {
12891                    run: "talk".into(),
12892                    node: crate::queue::CHAT_NODE.into(),
12893                },
12894            );
12895            controlled.runs.push(state.id.clone());
12896            controlled.hold_machine(Some("land stopped".into()));
12897            queue.put(&mut controlled).unwrap();
12898            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
12899            assert_eq!(resumed.status, TaskStatus::Queued);
12900            assert_eq!(
12901                resumed.resume_override.unwrap().pinned_run,
12902                Some(state.id.clone())
12903            );
12904            assert_eq!(resumed.attempts, 0);
12905        }
12906    }
12907
12908    #[test]
12909    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
12910        for review_rounds in [0, 1] {
12911            let home = tempfile::tempdir().unwrap();
12912            let mut state = run_state(RunStatus::Blocked);
12913            state.config.graph.review_rounds = review_rounds;
12914            if review_rounds > 0 {
12915                let mut review = review_round(1);
12916                review.clean = true;
12917                state.reviews = vec![review];
12918            }
12919            state.gate_ran = true;
12920            state.gate = vec![crate::run::CommandOutcome {
12921                command: "verify".into(),
12922                code: Some(1),
12923                output_tail: "gate failed after repair budget exhausted".into(),
12924                duration_ms: 0,
12925                resource_blocked: false,
12926            }];
12927            state.save_under(home.path()).unwrap();
12928            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
12929            assert!(exhausted_review_budget(&state));
12930            let mut task = held_task_with(&state.id);
12931            task.release();
12932            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
12933            let question = action_question(&state.id, resume_action(&state.id));
12934            assert_ne!(
12935                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
12936                    state.clone()
12937                )),
12938                ActionDecision::Resume(state.id.clone())
12939            );
12940            let error = crate::resume::validate(home.path(), &state.id)
12941                .unwrap_err()
12942                .to_string();
12943            assert!(!error.contains("review budget exhausted"), "{error}");
12944            assert!(
12945                error.contains(if review_rounds == 0 {
12946                    "review is disabled"
12947                } else {
12948                    "gate already ran"
12949                }),
12950                "{error}"
12951            );
12952
12953            // An unexecuted gate still has work to do with or without reviews.
12954            state.gate_ran = false;
12955            state.gate.clear();
12956            assert!(!exhausted_review_budget(&state));
12957            assert_eq!(
12958                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
12959                Some(state.id)
12960            );
12961        }
12962    }
12963
12964    #[test]
12965    fn resource_blocked_verification_resumes_the_same_run() {
12966        for (kind, stage) in [
12967            ("cache", "clean"),
12968            ("coordination", "clean"),
12969            ("cache", "review-e2e"),
12970            ("coordination", "no-reviews"),
12971            ("coordination", "handoff"),
12972        ] {
12973            let home = tempfile::tempdir().unwrap();
12974            let mut state = run_state(RunStatus::Blocked);
12975            state.config.graph.review_rounds = 1;
12976            let mut review = review_round(1);
12977            review.clean = true;
12978            state.reviews = vec![review];
12979            if stage == "review-e2e" {
12980                let review = &mut state.reviews[0];
12981                review.clean = false;
12982                review.blocking = 1;
12983                review.e2e = vec![crate::run::CommandOutcome {
12984                    command: "verify".into(),
12985                    code: None,
12986                    output_tail: "resource wait expired".into(),
12987                    duration_ms: 0,
12988                    resource_blocked: true,
12989                }];
12990            } else if stage == "no-reviews" {
12991                state.config.graph.review_rounds = 0;
12992                state.reviews.clear();
12993            } else if stage == "handoff" {
12994                // A completed final verification can hand off to the gate
12995                // even when the review still carries contested findings.
12996                let review = &mut state.reviews[0];
12997                review.clean = false;
12998                review.blocking = 1;
12999                review.e2e = vec![crate::run::CommandOutcome {
13000                    command: "verify".into(),
13001                    code: Some(0),
13002                    output_tail: String::new(),
13003                    duration_ms: 0,
13004                    resource_blocked: false,
13005                }];
13006            }
13007            state.gate_ran = false;
13008            state.resource_block = Some(crate::run::ResourceBlock {
13009                cause: crate::run::ResourceBlockCause::Other,
13010                node: if stage == "review-e2e" {
13011                    "review"
13012                } else {
13013                    "gate"
13014                }
13015                .into(),
13016                kind: kind.into(),
13017                detail: "resource wait expired".into(),
13018                at: jiff::Timestamp::now(),
13019            });
13020            state.save_under(home.path()).unwrap();
13021            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13022            assert!(!exhausted_review_budget(&state));
13023            let mut task = held_task_with(&state.id);
13024            task.release();
13025            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13026            assert_eq!(
13027                choose_starter(None, false, unfinished.as_deref()),
13028                Starter::Resume(state.id.clone())
13029            );
13030            let question = action_question(&state.id, resume_action(&state.id));
13031            assert_eq!(
13032                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13033                    state.clone()
13034                )),
13035                ActionDecision::Resume(state.id.clone())
13036            );
13037            assert_eq!(
13038                crate::resume::validate(home.path(), &state.id).unwrap().id,
13039                state.id
13040            );
13041            let queue = Queue::at(home.path().join("queue"));
13042            let mut controlled = Task::new(
13043                "resume verification".into(),
13044                state.instruction.clone(),
13045                state.repo.clone(),
13046                Source::Agent {
13047                    run: "talk".into(),
13048                    node: crate::queue::CHAT_NODE.into(),
13049                },
13050            );
13051            controlled.runs.push(state.id.clone());
13052            controlled.hold_machine(Some("verification resource unavailable".into()));
13053            queue.put(&mut controlled).unwrap();
13054            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13055            assert_eq!(resumed.status, TaskStatus::Queued);
13056            assert_eq!(
13057                resumed.resume_override.unwrap().pinned_run,
13058                Some(state.id.clone())
13059            );
13060            assert_eq!(resumed.attempts, 0);
13061
13062            // A genuinely unresolved final review still exhausts the budget.
13063            state.config.graph.review_rounds = 1;
13064            let mut unresolved = review_round(1);
13065            unresolved.blocking = 1;
13066            state.reviews = vec![unresolved];
13067            state.resource_block = None;
13068            state.save_under(home.path()).unwrap();
13069            assert!(exhausted_review_budget(&state));
13070            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13071        }
13072    }
13073
13074    #[tokio::test]
13075    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13076        if !crate::standalone_test(
13077            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13078        ) {
13079            return;
13080        }
13081        let home = tempfile::tempdir().unwrap();
13082        let mut owner = stopped_public_run(RunStatus::Blocked);
13083        owner.save_under(home.path()).unwrap();
13084        let history = vec![owner.id.clone()];
13085        let repo = owner.repo.clone();
13086        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13087        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13088        let initial =
13089            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13090        assert!(
13091            initial.is_pending(),
13092            "a busy record must not hold or resume the task"
13093        );
13094        owner.retired_to = Some("20260101-000001-bbbb".into());
13095        owner.save_under(home.path()).unwrap();
13096        drop(lock);
13097        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13098            .await
13099            .expect("ownership lock released")
13100            .expect("read settled owner");
13101        assert!(
13102            result.is_none(),
13103            "the retired owner must not be resumed from a stale read"
13104        );
13105    }
13106
13107    #[tokio::test]
13108    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13109        if !crate::standalone_test(
13110            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13111        ) {
13112            return;
13113        }
13114        let home = tempfile::tempdir().unwrap();
13115        let mut owner = stopped_public_run(RunStatus::Blocked);
13116        let repo = tempfile::tempdir().unwrap();
13117        crate::git::git(repo.path(), &["init"]).await.unwrap();
13118        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13119        owner.id = "20260101-000000-aaaa".into();
13120        owner.save_under(home.path()).unwrap();
13121        let mut successor = run_state(RunStatus::Blocked);
13122        successor.id = "20260101-000001-bbbb".into();
13123        successor.save_under(home.path()).unwrap();
13124        let runs = vec![owner.id.clone(), successor.id.clone()];
13125        assert_eq!(
13126            public_resume_owner(home.path(), &runs, &owner.repo)
13127                .await
13128                .unwrap()
13129                .unwrap()
13130                .id,
13131            owner.id
13132        );
13133        let subdir = owner.repo.join("nested");
13134        std::fs::create_dir(&subdir).unwrap();
13135        assert_eq!(
13136            public_resume_owner(home.path(), &runs, &subdir)
13137                .await
13138                .unwrap()
13139                .unwrap()
13140                .id,
13141            owner.id
13142        );
13143        #[cfg(unix)]
13144        {
13145            let alias = home.path().join("repo-alias");
13146            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13147            assert_eq!(
13148                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13149                    .await
13150                    .unwrap()
13151                    .unwrap()
13152                    .id,
13153                owner.id
13154            );
13155        }
13156        let different = tempfile::tempdir().unwrap();
13157        crate::git::git(different.path(), &["init"]).await.unwrap();
13158        assert!(
13159            public_resume_owner(home.path(), &runs, different.path())
13160                .await
13161                .is_err()
13162        );
13163        std::fs::remove_file(
13164            home.path()
13165                .join("runs")
13166                .join(&successor.id)
13167                .join("run.json"),
13168        )
13169        .unwrap();
13170        assert!(
13171            public_resume_owner(home.path(), &runs, &owner.repo)
13172                .await
13173                .is_err()
13174        );
13175    }
13176
13177    #[test]
13178    fn an_ordinary_release_keeps_a_resumable_run_available() {
13179        let mut released = task();
13180        released.start("stalled-run".to_owned());
13181        released.release();
13182        let unfinished = (!released.fresh_start)
13183            .then(|| Some("stalled-run".to_owned()))
13184            .flatten();
13185        assert_eq!(
13186            choose_starter(None, false, unfinished.as_deref()),
13187            Starter::Resume("stalled-run".to_owned()),
13188            "manual release must preserve the normal resume path"
13189        );
13190    }
13191
13192    #[test]
13193    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13194        use crate::handover::{ResumeRefusal, resume_refusal_under};
13195        let home = tempfile::tempdir().unwrap();
13196        let mut exhausted = run_state(RunStatus::Blocked);
13197        exhausted.driver_exited = true;
13198        exhausted.config.graph.review_rounds = 3;
13199        exhausted.reviews = (1..=3).map(review_round).collect();
13200        for refusal in [
13201            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13202            ResumeRefusal::Status(RunStatus::Ready),
13203            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13204            ResumeRefusal::Retired("retirement-successor".into()),
13205            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13206        ] {
13207            let mut state = exhausted.clone();
13208            let expected = match refusal {
13209                ResumeRefusal::Status(_) => {
13210                    state.status = RunStatus::Ready;
13211                    "status `ready`"
13212                }
13213                ResumeRefusal::Released(ref target) => {
13214                    state.released_to = Some(target.clone());
13215                    "execution was released"
13216                }
13217                ResumeRefusal::Retired(ref target) => {
13218                    state.retired_to = Some(target.clone());
13219                    "execution was retired"
13220                }
13221                ResumeRefusal::OwnershipTransferred(ref target) => {
13222                    state.pr_taken_over_by = Some(target.clone());
13223                    "PR ownership was transferred"
13224                }
13225                _ => "review budget exhausted (3/3 rounds used)",
13226            };
13227            assert_eq!(
13228                resume_refusal_under(&state, Some(home.path())),
13229                Some(refusal.clone())
13230            );
13231            assert_eq!(
13232                refusal.successor(),
13233                state
13234                    .released_to
13235                    .as_deref()
13236                    .or(state.retired_to.as_deref())
13237                    .or(state.pr_taken_over_by.as_deref())
13238            );
13239            state.save_under(home.path()).unwrap();
13240            let queue = Queue::at(home.path().join("queue"));
13241            let mut task = Task::new(
13242                "retained implementation".into(),
13243                state.instruction.clone(),
13244                state.repo.clone(),
13245                Source::Agent {
13246                    run: "talk".into(),
13247                    node: crate::queue::CHAT_NODE.into(),
13248                },
13249            );
13250            task.runs.push(state.id.clone());
13251            task.hold_machine(Some("stopped".into()));
13252            queue.put(&mut task).unwrap();
13253            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
13254            let before_run = serde_json::to_value(&state).unwrap();
13255            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
13256                .unwrap_err()
13257                .to_string();
13258            assert!(error.contains(expected), "{error}");
13259            assert!(!error.contains("only a stalled or blocked"), "{error}");
13260            if matches!(refusal, ResumeRefusal::Status(_)) {
13261                assert!(
13262                    error.contains("is final; there is nothing left to resume"),
13263                    "{error}"
13264                );
13265            }
13266            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
13267                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
13268                assert!(error.contains("review-only successor with a new review budget"));
13269                assert!(error.contains("does not resume this run"));
13270            }
13271            for target in [
13272                &state.released_to,
13273                &state.retired_to,
13274                &state.pr_taken_over_by,
13275            ]
13276            .into_iter()
13277            .flatten()
13278            {
13279                let short = if state.retired_to.as_ref() == Some(target) {
13280                    target.as_str()
13281                } else {
13282                    crate::run::short_of(target)
13283                };
13284                assert!(
13285                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
13286                    "{error}"
13287                );
13288                if short != target {
13289                    assert!(!error.contains(target), "full successor id leaked: {error}");
13290                }
13291            }
13292            assert_eq!(
13293                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
13294                before_task
13295            );
13296            assert_eq!(
13297                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
13298                    .unwrap(),
13299                before_run
13300            );
13301            let question = action_question(&state.id, resume_action(&state.id));
13302            for phrases in [&PHRASES_EN, &PHRASES_JA] {
13303                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
13304                    RunState::load_under(id, home.path())
13305                });
13306                let ActionDecision::Refuse(detail) = decision else {
13307                    panic!(
13308                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
13309                        state.id,
13310                        home.path().display()
13311                    );
13312                };
13313                assert!(detail.contains(expected), "{detail}");
13314            }
13315        }
13316        // Preserve predicate ordering, while keeping every recorded destination visible.
13317        exhausted.status = RunStatus::Ready;
13318        exhausted.released_to = Some("released".into());
13319        exhausted.retired_to = Some("retired".into());
13320        exhausted.pr_taken_over_by = Some("owner".into());
13321        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
13322        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
13323        let detail = reason.diagnostic(&exhausted);
13324        for target in ["released", "retired", "owner"] {
13325            assert!(detail.contains(&format!("magi show {target}")));
13326        }
13327    }
13328
13329    #[test]
13330    fn resume_action_ignores_question_checkpoints_in_another_home() {
13331        crate::run::pin_test_home();
13332        let home = tempfile::tempdir().unwrap();
13333        let mut state = run_state(RunStatus::Blocked);
13334        // The private directory reserves this fixture's identity even while
13335        // other tests write questions into the process-wide store.
13336        state.id = format!(
13337            "resume-context-{}",
13338            home.path().file_name().unwrap().to_str().unwrap()
13339        );
13340        state.driver_exited = true;
13341        state.config.graph.review_rounds = 1;
13342        state.reviews = vec![review_round(1)];
13343        state.save_under(home.path()).unwrap();
13344        let task = held_task_with(&state.id);
13345        let answer = action_question(&state.id, resume_action(&state.id));
13346        let mut checkpoint = approval_question(&state.id);
13347        let foreign = Questions::open();
13348        foreign.put(&mut checkpoint).unwrap();
13349        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
13350        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13351            RunState::load_under(id, home.path())
13352        });
13353        let matching: Vec<_> = foreign
13354            .list()
13355            .into_iter()
13356            .filter(|q| q.run == state.id && q.status.open())
13357            .collect();
13358        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
13359        assert!(
13360            matches!(decision, ActionDecision::Refuse(_)),
13361            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
13362            state.id,
13363            home.path().display(),
13364            crate::run::test_home().display()
13365        );
13366        assert_eq!(
13367            refusal,
13368            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
13369        );
13370        let local = Questions::at(home.path().join("questions"));
13371        for status in [
13372            ask::QuestionStatus::Open,
13373            ask::QuestionStatus::Answered,
13374            ask::QuestionStatus::Abandoned,
13375        ] {
13376            let mut question = checkpoint.clone();
13377            match status {
13378                ask::QuestionStatus::Open => {}
13379                ask::QuestionStatus::Answered => {
13380                    question
13381                        .answer(ask::Answer::Choice(question.choices[0].clone()))
13382                        .unwrap();
13383                }
13384                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
13385            }
13386            local.put(&mut question).unwrap();
13387            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
13388                RunState::load_under(id, home.path())
13389            });
13390            if status.open() {
13391                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
13392            } else {
13393                assert!(
13394                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
13395                    "status={status:?}, decision={decision:?}"
13396                );
13397            }
13398        }
13399    }
13400
13401    #[test]
13402    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
13403        let home = tempfile::tempdir().unwrap();
13404        let mut state = run_state(RunStatus::Stalled);
13405        state.id = format!(
13406            "resume-driver-{}",
13407            home.path().file_name().unwrap().to_str().unwrap()
13408        );
13409        state.driver_claimed = Some(false);
13410        state.save_under(home.path()).unwrap();
13411        let task = held_task_with(&state.id);
13412        let question = action_question(&state.id, resume_action(&state.id));
13413        let decide = || {
13414            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
13415                RunState::load_under(id, home.path())
13416            })
13417        };
13418        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
13419        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
13420        assert_eq!(
13421            decide(),
13422            ActionDecision::Refuse("run already has a live driver".into())
13423        );
13424        drop(lease);
13425        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
13426    }
13427
13428    #[test]
13429    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
13430        let home = tempfile::tempdir().unwrap();
13431        let mut state = run_state(RunStatus::Blocked);
13432        state.driver_exited = true;
13433        state.config.graph.review_rounds = 1;
13434        state.reviews = vec![review_round(1)];
13435        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
13436        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
13437            let mut saved = state.clone();
13438            match checkpoint {
13439                "publication" => saved.pr_publication_pending = true,
13440                "approval" => {
13441                    saved.land_approval = Some(crate::run::LandApproval {
13442                        question: "approval".into(),
13443                        head: "head".into(),
13444                    })
13445                }
13446                "armed" => saved.land_armed_head = Some("head".into()),
13447                "landing" => saved.status = RunStatus::Landing,
13448                _ => {
13449                    let mut question = ask::Question::new(
13450                        saved.id.clone(),
13451                        "review".into(),
13452                        "review-1".into(),
13453                        "continue?".into(),
13454                        String::new(),
13455                        vec!["continue".into()],
13456                    );
13457                    ask::Questions::at(home.path().join("questions"))
13458                        .put(&mut question)
13459                        .unwrap();
13460                }
13461            }
13462            saved.save_under(home.path()).unwrap();
13463            assert!(
13464                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
13465                "{checkpoint}"
13466            );
13467            assert!(
13468                crate::resume::validate(home.path(), &saved.id).is_ok(),
13469                "{checkpoint}"
13470            );
13471        }
13472    }
13473
13474    #[test]
13475    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
13476        let mut state = run_state(RunStatus::Blocked);
13477        state.config.graph.review_rounds = 3;
13478        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
13479        assert!(exhausted_review_budget(&state));
13480
13481        // One round still unused: resuming can still ask a reviewer something.
13482        state.reviews.pop();
13483        assert!(!exhausted_review_budget(&state));
13484
13485        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
13486        // count: only a `Blocked` run re-enters the review loop on resume.
13487        let mut stalled = run_state(RunStatus::Stalled);
13488        stalled.config.graph.review_rounds = 1;
13489        stalled.reviews = vec![review_round(1)];
13490        assert!(!exhausted_review_budget(&stalled));
13491    }
13492
13493    fn review_round(round: usize) -> crate::run::ReviewRound {
13494        crate::run::ReviewRound {
13495            round,
13496            head: "deadbeef".to_owned(),
13497            verified_head: None,
13498            verified_at: None,
13499            reviews: Vec::new(),
13500            e2e: Vec::new(),
13501            verify_retried: false,
13502            e2e_deferred: false,
13503            e2e_defer_reason: None,
13504            fix: None,
13505            blocking: 0,
13506            answered: 1,
13507            expected: 1,
13508            clean: false,
13509            progressed: true,
13510            vote_split: false,
13511            reconsideration: Vec::new(),
13512            verdict: None,
13513        }
13514    }
13515
13516    #[test]
13517    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
13518        let mut run = RunState::new(
13519            PathBuf::from("/repo"),
13520            "main".to_owned(),
13521            "abc1234def".to_owned(),
13522            "add retries".to_owned(),
13523            Config::default(),
13524        );
13525        run.status = RunStatus::Judging;
13526        run.parked = true;
13527        let mut task = Task::new(
13528            "add retries".to_owned(),
13529            "add retries".to_owned(),
13530            PathBuf::from("/repo"),
13531            crate::queue::Source::Human,
13532        );
13533        task.status = TaskStatus::Failed;
13534        task.runs = vec![run.id.clone()];
13535        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
13536        assert!(with(&task, &run), "parked after judging is the case");
13537        let mut parked_task = task.clone();
13538        parked_task.status = TaskStatus::Parked;
13539        assert!(with(&parked_task, &run), "the Parked status is the case");
13540
13541        let mut not_parked = run.clone();
13542        not_parked.parked = false;
13543        not_parked.status = RunStatus::Stalled;
13544        assert!(!with(&task, &not_parked), "a stall is the conductor's");
13545
13546        let mut fresh = task.clone();
13547        fresh.fresh_start = true;
13548        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
13549
13550        let mut review = task.clone();
13551        review.review_branch = Some("magi/x/A".to_owned());
13552        assert!(!with(&review, &run), "review is ranked before resume");
13553
13554        let mut held = task.clone();
13555        held.status = TaskStatus::Held;
13556        assert!(!with(&held, &run), "a hold stays visible to the conductor");
13557
13558        let mut released = run.clone();
13559        released.released_to = Some("20260901-000000-new1".to_owned());
13560        assert!(!with(&task, &released), "nothing left to resume into");
13561
13562        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
13563            "unreadable"
13564        )));
13565    }
13566
13567    #[test]
13568    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
13569        let mut released = RunState::new(
13570            PathBuf::from("/repo"),
13571            "main".to_owned(),
13572            "abc1234def".to_owned(),
13573            "add retries".to_owned(),
13574            Config::default(),
13575        );
13576        released.status = RunStatus::Blocked;
13577        assert_eq!(
13578            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13579            Some(released.id.clone())
13580        );
13581        released.released_to = Some("20260901-000000-new1".to_owned());
13582        assert_eq!(
13583            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
13584            None,
13585            "there is nothing left to resume it into"
13586        );
13587    }
13588
13589    #[test]
13590    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
13591        // Mirrors the failure this exists to close: a task's last run ended
13592        // `Blocked` with the review budget spent, `crate::conduct` chose
13593        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
13594        // evidence), and without this check `attempt` would go on treating
13595        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
13596        // review loop iterates zero times over an already-spent budget, so
13597        // the resumed run settles right back to `Blocked` having asked nobody
13598        // anything, and `Requeue`'s promised fresh competition never happens.
13599        let mut exhausted = RunState::new(
13600            PathBuf::from("/repo"),
13601            "main".to_owned(),
13602            "abc1234def".to_owned(),
13603            "add retries".to_owned(),
13604            Config::default(),
13605        );
13606        exhausted.status = RunStatus::Blocked;
13607        exhausted.config.graph.review_rounds = 1;
13608        exhausted.reviews = vec![review_round(1)];
13609
13610        assert_eq!(
13611            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
13612            None,
13613            "an exhausted `Blocked` run must not be offered as resumable"
13614        );
13615
13616        // A `Blocked` run with rounds still unused is genuinely worth
13617        // resuming, and must still be found.
13618        let mut has_budget_left = RunState::new(
13619            PathBuf::from("/repo"),
13620            "main".to_owned(),
13621            "abc1234def".to_owned(),
13622            "add retries".to_owned(),
13623            Config::default(),
13624        );
13625        has_budget_left.status = RunStatus::Blocked;
13626        has_budget_left.config.graph.review_rounds = 3;
13627        has_budget_left.reviews = vec![review_round(1)];
13628
13629        assert_eq!(
13630            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
13631                Ok(has_budget_left.clone())
13632            }),
13633            Some(has_budget_left.id.clone())
13634        );
13635    }
13636
13637    #[test]
13638    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
13639        let mut run = RunState::new(
13640            PathBuf::from("/repo"),
13641            "main".to_owned(),
13642            "abc1234def".to_owned(),
13643            "add retries".to_owned(),
13644            Config::default(),
13645        );
13646        run.status = RunStatus::Blocked;
13647        run.config.graph.review_rounds = 1;
13648        run.reviews = vec![review_round(1)];
13649        run.pr_publication_pending = true;
13650        assert_eq!(
13651            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
13652            Some(run.id.clone()),
13653            "a spent review budget must not turn a failed publication into a re-competition"
13654        );
13655    }
13656
13657    #[test]
13658    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
13659        let mut task = Task::new(
13660            "recover work".into(),
13661            "recover work".into(),
13662            PathBuf::from("/repo"),
13663            crate::queue::Source::Human,
13664        );
13665        let mut history = std::collections::BTreeMap::new();
13666        for index in 0..8 {
13667            let mut run = run_state(RunStatus::Blocked);
13668            run.id = format!("20260101-000000-{index:04}");
13669            run.base_commit = format!("upstream-{index}");
13670            // Seven empty newer attempts must not erase the old recovery owner.
13671            if index > 0 {
13672                run.candidates.clear();
13673            }
13674            task.runs.extend([run.id.clone(), run.id.clone()]);
13675            history.insert(run.id.clone(), run);
13676            task.requeue();
13677        }
13678        let check = |task: &Task, starter: &Starter, limit| {
13679            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
13680        };
13681        assert!(
13682            check(&task, &Starter::Start, 8)
13683                .unwrap()
13684                .contains("8 unretired")
13685        );
13686        assert!(check(&task, &Starter::Start, 9).is_none());
13687        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
13688        task.release_operator("owner", None);
13689        assert_eq!(task.attempts, 0);
13690        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13691        assert!(check(&restored, &Starter::Start, 8).is_some());
13692        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
13693        assert!(check(&restored, &Starter::Start, 0).is_none());
13694    }
13695
13696    #[test]
13697    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
13698        let tmp = tempfile::tempdir().unwrap();
13699        let mut task = Task::new(
13700            "recover selected PR".into(),
13701            "preserve implementation".into(),
13702            tmp.path().join("repo"),
13703            crate::queue::Source::Human,
13704        );
13705        let mut failed = run_state(RunStatus::Failed);
13706        failed.id = "20260101-000000-fail".into();
13707        failed.candidates.clear();
13708        failed.prep_complete = Some(false);
13709        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
13710        failed.startup = Some(crate::run::Startup {
13711            kind: "pr-recovery".into(),
13712            branch: Some("selected-public-head".into()),
13713            stage: "worktree-setup".into(),
13714            complete: false,
13715            failure: Some("setup modified a tracked file and failed".into()),
13716        });
13717        // Setup may fail before a candidate is recorded; its dirty worktree
13718        // still needs protection and consumes the independent retained bound.
13719        let worktree = failed.worktree_root().join("under-review");
13720        std::fs::create_dir_all(&worktree).unwrap();
13721        let retained_edit = worktree.join("implementation");
13722        std::fs::write(&retained_edit, "retained setup edit").unwrap();
13723        task.record_startup_failure(crate::run::StartupFailure {
13724            run: failed.id.clone(),
13725            stage: "worktree-setup".into(),
13726        });
13727        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
13728        assert!(task.runs.is_empty() && task.passes.is_empty());
13729        assert_eq!(task.attempts, 0);
13730        let starter = Starter::Review("selected-public-head".into());
13731        assert!(
13732            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
13733                .unwrap()
13734                .contains("1 unretired")
13735        );
13736        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
13737        assert!(
13738            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
13739                .unwrap()
13740                .contains("Cannot verify")
13741        );
13742        // Older or mixed writers can link the same reservation in both lists.
13743        let mut mixed = task.clone();
13744        mixed.runs.push(failed.id.clone());
13745        mixed
13746            .startup_failures
13747            .push(task.startup_failures[0].clone());
13748        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
13749        failed.retired_to = Some("verified-recovery-owner".into());
13750        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
13751        assert!(
13752            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
13753                panic!("resuming the existing owner must not allocate a new attempt")
13754            })
13755            .is_none()
13756        );
13757        assert_eq!(
13758            std::fs::read_to_string(retained_edit).unwrap(),
13759            "retained setup edit"
13760        );
13761        assert!(task.runs.is_empty() && task.passes.is_empty());
13762        assert_eq!(task.attempts, 0);
13763    }
13764
13765    #[test]
13766    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
13767        let mut task = Task::new(
13768            "recover work".into(),
13769            "recover work".into(),
13770            PathBuf::from("/repo"),
13771            crate::queue::Source::Human,
13772        );
13773        let mut run = run_state(RunStatus::Superseded);
13774        run.candidates.clear();
13775        task.runs.push(run.id.clone());
13776        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
13777        run.retired_to = Some("authority".into());
13778        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13779        run.retired_to = None;
13780        run.released_to = Some("authority".into());
13781        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
13782        assert!(
13783            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
13784                .unwrap()
13785                .contains("Cannot verify")
13786        );
13787        // Resuming an existing owner needs no new inventory or worktree budget.
13788        assert!(
13789            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
13790                panic!("resume must not load historical attempts")
13791            })
13792            .is_none()
13793        );
13794    }
13795
13796    #[test]
13797    fn retired_resume_requires_a_valid_same_repository_authority() {
13798        let mut source = run_state(RunStatus::Blocked);
13799        let mut empty = run_state(RunStatus::Blocked);
13800        empty.retired_to = Some(source.id.clone());
13801        let runs = vec![source.id.clone(), empty.id.clone()];
13802        let resolve = |source: &RunState, empty: &RunState| {
13803            unfinished_run_with(&runs, "fixture", |id| {
13804                if id == source.id {
13805                    Ok(source.clone())
13806                } else if id == empty.id {
13807                    Ok(empty.clone())
13808                } else {
13809                    bail!("unreadable authority")
13810                }
13811            })
13812        };
13813        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
13814        assert_eq!(
13815            choose_starter(None, false, resolve(&source, &empty).as_deref()),
13816            Starter::Resume(source.id.clone())
13817        );
13818        source.retired_to = Some(empty.id.clone());
13819        assert!(
13820            resolve(&source, &empty).is_none(),
13821            "cycles do not revive obsolete runs"
13822        );
13823        source.retired_to = None;
13824        source.repo = PathBuf::from("/another-repository");
13825        assert!(resolve(&source, &empty).is_none());
13826        source.repo = empty.repo.clone();
13827        source.released_to = Some("later".into());
13828        assert!(resolve(&source, &empty).is_none());
13829        empty.retired_to = Some("unlisted-run".into());
13830        assert!(resolve(&source, &empty).is_none());
13831    }
13832
13833    #[test]
13834    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
13835        // A task whose history holds an *older* run that still looks
13836        // resumable (say, a competition `Runner::review` was started
13837        // alongside after that older run went `Stalled`) and a *newest* run
13838        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
13839        // on this task must mean a fresh competition — falling back to the
13840        // stale, superseded `Stalled` run instead would resurrect history
13841        // nothing asked to revisit and silently defeat the requeue.
13842        let mut older_stalled = RunState::new(
13843            PathBuf::from("/repo"),
13844            "main".to_owned(),
13845            "abc1234def".to_owned(),
13846            "add retries".to_owned(),
13847            Config::default(),
13848        );
13849        older_stalled.status = RunStatus::Stalled;
13850
13851        let mut newest_exhausted = RunState::new(
13852            PathBuf::from("/repo"),
13853            "main".to_owned(),
13854            "abc1234def".to_owned(),
13855            "add retries".to_owned(),
13856            Config::default(),
13857        );
13858        newest_exhausted.status = RunStatus::Blocked;
13859        newest_exhausted.config.graph.review_rounds = 1;
13860        newest_exhausted.reviews = vec![review_round(1)];
13861
13862        assert_eq!(
13863            unfinished_run_with(
13864                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
13865                "t",
13866                |_| Ok(newest_exhausted.clone())
13867            ),
13868            None,
13869            "the newest run is exhausted, so nothing here is worth resuming - \
13870             least of all the older, already-superseded run"
13871        );
13872    }
13873
13874    #[test]
13875    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
13876        assert_eq!(
13877            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
13878                Err(anyhow::anyhow!("fixture is absent"))
13879            }),
13880            None
13881        );
13882    }
13883
13884    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
13885        let mut q = ask::Question::new(
13886            run.to_owned(),
13887            "implement".to_owned(),
13888            "impl-A".to_owned(),
13889            "continue?".to_owned(),
13890            String::new(),
13891            vec!["resume で続行する".to_owned(), "other".to_owned()],
13892        );
13893        q.actions.insert("resume で続行する".to_owned(), action);
13894        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
13895            .unwrap();
13896        q
13897    }
13898
13899    fn held_task_with(run: &str) -> Task {
13900        let mut t = task();
13901        t.runs = vec![run.to_owned()];
13902        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
13903        t
13904    }
13905
13906    fn resume_action(run: &str) -> ask::ChoiceAction {
13907        ask::ChoiceAction::Resume { run: run.into() }
13908    }
13909
13910    #[test]
13911    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
13912        let home = crate::run::test_home();
13913        for parked in [false, true] {
13914            let mut t = task();
13915            t.start("A".into());
13916            t.start("B".into());
13917            assert_eq!(t.runs, vec!["A", "B"]);
13918            t.start("A".into());
13919            let mut resumed = run_state(RunStatus::Blocked);
13920            resumed.id = "A".into();
13921            resumed.parked = parked;
13922            resumed.driver_exited = true;
13923            t.hold_machine(Some("resumed run stopped".into()));
13924            let q = action_question("A", resume_action("A"));
13925            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
13926            assert_eq!(
13927                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
13928                    assert_eq!(id, "A");
13929                    Ok(resumed.clone())
13930                }),
13931                ActionDecision::Resume("A".into())
13932            );
13933            assert_eq!(
13934                action_standing(&t, &action_question("B", resume_action("B"))),
13935                ActionStanding::Stale
13936            );
13937            t.release_operator("cli", None);
13938            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
13939                assert_eq!(id, "A");
13940                Ok(resumed.clone())
13941            });
13942            assert_eq!(
13943                choose_starter(None, false, unfinished.as_deref()),
13944                Starter::Resume("A".into())
13945            );
13946            assert_eq!(t.runs, vec!["B", "A"]);
13947        }
13948    }
13949
13950    #[test]
13951    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
13952        let home = crate::run::test_home();
13953        let mut state = crate::land::tests::repair_state(true, true);
13954        state.status = RunStatus::Landing;
13955        state.parked = true;
13956        state.driver_exited = true;
13957        let mut q = ask::Question::new(
13958            state.id.clone(),
13959            land::APPROVAL_NODE.into(),
13960            "land".into(),
13961            "Merge?".into(),
13962            String::new(),
13963            vec![land::APPROVE.into(), land::HOLD.into()],
13964        );
13965        q.id = state.id.clone();
13966        state.land_approval = Some(crate::run::LandApproval {
13967            question: q.id.clone(),
13968            head: "current-head".into(),
13969        });
13970        assert!(land::upgrade_repair_choice(&mut q, &state));
13971        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
13972        let mut task = held_task_with(&state.id);
13973        task.status = TaskStatus::Parked;
13974        assert_eq!(
13975            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13976            ActionDecision::Resume(state.id.clone())
13977        );
13978        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
13979        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
13980        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
13981        assert_eq!(
13982            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
13983            ActionDecision::Resume(state.id.clone()),
13984            "a repair answer newer than the manual hold resumes the existing owner"
13985        );
13986        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
13987        for answered_at in [q.answered_at, None] {
13988            let mut older = q.clone();
13989            older.answered_at = answered_at;
13990            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
13991                panic!("a later manual hold must prevent dispatch")
13992            });
13993            let ActionDecision::Refuse(reason) = refused else {
13994                panic!("expected an actionable refusal, got {refused:?}");
13995            };
13996            assert!(reason.contains("later operator decision"));
13997            assert!(reason.contains(&format!("magi task release {}", task.id)));
13998        }
13999        task.operator_decided_at = None;
14000        let mut superseded = state.clone();
14001        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14002        assert_eq!(
14003            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14004            ActionDecision::Stale
14005        );
14006        for case in 1..4 {
14007            let mut changed = state.clone();
14008            match case {
14009                1 => changed.status = RunStatus::Blocked,
14010                2 => changed.released_to = Some("new-owner".into()),
14011                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14012            }
14013            assert!(matches!(
14014                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14015                ActionDecision::Refuse(_)
14016            ));
14017        }
14018        assert!(matches!(
14019            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14020                "missing owner"
14021            )),
14022            ActionDecision::Refuse(_)
14023        ));
14024        task.runs.push("replacement".into());
14025        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14026        assert_eq!(
14027            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14028                "old owner must not load"
14029            )),
14030            ActionDecision::Stale
14031        );
14032    }
14033
14034    #[test]
14035    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14036        let mut state = crate::land::tests::repair_state(true, true);
14037        state.status = RunStatus::Landing;
14038        state.parked = true;
14039        state.driver_exited = true;
14040        let mut q = ask::Question::new(
14041            state.id.clone(),
14042            land::APPROVAL_NODE.into(),
14043            "land".into(),
14044            "Merge?".into(),
14045            String::new(),
14046            vec![land::APPROVE.into(), land::HOLD.into()],
14047        );
14048        q.id = state.id.clone();
14049        state.land_approval = Some(crate::run::LandApproval {
14050            question: q.id.clone(),
14051            head: "current-head".into(),
14052        });
14053        state.save().unwrap();
14054        land::upgrade_repair_choice(&mut q, &state);
14055        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14056        Questions::open().put(&mut q).unwrap();
14057        let tmp = tempfile::tempdir().unwrap();
14058        let queue = Queue::at(tmp.path().join("queue"));
14059        let mut task = held_task_with(&state.id);
14060        task.status = TaskStatus::Parked;
14061        queue.put(&mut task).unwrap();
14062        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14063        let free = Arc::new(tokio::sync::Semaphore::new(1));
14064        assert!(matches!(
14065            claim_dispatch(&queue, &task, false, &empty, &free),
14066            Err(SkipReason::OrdinaryCapacity)
14067        ));
14068        assert!(matches!(
14069            claim_dispatch(&queue, &task, true, &free, &free),
14070            Err(SkipReason::CoolingDown)
14071        ));
14072        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14073        assert!(claim.permit.is_some());
14074        assert!(matches!(
14075            claim_dispatch(&queue, &task, false, &free, &free),
14076            Err(SkipReason::ClaimUnavailable)
14077        ));
14078        drop(claim);
14079        Questions::open()
14080            .update(&q.id, |q| {
14081                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14082                Ok(())
14083            })
14084            .unwrap();
14085        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14086        assert!(claim.permit.is_none());
14087        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14088    }
14089
14090    #[test]
14091    fn decide_action_resumes_only_the_latest_resumable_run() {
14092        let home = crate::run::test_home();
14093        let t = held_task_with("r1");
14094        let q = action_question("r1", resume_action("r1"));
14095        let load = |s: RunState| move |_: &str| Ok(s);
14096        assert_eq!(
14097            decide_action(
14098                &home,
14099                &t,
14100                &q,
14101                &PHRASES_EN,
14102                load(run_state(RunStatus::Blocked))
14103            ),
14104            ActionDecision::Resume("r1".into())
14105        );
14106        // Not the latest run of the task.
14107        let q_other = action_question("r1", resume_action("r0"));
14108        assert!(matches!(
14109            decide_action(
14110                &home,
14111                &t,
14112                &q_other,
14113                &PHRASES_EN,
14114                load(run_state(RunStatus::Blocked))
14115            ),
14116            ActionDecision::Refuse(_)
14117        ));
14118        // A finished run cannot make progress.
14119        assert!(matches!(
14120            decide_action(
14121                &home,
14122                &t,
14123                &q,
14124                &PHRASES_EN,
14125                load(run_state(RunStatus::Ready))
14126            ),
14127            ActionDecision::Refuse(_)
14128        ));
14129        // A released one either.
14130        let mut released = run_state(RunStatus::Blocked);
14131        released.released_to = Some("elsewhere".into());
14132        assert!(matches!(
14133            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14134            ActionDecision::Refuse(_)
14135        ));
14136        // Unreadable state is a refusal, never a fresh competition.
14137        assert!(matches!(
14138            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14139            ActionDecision::Refuse(_)
14140        ));
14141    }
14142
14143    #[test]
14144    fn decide_action_ignores_a_question_about_an_earlier_run() {
14145        let home = crate::run::test_home();
14146        let mut t = held_task_with("r1");
14147        t.runs.push("r2".to_owned());
14148        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14149        assert_eq!(
14150            decide_action(
14151                &home,
14152                &t,
14153                &action_question("r1", ask::ChoiceAction::Done),
14154                &PHRASES_EN,
14155                never
14156            ),
14157            ActionDecision::Stale
14158        );
14159    }
14160
14161    #[test]
14162    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14163        let home = crate::run::test_home();
14164        let mut t = held_task_with("r1");
14165        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14166        assert_eq!(
14167            decide_action(
14168                &home,
14169                &t,
14170                &action_question("r1", ask::ChoiceAction::Requeue),
14171                &PHRASES_EN,
14172                never
14173            ),
14174            ActionDecision::Requeue
14175        );
14176        let done_q = action_question("r1", ask::ChoiceAction::Done);
14177        assert_eq!(
14178            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14179            ActionDecision::Done
14180        );
14181        t.mark_action_applied(&done_q.id);
14182        assert_eq!(
14183            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14184            ActionDecision::Skip
14185        );
14186
14187        // A plain answer (no action for that label) does nothing.
14188        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14189        plain.actions.clear();
14190        assert_eq!(
14191            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14192            ActionDecision::Skip
14193        );
14194        // A running task is left alone.
14195        let mut running = held_task_with("r1");
14196        running.status = TaskStatus::Running;
14197        assert_eq!(
14198            decide_action(
14199                &home,
14200                &running,
14201                &action_question("r1", ask::ChoiceAction::Done),
14202                &PHRASES_EN,
14203                never
14204            ),
14205            ActionDecision::Skip
14206        );
14207    }
14208
14209    #[test]
14210    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14211        crate::run::pin_test_home();
14212        for legacy in [false, true] {
14213            let dir = tempfile::tempdir().unwrap();
14214            let queue = Queue::at(dir.path().join("queue"));
14215            let questions = Questions::at(dir.path().join("questions"));
14216            let run = "20260101-000000-hold";
14217            let mut task = held_task_with(run);
14218            task.status = TaskStatus::Parked;
14219            let mut q = ask::Question::new(
14220                run.into(),
14221                land::APPROVAL_NODE.into(),
14222                "land".into(),
14223                "Repair?".into(),
14224                String::new(),
14225                vec![land::REPAIR.into()],
14226            );
14227            q.actions.insert(land::REPAIR.into(), resume_action(run));
14228            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14229            // Deterministically order the answer before the actual manual hold.
14230            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14231            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14232            questions.put(&mut q).unwrap();
14233            task.hold_manual(Some("Keep this PR paused".into()));
14234            if legacy {
14235                task.hold_source = None;
14236            }
14237            queue.put(&mut task).unwrap();
14238
14239            apply_task_choice_actions(&queue, &questions, dir.path());
14240            let after = queue.get(&task.id).unwrap();
14241            assert!(after.operator_held());
14242            assert_eq!(after.hold_source, task.hold_source);
14243            assert_eq!(after.operator_decided_at, task.operator_decided_at);
14244            assert_eq!(after.runs, task.runs);
14245            assert_eq!(after.instruction, task.instruction);
14246            assert!(after.resume_override.is_none());
14247            assert!(after.action_applied(&q.id));
14248            let reason = after.hold_reason.as_deref().unwrap();
14249            assert!(reason.starts_with("Keep this PR paused"));
14250            assert!(reason.contains("later operator decision"));
14251            assert!(reason.contains(&format!("magi task release {}", task.id)));
14252
14253            for recovery in [
14254                crate::conduct::Recovery::Review,
14255                crate::conduct::Recovery::Requeue,
14256            ] {
14257                crate::conduct::apply(
14258                    &queue,
14259                    &questions,
14260                    &crate::conduct::Verdict {
14261                        decisions: vec![crate::conduct::Decision {
14262                            id: task.id.clone(),
14263                            recovery: Some(recovery),
14264                            ..Default::default()
14265                        }],
14266                    },
14267                )
14268                .unwrap();
14269            }
14270            // Reconciliation is idempotent, and automatic recovery cannot
14271            // reopen this owner after it observes the rejected repair answer.
14272            apply_task_choice_actions(&queue, &questions, dir.path());
14273            let still_held = queue.get(&task.id).unwrap();
14274            assert!(still_held.operator_held());
14275            assert_eq!(still_held.hold_reason, after.hold_reason);
14276            assert_eq!(still_held.runs, task.runs);
14277            assert!(still_held.review_branch.is_none());
14278            assert!(!still_held.fresh_start);
14279            assert!(queue.next_runnable().is_none());
14280        }
14281    }
14282
14283    #[test]
14284    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
14285        for held in [false, true] {
14286            for retry in [false, true] {
14287                let dir = tempfile::tempdir().unwrap();
14288                let queue = Queue::at(dir.path().join("queue"));
14289                let questions = Questions::at(dir.path().join("questions"));
14290                let home = dir.path().join("home");
14291                let mut t = task();
14292                if held {
14293                    t.hold_machine(Some("driver state unknown".into()));
14294                }
14295                queue.put(&mut t).unwrap();
14296                let verdict = serde_json::from_value(serde_json::json!({
14297                    "decisions": [{
14298                        "id": t.id,
14299                        "question": "Driver state unknown; retry the checks or hold?",
14300                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
14301                        "actions": {
14302                            "daemon: recheck and retry": {"do": "requeue"},
14303                            "daemon: hold the task": {"do": "hold"}
14304                        }
14305                    }]
14306                }))
14307                .unwrap();
14308                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
14309                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14310                let mut q = questions.list().pop().unwrap();
14311                let choice = if retry {
14312                    "daemon: recheck and retry"
14313                } else {
14314                    "daemon: hold the task"
14315                };
14316                assert_eq!(q.actions.len(), 2);
14317                q.answer(ask::Answer::Choice(choice.into())).unwrap();
14318                questions.put(&mut q).unwrap();
14319
14320                // A Web answer does not remove the deputy's fresh lease.
14321                questions.beat(&q.id, ask::WaiterKind::Deputy);
14322                for _ in 0..2 {
14323                    resolve_blockers(&queue, &questions);
14324                    apply_task_choice_actions(&queue, &questions, &home);
14325                    let waiting = queue.get(&t.id).unwrap();
14326                    assert_eq!(waiting.status, TaskStatus::Blocked);
14327                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
14328                    assert!(waiting.answers.is_empty());
14329                    assert!(!waiting.action_applied(&q.id));
14330                    assert!(runnable(&queue).is_empty());
14331                    let free = Arc::new(tokio::sync::Semaphore::new(1));
14332                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
14333                }
14334                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14335
14336                // Releasing the blocker and applying the operation share one save.
14337                resolve_blockers(&queue, &questions);
14338                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
14339                apply_task_choice_actions(&queue, &questions, &home);
14340                let after = queue.get(&t.id).unwrap();
14341                assert_eq!(
14342                    after.status,
14343                    if retry {
14344                        TaskStatus::Queued
14345                    } else {
14346                        TaskStatus::Held
14347                    }
14348                );
14349                assert!(after.action_applied(&q.id));
14350                assert_eq!(after.operator_held(), !retry);
14351                assert_eq!(after.answers.len(), 1);
14352
14353                // A later operator decision must not replay this answer.
14354                let mut changed = after;
14355                if retry {
14356                    changed.hold_manual(Some("later hold".into()));
14357                } else {
14358                    changed.release_operator("test", None);
14359                }
14360                let expected = changed.status;
14361                queue.put(&mut changed).unwrap();
14362                apply_task_choice_actions(&queue, &questions, &home);
14363                assert_eq!(queue.get(&t.id).unwrap().status, expected);
14364            }
14365        }
14366    }
14367
14368    #[test]
14369    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
14370        let dir = tempfile::tempdir().unwrap();
14371        let queue = Queue::at(dir.path().join("queue"));
14372        let questions = Questions::at(dir.path().join("questions"));
14373        let home = dir.path().join("home");
14374        let mut state = run_state(RunStatus::Blocked);
14375        state.id = "20260101-000000-act1".to_owned();
14376        state.save_under(&home).unwrap();
14377
14378        let mut t = held_task_with(&state.id);
14379        queue.put(&mut t).unwrap();
14380        let mut q = action_question(&state.id, resume_action(&state.id));
14381        questions.put(&mut q).unwrap();
14382
14383        apply_task_choice_actions(&queue, &questions, &home);
14384        let after = queue.get(&t.id).unwrap();
14385        assert_eq!(after.status, TaskStatus::Queued);
14386        assert!(!after.fresh_start);
14387        assert!(after.action_applied(&q.id));
14388        let pin = after.resume_override.clone().unwrap();
14389        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
14390        assert!(pin.forced);
14391
14392        // Held again later: the same answer does not release it a second time.
14393        let mut again = queue.get(&t.id).unwrap();
14394        again.hold_machine(Some("later".into()));
14395        queue.put(&mut again).unwrap();
14396        apply_task_choice_actions(&queue, &questions, &home);
14397        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14398    }
14399
14400    #[test]
14401    fn a_delivered_answer_is_still_acted_on_exactly_once() {
14402        let dir = tempfile::tempdir().unwrap();
14403        let queue = Queue::at(dir.path().join("queue"));
14404        let questions = Questions::at(dir.path().join("questions"));
14405        let home = dir.path().join("home");
14406        let mut state = run_state(RunStatus::Blocked);
14407        state.id = "20260101-000000-act2".to_owned();
14408        state.save_under(&home).unwrap();
14409
14410        let mut t = held_task_with(&state.id);
14411        queue.put(&mut t).unwrap();
14412        let mut q = action_question(&state.id, resume_action(&state.id));
14413        q.answer_delivered = true;
14414        questions.put(&mut q).unwrap();
14415
14416        // Delivered, and the agent then died: the task is still held, so the
14417        // chosen action applies.
14418        apply_task_choice_actions(&queue, &questions, &home);
14419        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14420        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
14421
14422        // Held again: the same answer does nothing a second time.
14423        let mut again = queue.get(&t.id).unwrap();
14424        again.hold_machine(Some("later".into()));
14425        queue.put(&mut again).unwrap();
14426        apply_task_choice_actions(&queue, &questions, &home);
14427        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14428    }
14429
14430    #[test]
14431    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
14432        let dir = tempfile::tempdir().unwrap();
14433        let queue = Queue::at(dir.path().join("queue"));
14434        let questions = Questions::at(dir.path().join("questions"));
14435        let home = dir.path().join("home");
14436        let mut state = run_state(RunStatus::Blocked);
14437        state.id = "20260101-000000-act3".to_owned();
14438        state.save_under(&home).unwrap();
14439        let mut t = held_task_with(&state.id);
14440        queue.put(&mut t).unwrap();
14441        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
14442        questions.put(&mut q).unwrap();
14443
14444        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
14445        apply_task_choice_actions(&queue, &questions, &home);
14446        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14447
14448        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
14449        apply_task_choice_actions(&queue, &questions, &home);
14450        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14451    }
14452
14453    #[test]
14454    fn action_standing_tells_the_reasons_apart() {
14455        let mut t = held_task_with("r1");
14456        let q = action_question("r1", ask::ChoiceAction::Requeue);
14457        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14458        let mut plain = q.clone();
14459        plain.actions.clear();
14460        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
14461
14462        // Applied wins over everything, even a running task.
14463        t.mark_action_applied(&q.id);
14464        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
14465
14466        // A newer attempt running: the old question is Stale, not Busy.
14467        let mut t = held_task_with("r1");
14468        t.start("r2".to_owned());
14469        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
14470        // The same question about the latest run just waits.
14471        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
14472        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14473        t.status = TaskStatus::Blocked;
14474        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
14475
14476        // A conductor question is keyed by the task, never stale.
14477        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
14478        c.node = crate::conduct::NODE.to_owned();
14479        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
14480        assert!(!ActionStanding::Busy.daemon_owns());
14481    }
14482
14483    #[test]
14484    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
14485        let dir = tempfile::tempdir().unwrap();
14486        let queue = Queue::at(dir.path().join("queue"));
14487        let questions = Questions::at(dir.path().join("questions"));
14488        let home = dir.path().join("home");
14489        let mut state = run_state(RunStatus::Blocked);
14490        state.id = "20260101-000000-act4".to_owned();
14491        state.save_under(&home).unwrap();
14492        let mut t = held_task_with(&state.id);
14493        t.status = TaskStatus::Running;
14494        queue.put(&mut t).unwrap();
14495        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
14496        q.cwd = Some(dir.path().display().to_string());
14497        questions.put(&mut q).unwrap();
14498
14499        // While the task runs the daemon will not act, so the waiter still
14500        // delivers the word to the dead asker's seat ...
14501        let running = queue.get(&t.id).unwrap();
14502        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
14503        assert!(matches!(
14504            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
14505            crate::waiter::Action::Deliver(_)
14506        ));
14507        // ... and the daemon waits while the task runs, then applies once.
14508        apply_task_choice_actions(&queue, &questions, &home);
14509        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14510        let mut back = queue.get(&t.id).unwrap();
14511        back.hold_machine(Some("later".into()));
14512        queue.put(&mut back).unwrap();
14513        apply_task_choice_actions(&queue, &questions, &home);
14514        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
14515        let mut again = queue.get(&t.id).unwrap();
14516        again.hold_machine(Some("again".into()));
14517        queue.put(&mut again).unwrap();
14518        apply_task_choice_actions(&queue, &questions, &home);
14519        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14520    }
14521}