Skip to main content

magi/
daemon.rs

1//! The unattended scheduler and independently leased task workers.
2//!
3//! The scheduler chooses tasks and execution lanes; a detached worker owns each
4//! queue claim, graph driver and outcome settlement. Replacing the scheduler
5//! reconstructs occupied slots from live worker jobs, without touching their
6//! attempts, passes or paid agent calls. Finite maintenance jobs follow the same
7//! lifetime rule. Explicit parking is durable control, never an upgrade step.
8//!
9//! # A crashed worker is legible
10//!
11//! A task is written `Running`, with its run id, before graph execution. The
12//! worker keeps its claim until the outcome is recorded. Recovery requires both
13//! no live worker reservation and an obtainable task claim, and settles the
14//! saved run through the same policy as a live finish. A scheduler's missing
15//! heartbeat alone is never evidence that a run died.
16//!
17//! # Retries are bounded
18//!
19//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
20//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
21//! exception is a run that ended `Stalled`: the panel collapsed because the
22//! agent CLIs hit their quota, which is a fact about the machine and not about
23//! the task, so it must not spend an attempt. Without that exception a quota
24//! outage would quietly hold the entire backlog, and the operator would come
25//! back to a reset quota and nothing left that the loop is willing to run.
26
27use std::path::{Path, PathBuf};
28use std::sync::Arc;
29use std::sync::atomic::{AtomicBool, Ordering};
30use std::sync::{Mutex, MutexGuard};
31use std::time::Duration;
32
33use anyhow::{Context, Result, bail};
34use jiff::Timestamp;
35use serde::{Deserialize, Serialize};
36use tokio::sync::Notify;
37
38use crate::ask::{self, Questions};
39use crate::clean;
40use crate::conduct::Conductor;
41use crate::config::{BuildCache, Config, MergeMode};
42use crate::graph::Runner;
43use crate::land;
44use crate::notices::{self, Link, Notice};
45use crate::queue::{CompletionActor, CompletionContext, Queue, Task, TaskStatus};
46use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
47use crate::triage;
48
49/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
50pub const SCHEMA: u32 = 1;
51
52/// How often the status file is refreshed. A reader treats a status file older
53/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
54/// that a busy daemon is never mistaken for a dead one.
55pub const HEARTBEAT: Duration = Duration::from_secs(5);
56
57/// How old a heartbeat may be before a reader calls the daemon dead. Six
58/// missed beats: long enough to survive a slow filesystem, short enough that
59/// a crashed daemon is not still reported as running a task.
60///
61/// The single threshold every reader shares — the web UI's `/api/health` and
62/// `magi doctor` both call [`Reading::running`] rather than each comparing
63/// against their own copy of this number, so a crashed daemon cannot look
64/// alive on one screen and dead on another.
65pub const STALE_SECS: i64 = 30;
66
67/// Default queue poll interval.
68pub const POLL: Duration = Duration::from_secs(5);
69
70/// How old a claim has to be before startup sweeps it. Longer than any run
71/// this graph plausibly takes, so a sweep cannot pull a task out from under a
72/// daemon that is merely slow.
73pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
74
75/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
76/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
77///
78/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
79/// poll, by attempting the task's own claim: a dead pid is proof enough for
80/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
81/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
82/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
83/// age instead, since there is nothing else to check (see
84/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
85/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
86/// task `running` — see
87/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
88/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
89/// conductor well before the mechanical six-hour sweep would, and thirty
90/// minutes is comfortably below `STALE_CLAIM` while still being generous
91/// enough that a task merely late to publish its first [`HEARTBEAT`] is
92/// never mistaken for abandoned.
93pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
94
95/// What the loop is working on, for the status file.
96#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
97#[serde(default)]
98pub struct Current {
99    /// Worker reservation that produced this claim; absent on legacy drivers.
100    #[serde(default, skip_serializing_if = "Option::is_none")]
101    pub worker: Option<String>,
102    /// Task id being run.
103    pub task: String,
104    /// Run id the task produced.
105    pub run: String,
106}
107
108/// The daemon's liveness, published to `<home>/daemon.json`.
109///
110/// This is the only interface between the loop and the web UI, which is why it
111/// carries `updated_at` as well as `started_at`: a reader cannot tell a
112/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
113/// can compare the heartbeat against the clock.
114#[derive(Debug, Clone, Serialize, Deserialize)]
115pub struct Status {
116    /// On-disk format version.
117    pub schema: u32,
118    /// Process id, so a human can find or kill the daemon.
119    pub pid: u32,
120    /// When this process started.
121    pub started_at: Timestamp,
122    /// Last heartbeat.
123    pub updated_at: Timestamp,
124    /// True when the queue has nothing runnable.
125    pub idle: bool,
126    /// Every task and run currently in flight. More than one entry means the
127    /// loop is driving more than one run at once — see
128    /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
129    /// nothing is running, so a reader never has to treat "no field" and "an
130    /// empty list" as two different kinds of idle.
131    pub current: Vec<Current>,
132    /// Tasks that reached a terminal status in this process.
133    pub completed: usize,
134    /// Queue polls since start, so a wedged loop shows up as a frozen count.
135    pub polls: u64,
136    /// Last completed candidate scan that started no tasks; absent otherwise.
137    #[serde(default)]
138    pub dispatch_wait: Option<DispatchWait>,
139    /// Per-task skip reasons observed by the latest completed dispatch scan.
140    /// Retained even when another task started in the same scan so skipped
141    /// candidates do not lose their observed blocker.
142    #[serde(default)]
143    pub dispatch_skips: std::collections::BTreeMap<String, String>,
144    /// Effective startup capabilities of the question recovery loops.
145    #[serde(default)]
146    pub question_recovery: Option<crate::question_delivery::Recovery>,
147    /// Independent-worker control protocol supported by this scheduler.
148    #[serde(default)]
149    pub worker_protocol: Option<u32>,
150}
151
152impl Status {
153    /// A fresh, idle status for this process.
154    #[must_use]
155    pub fn new() -> Self {
156        let now = Timestamp::now();
157        Self {
158            schema: SCHEMA,
159            pid: std::process::id(),
160            started_at: now,
161            updated_at: now,
162            idle: true,
163            current: Vec::new(),
164            completed: 0,
165            polls: 0,
166            dispatch_wait: None,
167            dispatch_skips: std::collections::BTreeMap::new(),
168            question_recovery: None,
169            worker_protocol: Some(1),
170        }
171    }
172}
173
174impl Default for Status {
175    fn default() -> Self {
176        Self::new()
177    }
178}
179
180/// How the loop should behave.
181#[derive(Debug, Clone, Serialize, Deserialize)]
182#[serde(default)]
183pub struct Opts {
184    /// Repository used by tasks that name none.
185    pub repo: PathBuf,
186    /// Explicit `magi.toml`, instead of the discovered layer stack.
187    pub config: Option<PathBuf>,
188    /// Queue poll interval.
189    pub poll: Duration,
190    /// Attempts a task gets before it is held for a human.
191    pub max_attempts: usize,
192    /// Drain what is runnable now, then return, instead of waiting for more.
193    pub once: bool,
194    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
195    pub merge: Option<String>,
196    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
197    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
198    /// `None` resolves to [`crate::run::default_worktree_root`] - the
199    /// operator's real `~/wt/<repo>` - the same way a run with no
200    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
201    /// that does not own that directory (a test, an embedding that manages
202    /// worktrees itself) must set this, or every idle tick reclaims worktrees
203    /// out from under whoever actually does.
204    pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208    fn default() -> Self {
209        Self {
210            repo: PathBuf::from("."),
211            config: None,
212            poll: POLL,
213            max_attempts: 2,
214            once: false,
215            merge: None,
216            worktrees_root: None,
217        }
218    }
219}
220
221impl Opts {
222    fn absolute(&self) -> Result<Self> {
223        let mut opts = self.clone();
224        opts.repo = std::path::absolute(&opts.repo)?;
225        opts.config = opts
226            .config
227            .as_deref()
228            .map(std::path::absolute)
229            .transpose()?;
230        opts.worktrees_root = opts
231            .worktrees_root
232            .as_deref()
233            .map(std::path::absolute)
234            .transpose()?;
235        Ok(opts)
236    }
237}
238
239/// How many runs a plain `usize` from config may drive concurrently, floored
240/// at one. A `0` in a config file would otherwise stall the loop entirely -
241/// no runnable task could ever start - which is never what an operator who
242/// wrote `0` meant.
243fn max_concurrent(n: usize) -> usize {
244    n.max(1)
245}
246
247/// Where the status file lives.
248#[must_use]
249pub fn status_path() -> PathBuf {
250    crate::run::home().join("daemon.json")
251}
252
253/// Publish the status file for this process.
254pub fn write_status(status: &Status) -> Result<()> {
255    write_status_to(&status_path(), status)
256}
257
258/// Publish a status to an explicit path.
259///
260/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
261/// on every health poll and must never see a half-written one.
262pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
263    if let Some(parent) = path.parent() {
264        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
265    }
266    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
267    let tmp = path.with_extension("json.tmp");
268    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
269    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
270    Ok(())
271}
272
273/// Delete the status file. Called on the way out so a clean exit reads as
274/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
275pub fn clear_status() {
276    clear_status_at(&status_path());
277}
278
279/// Delete a status file at an explicit path, so the loop's teardown and
280/// [`clear_status`] cannot drift apart: the loop is handed the path it
281/// published to, and a test can watch a temp file disappear.
282fn clear_status_at(path: &Path) {
283    let _ = std::fs::remove_file(path);
284}
285
286/// A cooperative stop, shared with whoever asked the loop to run.
287///
288/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
289/// Ctrl-C listener and the web UI keep others, and every clone points at the
290/// same flag. There is no channel because there is nothing to send — the only
291/// message is "stop", it is idempotent, and a flag cannot be missed by a
292/// receiver that was not listening yet.
293///
294/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
295/// detached task workers keep their own lifetimes and ownership after this
296/// handle's scheduler exits.
297#[derive(Debug, Clone, Default)]
298pub struct Stop {
299    /// Set once, never cleared: a stop is not something an operator takes back
300    /// half way through, and a clearable flag would let a start racing a stop
301    /// resurrect a loop that is already unwinding.
302    stopped: Arc<AtomicBool>,
303    /// Live task workers observed by the scheduler's latest dispatch snapshot.
304    busy: Arc<std::sync::atomic::AtomicUsize>,
305    /// Wakes the idle wait. Without this a stop would not be seen until the
306    /// poll interval elapsed, and an operator tapping stop on a phone would
307    /// watch a button do nothing for five seconds.
308    wake: Arc<Notify>,
309    /// Handed to the run in flight, so a stop can also mean "park at the next
310    /// node boundary" instead of "finish the whole competition first".
311    pause: crate::graph::Pause,
312}
313
314impl Stop {
315    /// A stop nobody has asked for yet.
316    #[must_use]
317    pub fn new() -> Self {
318        Self::default()
319    }
320
321    /// Ask the loop to stop. Idempotent, and safe to call before the loop
322    /// starts: the flag is checked before the first poll.
323    pub fn stop(&self) {
324        self.stopped.store(true, Ordering::SeqCst);
325        // `notify_one` rather than `notify_waiters` because the loop may not be
326        // parked yet: this stores a permit, so a wait that registers a moment
327        // later returns at once instead of sleeping out the whole interval.
328        self.wake.notify_one();
329    }
330
331    /// Has a stop been asked for?
332    #[must_use]
333    pub fn stopped(&self) -> bool {
334        self.stopped.load(Ordering::SeqCst)
335    }
336
337    /// Whether a requested scheduler retirement still has an active snapshot.
338    /// Workers continue independently after the scheduler has retired.
339    #[must_use]
340    pub fn finishing(&self) -> bool {
341        self.stopped() && self.busy_now()
342    }
343
344    /// Ask the loop to stop *and* the run in flight to park at its next node
345    /// boundary.
346    ///
347    /// Unlike plain stop, explicit park asks workers to checkpoint at their
348    /// existing safe boundaries. Binary replacement never needs a park.
349    pub fn park(&self, cause: crate::run::ParkCause) {
350        self.pause.park_for(cause);
351        self.stop();
352    }
353
354    /// Has a park been asked for?
355    #[must_use]
356    pub fn parking(&self) -> bool {
357        self.pause.parked()
358    }
359
360    /// The pause handle to give a runner.
361    #[must_use]
362    pub fn pause(&self) -> crate::graph::Pause {
363        self.pause.clone()
364    }
365
366    /// Whether the scheduler's latest snapshot contains active task workers.
367    #[must_use]
368    pub fn busy_now(&self) -> bool {
369        self.busy.load(Ordering::SeqCst) > 0
370    }
371
372    /// Wait out one poll interval, returning early once a stop is asked for.
373    async fn idle(&self, poll: Duration) {
374        tokio::select! {
375            () = tokio::time::sleep(poll) => {}
376            () = self.wake.notified() => {}
377        }
378    }
379}
380
381/// The daemon's published state, read permissively.
382///
383/// This mirrors [`Status`], but is a separate declaration on purpose: every
384/// field defaults, so a status file from an older or newer magi still yields
385/// a usable reading — one this build has never heard of — instead of a parse
386/// error that hides the daemon entirely.
387#[derive(Debug, Clone, Default, Deserialize)]
388#[serde(default)]
389pub struct Reading {
390    /// Format version the daemon claims.
391    pub schema: u32,
392    /// Daemon process id, for an operator who wants to stop it.
393    pub pid: Option<u32>,
394    /// When that process started.
395    pub started_at: Option<Timestamp>,
396    /// Last heartbeat. Absent means the file is unusable, hence not running.
397    pub updated_at: Option<Timestamp>,
398    /// True when the queue had nothing runnable at the last poll.
399    pub idle: bool,
400    /// What the daemon is working on. Empty means idle; more than one entry
401    /// means more than one run is in flight at once.
402    ///
403    /// `deserialize_with` rather than the plain derive: a daemon started
404    /// before this field became a list is still out there writing the old
405    /// shape — a single `{"task":...,"run":...}` object, or its absence —
406    /// on every heartbeat until it is restarted, and a live process reading
407    /// that file during the rollout must still see it as running rather than
408    /// as absent. A bare type change here would fail the whole struct's
409    /// deserialization on a type mismatch, defeating the permissiveness this
410    /// type exists for.
411    #[serde(deserialize_with = "de_current")]
412    pub current: Vec<Current>,
413    /// Tasks this daemon process has finished.
414    pub completed: u64,
415    /// Queue polls this daemon process has made.
416    pub polls: u64,
417    /// Last no-start scan, retaining unknown reason keys from newer writers.
418    pub dispatch_wait: Option<DispatchWait>,
419    /// Per-task skip reasons observed by the latest completed dispatch scan.
420    #[serde(default)]
421    pub dispatch_skips: std::collections::BTreeMap<String, String>,
422    /// Effective startup capabilities of the question recovery loops.
423    #[serde(default)]
424    pub question_recovery: Option<crate::question_delivery::Recovery>,
425    /// Independent-worker control protocol, absent on legacy embedded loops.
426    pub worker_protocol: Option<u32>,
427}
428
429/// Accept the old single-`Current`-or-absent shape as well as the current
430/// list, so a reader never has to know which build wrote the file.
431fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
432where
433    D: serde::Deserializer<'de>,
434{
435    #[derive(Deserialize)]
436    #[serde(untagged)]
437    enum Shape {
438        Many(Vec<Current>),
439        One(Current),
440    }
441    Ok(
442        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
443            Shape::Many(v) => v,
444            Shape::One(c) => vec![c],
445        }),
446    )
447}
448
449impl Reading {
450    /// Seconds since the last heartbeat, or `None` when there has never been
451    /// one.
452    #[must_use]
453    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
454        self.updated_at
455            .map(|at| (now.as_second() - at.as_second()).max(0))
456    }
457
458    /// Whether the loop counts as running: a heartbeat no older than
459    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
460    /// progress hours after the daemon that owned it was killed.
461    #[must_use]
462    pub fn running(&self, now: Timestamp) -> bool {
463        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
464    }
465}
466
467/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
468/// usable there.
469///
470/// Missing, half-written and unparseable all collapse to `None`, because the
471/// only question a reader asks is whether a daemon is alive, and a file it
472/// cannot read is not evidence that one is.
473#[must_use]
474pub fn read_status(home: &Path) -> Option<Reading> {
475    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
476    serde_json::from_str(&body).ok()
477}
478
479struct ClaimObservation {
480    current: Current,
481    evidence: crate::run::LivenessEvidence,
482}
483
484fn observe_current_work(home: &Path, now: Timestamp) -> Vec<ClaimObservation> {
485    let mut observed: Vec<ClaimObservation> = Vec::new();
486    let reading = read_status(home).filter(|reading| reading.running(now));
487    let daemon_pid = reading.as_ref().and_then(|r| r.pid);
488    let heartbeat_age_secs = reading.as_ref().and_then(|r| r.age_secs(now));
489    if let Some(reading) = reading {
490        for claim in reading.current {
491            let task = (!claim.task.is_empty()).then(|| claim.task.clone());
492            let (worker_pid, worker_status, worker_lookup_error) = match claim.worker.as_deref() {
493                Some(worker_id) => match crate::worker::get(home, worker_id) {
494                    Ok(job)
495                        if matches!(
496                            job.status,
497                            crate::worker::Status::Finished | crate::worker::Status::Failed
498                        ) =>
499                    {
500                        // The worker positively reached a terminal status, so
501                        // this heartbeat snapshot is stale until the next poll.
502                        continue;
503                    }
504                    Ok(job) => (job.pid, Some(job.status), None),
505                    Err(error) => (None, None, Some(format!("{error:#}"))),
506                },
507                None => (None, None, None),
508            };
509            let evidence = crate::run::LivenessEvidence::DaemonHeartbeat {
510                daemon_pid,
511                heartbeat_age_secs,
512                worker_id: claim.worker.clone(),
513                worker_pid,
514                worker_status,
515                worker_lookup_error,
516                task,
517            };
518            observed.push(ClaimObservation {
519                current: claim,
520                evidence,
521            });
522        }
523    }
524    let workers = crate::worker::observe_active_detailed(home).and_then(|jobs| {
525        jobs.into_iter()
526            .filter(|entry| entry.job.kind == "task")
527            .map(|entry| {
528                let job = entry.job;
529                let request: TaskWorker = serde_json::from_value(job.payload).map_err(|_| {
530                    anyhow::anyhow!("invalid task worker payload metadata for worker {}", job.id)
531                })?;
532                let run = Queue::at(request.queue)
533                    .get(&request.task)
534                    .ok()
535                    .and_then(|task| task.execution_runs().last().cloned())
536                    .unwrap_or_default();
537                let task_label = (!request.task.is_empty()).then(|| request.task.clone());
538                let current = Current {
539                    worker: Some(job.id.clone()),
540                    task: request.task,
541                    run,
542                };
543                let evidence = crate::run::LivenessEvidence::WorkerClaim {
544                    worker_id: job.id,
545                    pid: job.pid,
546                    status: job.status,
547                    reason: entry.reason,
548                    task: task_label,
549                    daemon_pid: None,
550                };
551                Ok(ClaimObservation { current, evidence })
552            })
553            .collect::<Result<Vec<_>>>()
554    });
555    match workers {
556        Ok(workers) => {
557            for mut worker in workers {
558                if let Some(existing) = observed.iter_mut().find(|claim| {
559                    claim.current.task == worker.current.task
560                        && claim.current.run == worker.current.run
561                        && claim.current.worker == worker.current.worker
562                }) {
563                    if let crate::run::LivenessEvidence::WorkerClaim {
564                        daemon_pid: ref mut target_daemon_pid,
565                        ..
566                    } = worker.evidence
567                    {
568                        *target_daemon_pid = daemon_pid;
569                    }
570                    existing.evidence = worker.evidence;
571                } else {
572                    observed.push(worker);
573                }
574            }
575        }
576        Err(error) => {
577            // This API gates destructive cleanup. Unknown worker ownership
578            // protects every known task/run instead of pretending it is idle.
579            let detail = format!("{error:#}");
580            tracing::error!("cannot determine active workers: {detail}");
581            let evidence = crate::run::LivenessEvidence::WorkerStoreUnreadable { error: detail };
582            observed.extend(
583                Queue::at(home.join("queue"))
584                    .list()
585                    .into_iter()
586                    .map(|task| ClaimObservation {
587                        current: Current {
588                            worker: None,
589                            task: task.id.clone(),
590                            run: task.execution_runs().last().cloned().unwrap_or_default(),
591                        },
592                        evidence: evidence.clone(),
593                    }),
594            );
595            observed.extend(
596                crate::run::list_ids_in(&home.join("runs"))
597                    .into_iter()
598                    .map(|run| ClaimObservation {
599                        current: Current {
600                            worker: None,
601                            task: String::new(),
602                            run,
603                        },
604                        evidence: evidence.clone(),
605                    }),
606            );
607        }
608    }
609    observed
610}
611
612/// Read-only evidence of runs owned by a live daemon or independent worker.
613///
614/// CLI, sandboxed conversation controls and Web cleanup share this observation.
615/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
616/// Starting reservations and unknown worker state remain protected; observing
617/// them never creates, reconciles or archives files in the worker store.
618/// Callers interested in one identity use [`is_working_on`] or
619/// [`is_working_on_task`].
620#[must_use]
621pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
622    observe_current_work(home, now)
623        .into_iter()
624        .map(|entry| entry.current)
625        .collect()
626}
627
628/// Structured evidence for a live daemon or worker claim on `run`, if any.
629#[must_use]
630pub fn claim_for_run(
631    home: &Path,
632    run: &str,
633    now: Timestamp,
634) -> Option<crate::run::LivenessEvidence> {
635    observe_current_work(home, now)
636        .into_iter()
637        .find(|entry| entry.current.run == run)
638        .map(|entry| entry.evidence)
639}
640
641/// Whether a live daemon is working on this run at this moment.
642#[must_use]
643pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
644    claim_for_run(home, run, now).is_some()
645}
646
647/// Admission may ignore only this process's confirmed worker reservation.
648/// Keep anonymous/legacy daemon claims and every other worker, even for the
649/// same task. The run's execution lease and process identity are checked by
650/// the caller under the owner lock as well.
651pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
652    Ok(other_claim_for_run(home, run, now)?.is_some())
653}
654
655/// Same exclusion rule as [`is_working_on_other`], returning the concrete claim
656/// evidence when another owner (or conservative protection) claims `run`.
657pub(crate) fn other_claim_for_run(
658    home: &Path,
659    run: &str,
660    now: Timestamp,
661) -> Result<Option<crate::run::LivenessEvidence>> {
662    // A helper or test may inherit an identity from a different run store.
663    // That identity grants no exception here; retain all ownership evidence.
664    let same_home = std::env::var_os("MAGI_WORKER_HOME")
665        .is_some_and(|worker_home| Path::new(&worker_home) == home);
666    let caller = if same_home {
667        crate::worker::current_job(home)?
668    } else {
669        None
670    }
671    .filter(|job| {
672        job.kind == "task"
673            && job.status == crate::worker::Status::Running
674            && job.pid == Some(std::process::id())
675    });
676    let caller_id = caller.as_ref().map(|job| job.id.as_str());
677    Ok(observe_current_work(home, now)
678        .into_iter()
679        .find(|entry| {
680            entry.current.run == run
681                && !(caller_id.is_some() && entry.current.worker.as_deref() == caller_id)
682        })
683        .map(|entry| entry.evidence))
684}
685
686#[cfg(test)]
687fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
688    claims
689        .iter()
690        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
691}
692
693/// Whether a live daemon is working on a run whose short id is this one.
694///
695/// For a worktree that has no run record to compare against at all -
696/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
697/// id is not available to hand to [`is_working_on`]. The short id is: a run's
698/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
699/// and it is exactly the gap between the daemon claiming a task and
700/// `RunState::new` saving the first `run.json` that this exists to protect -
701/// a run genuinely in flight but invisible to a scan of `runs/`.
702#[must_use]
703pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
704    current_work(home, now)
705        .iter()
706        .any(|c| crate::run::short_of(&c.run) == short)
707}
708
709/// Whether a live daemon is working on this task at this moment.
710#[must_use]
711pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
712    current_work(home, now).iter().any(|c| c.task == task)
713}
714
715/// Remove claim files whose owner is provably dead, or that have simply
716/// outlived `older_than`, and return the task ids swept.
717///
718/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
719/// destructor, and the orphaned `.lock` file would make its task permanently
720/// unclaimable — the backlog would stop for good at exactly the task that was
721/// in flight when the machine went down.
722///
723/// The pid recorded in the lock is the authority whenever it can be read at
724/// all; age is only a fallback for when it cannot be.
725///
726/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
727///   full stop — dead sweeps the lock immediately, regardless of age; alive
728///   protects it, regardless of age. This is what lets a lock be reclaimed in
729///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
730///   before this daemon even started, next to a `queued` task, no longer has
731///   to sit for six hours before anything notices its owner is gone.
732/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
733///   falls back to `older_than`, since there is nothing else to check.
734///
735/// Age must never override a *positive* liveness confirmation. `sweep`
736/// polls concurrently with independently running task workers. A worker may
737/// legitimately run longer than `older_than`; its live pid must still protect
738/// its claim. Age alone must never turn that claim into a second task attempt,
739/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
740/// to a second attempt — two `Runner`s writing the same `run.json` and the
741/// same worktree at once. `pid_alive` answering "alive" for anything it
742/// cannot determine (a live process, a pid this build cannot check, one
743/// under another account) is exactly what keeps that path from ever
744/// firing on a guess.
745///
746/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
747/// output unreadable must not be license to guess, and the risk of an
748/// unparseable lock outliving a genuinely dead owner is bounded by an order
749/// of magnitude above any plausible run rather than by a positive check.
750///
751/// Runs on every poll, not only at startup — a daemon up for days must keep
752/// noticing a lock some other, now-dead, daemon left behind just as readily
753/// as one it trips over on the way up.
754pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
755    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
756}
757
758/// [`sweep_stale_claims`] with its process-query boundary supplied by the
759/// caller. This keeps the lock policy testable where process listing is
760/// unavailable, while production still uses the platform query above.
761fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
762where
763    F: Fn(u32) -> bool,
764{
765    let this_process = std::process::id();
766    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
767        .into_iter()
768        .flatten()
769        .flatten()
770        .map(|e| e.path())
771        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
772        .filter(|p| {
773            match std::fs::read_to_string(p)
774                .ok()
775                .and_then(|body| body.trim().parse::<u32>().ok())
776            {
777                // This process wrote it and is asking the question right
778                // now, so it is definitionally still alive - settled without
779                // spawning a helper process at all.
780                Some(pid) if pid == this_process => false,
781                Some(pid) => !pid_alive(pid),
782                None => p
783                    .metadata()
784                    .and_then(|m| m.modified())
785                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
786                    .is_ok_and(|age| age >= older_than),
787            }
788        })
789        .filter(|p| std::fs::remove_file(p).is_ok())
790        .filter_map(|p| {
791            p.file_stem()
792                .and_then(|s| s.to_str())
793                .map(std::borrow::ToOwned::to_owned)
794        })
795        .collect();
796    swept.sort_unstable();
797    swept
798}
799
800/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
801/// no live daemon's heartbeat naming it? Deterministic — no model call, and
802/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
803/// shown.
804fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
805    task.status == TaskStatus::Running
806        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
807        && !is_working_on_task(home, &task.id, now)
808}
809
810/// Every task [`is_stalled`] right now — "止まったタスク" in
811/// `crate::conduct`'s vocabulary.
812fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
813    queue
814        .list()
815        .into_iter()
816        .filter(|t| is_stalled(t, home, now))
817        .collect()
818}
819
820/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
821/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
822/// `Failed`-and-so-also-runnable: a task that already attempted and lost
823/// belongs in [`finished_tasks`], where the question is a recovery, not a
824/// dependency.
825fn queued_tasks(queue: &Queue) -> Vec<Task> {
826    queue
827        .list()
828        .into_iter()
829        .filter(|t| t.status == TaskStatus::Queued)
830        .collect()
831}
832
833/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
834/// タスク" in `crate::conduct`'s vocabulary.
835fn finished_tasks(queue: &Queue) -> Vec<Task> {
836    queue
837        .list()
838        .into_iter()
839        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
840        .collect()
841}
842
843/// Deterministically resolve `Task::blocked_by`: a dependency task that
844/// reached `Done`, or a question that was answered, is removed — no model
845/// involved, on every poll. An answered question's content is copied onto
846/// the task ([`Task::record_answer`]) before its id is dropped, so it
847/// reaches the next `crate::conduct` prompt and the next run's instruction
848/// (see [`instruction_for`]) rather than only clearing the block.
849///
850/// A `blocked_by` id that names neither an existing task nor an existing
851/// question - `magi task rm` (or an operator by hand) deleted it while this
852/// task was still waiting - is caught before any of that: it can never
853/// become `Done` or `Answered`, so the ordinary loop below would otherwise
854/// leave the task `blocked` forever with nothing to notice. Such a task is
855/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
856/// which puts it in front of `crate::triage::run_once`'s own walk the next
857/// time it runs - see that module's doc for why the choice is "ask a human",
858/// never "assume the missing dependency was satisfied and unblock anyway".
859fn resolve_blockers(queue: &Queue, questions: &Questions) {
860    for listed in queue.list() {
861        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
862            continue;
863        }
864        let Ok(_claim) = queue.claim(&listed.id) else {
865            continue;
866        };
867        let Ok(mut task) = queue.get(&listed.id) else {
868            continue;
869        };
870        if task.status != TaskStatus::Blocked {
871            continue;
872        }
873        // A dependency deleted on purpose is released, not held - and before
874        // the missing check, so a pass that races the delete (or a claim that
875        // made `Queue::remove` skip this task) settles it quietly.
876        let deleted = queue.apply_deleted_blockers(&mut task, questions);
877        if !deleted.is_empty() {
878            record(queue, &mut task);
879            for id in &deleted {
880                queue.note_dependency_deleted(&task, id);
881            }
882            if task.status != TaskStatus::Blocked {
883                continue;
884            }
885        }
886        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
887        if !missing.is_empty() {
888            let language = language_of(&task, Path::new("."));
889            let mut cause = missing.clone();
890            cause.sort();
891            cause.dedup();
892            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
893            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
894                &task.blocked_by,
895                &missing,
896                &language,
897            )));
898            record(queue, &mut task);
899            continue;
900        }
901        // A conductor question nobody answered in time is retired by the
902        // waiter, and nothing else would ever move the task it blocks.
903        if let Some(q) = task.blocked_by.iter().find_map(|id| {
904            let crate::queue::Dependency::Question(full) =
905                crate::queue::dependency(queue, questions, id)
906            else {
907                return None;
908            };
909            questions.get_for_effects(&full).ok().filter(|q| {
910                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
911            })
912        }) {
913            let language = language_of(&task, Path::new("."));
914            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
915            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
916            record(queue, &mut task);
917            continue;
918        }
919        let mut changed = false;
920        for id in task.blocked_by.clone() {
921            let resolved = crate::queue::dependency(queue, questions, &id);
922            if let crate::queue::Dependency::Task(full) = &resolved {
923                if queue
924                    .get(full)
925                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
926                {
927                    task.unblock(&id);
928                    changed = true;
929                }
930                continue;
931            }
932            if let crate::queue::Dependency::Question(full) = resolved
933                && let Ok(q) = questions.get_for_effects(&full)
934                && q.status == ask::QuestionStatus::Answered
935            {
936                // The action sweep releases conductor blockers atomically
937                // with their selected operation. A fresh deputy lease must
938                // never leave an answered hold temporarily runnable.
939                if q.node == crate::conduct::NODE
940                    && q.chosen_action().is_some()
941                    && !task.action_applied(&q.id)
942                {
943                    continue;
944                }
945                let answer = match &q.answer {
946                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
947                    None => String::new(),
948                };
949                task.record_answer(q.summary.clone(), answer);
950                task.unblock(&id);
951                changed = true;
952            }
953        }
954        if changed {
955            record(queue, &mut task);
956        }
957    }
958}
959
960/// The `hold_reason` of a task whose conductor question went unanswered.
961fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
962    if crate::lang::is_japanese(language) {
963        format!(
964            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
965            q.short(),
966            q.summary
967        )
968    } else {
969        format!(
970            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
971            q.short(),
972            q.summary
973        )
974    }
975}
976
977/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
978/// for several unrelated reasons, and the waiter must not read them alike.
979#[derive(Debug, Clone, Copy, PartialEq, Eq)]
980pub(crate) enum ActionStanding {
981    /// The answer carries no action: the waiter delivers it as before.
982    NoAction,
983    /// The daemon will apply it (not applied, task idle, current attempt).
984    Pending,
985    /// Already applied (`Task::actions_applied`): the daemon has acted, so
986    /// delivering the word to the old seat would run it beside the new work.
987    Applied,
988    /// The question is about an earlier attempt than the task's latest.
989    Stale,
990    /// The task is running / blocked / done: the daemon defers for now.
991    Busy,
992}
993
994impl ActionStanding {
995    /// The daemon has acted or will act: the waiter must not deliver.
996    pub(crate) fn daemon_owns(self) -> bool {
997        matches!(self, Self::Pending | Self::Applied | Self::Stale)
998    }
999}
1000
1001/// Classify `q`'s chosen action against `task`. `Stale` is judged before
1002/// `Busy`: a question about an earlier attempt must be stopped even while a
1003/// newer competition is running.
1004pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
1005    if task.stale_question(q) {
1006        ActionStanding::Stale
1007    } else if q.chosen_action().is_none() {
1008        ActionStanding::NoAction
1009    } else if task.action_applied(&q.id) {
1010        ActionStanding::Applied
1011    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1012        ActionStanding::Stale
1013    } else if matches!(
1014        task.status,
1015        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1016    ) {
1017        ActionStanding::Busy
1018    } else {
1019        ActionStanding::Pending
1020    }
1021}
1022
1023/// What [`decide_action`] concluded about one answered question.
1024#[derive(Debug, Clone, PartialEq, Eq)]
1025enum ActionDecision {
1026    /// Nothing to do now (no action, already applied, or the task is busy).
1027    Skip,
1028    /// Continue the named run instead of competing again.
1029    Resume(String),
1030    /// Requeue as a fresh competition.
1031    Requeue,
1032    /// Hold the task by explicit operator choice.
1033    Hold,
1034    /// Close the task as done.
1035    Done,
1036    /// The question is about an earlier attempt than the task's latest; it
1037    /// is recorded as handled and changes nothing.
1038    Stale,
1039    /// The action cannot be carried out; hold the task and say why. Never
1040    /// falls back to something else, because the operator chose this one.
1041    Refuse(String),
1042}
1043
1044/// Decide what the choice answered on `q` means for `task`. `load` reads a
1045/// run's state, as with [`unfinished_run_with`]. `home` must name that same
1046/// store for driver leases and question checkpoints.
1047///
1048/// `Resume` only fires on the task's *latest* run, and only while that run
1049/// could actually make progress ([`RunStatus::resumable`], not released, review
1050/// budget left); an answer naming anything else is refused rather than
1051/// reinterpreted as a fresh competition.
1052fn decide_action<F>(
1053    home: &Path,
1054    task: &Task,
1055    q: &ask::Question,
1056    p: &Phrases,
1057    load: F,
1058) -> ActionDecision
1059where
1060    F: FnOnce(&str) -> Result<RunState>,
1061{
1062    if task.stale_question(q) {
1063        return ActionDecision::Stale;
1064    }
1065    let Some(action) = q.chosen_action() else {
1066        return ActionDecision::Skip;
1067    };
1068    if task.action_applied(&q.id)
1069        || matches!(
1070            task.status,
1071            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1072        )
1073    {
1074        return ActionDecision::Skip;
1075    }
1076    // A question about an earlier attempt must not act on a newer one. A
1077    // conductor question is keyed by the task id, not a run, so it is exempt.
1078    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1079        return ActionDecision::Stale;
1080    }
1081    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
1082    let stopping = q.node == land::APPROVAL_NODE
1083        && q.resolution()
1084            .as_deref()
1085            .is_some_and(crate::merge_decision::stops);
1086    // An answer is the owner's decision as of when it was given: a manual hold
1087    // placed before it (even after the question was asked) was seen and
1088    // overruled by it, while a hold or release after it supersedes it.
1089    let decision_at = q.answered_at.unwrap_or(q.asked_at);
1090    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
1091        return if repair || stopping {
1092            ActionDecision::Refuse(format!(
1093                "{} 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 {}`",
1094                if repair { "repair" } else { "stop" },
1095                q.id,
1096                q.run,
1097                task.id
1098            ))
1099        } else {
1100            ActionDecision::Stale
1101        };
1102    }
1103    match action {
1104        a if a.maintenance() => ActionDecision::Skip,
1105        ask::ChoiceAction::RecoverBase { .. }
1106        | ask::ChoiceAction::ResumeRun { .. }
1107        | ask::ChoiceAction::ReleaseTask { .. }
1108        | ask::ChoiceAction::RerunChecks { .. }
1109        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
1110        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
1111        ask::ChoiceAction::Hold => ActionDecision::Hold,
1112        ask::ChoiceAction::Done => ActionDecision::Done,
1113        ask::ChoiceAction::Resume { run } => {
1114            if task.execution_runs().last() != Some(run) {
1115                return ActionDecision::Refuse((p.resume_not_latest)(
1116                    q.short(),
1117                    ask::short_id(run),
1118                ));
1119            }
1120            match load(run) {
1121                Ok(s) if stopping => {
1122                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1123                        || !s
1124                            .land_approval
1125                            .as_ref()
1126                            .is_some_and(|binding| binding.question == q.id)
1127                    {
1128                        ActionDecision::Stale
1129                    } else if s.liveness_under(home, false) == Liveness::Live {
1130                        ActionDecision::Skip
1131                    } else if s.status == RunStatus::Landing
1132                        && !s.released()
1133                        && s.retired_to.is_none()
1134                    {
1135                        ActionDecision::Resume(run.clone())
1136                    } else {
1137                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1138                    }
1139                }
1140                Ok(s)
1141                    if q.node == land::APPROVAL_NODE
1142                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1143                {
1144                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1145                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1146                    {
1147                        // A live/manual driver already consumed or superseded
1148                        // this answer. Do not hold its fresh approval wait.
1149                        ActionDecision::Stale
1150                    } else if s.liveness_under(home, false) == Liveness::Live {
1151                        ActionDecision::Skip
1152                    } else if s.status != RunStatus::Landing
1153                        || s.released()
1154                        || s.reviews.is_empty()
1155                        || !implementers_match(task, &s)
1156                        || !s
1157                            .land_approval
1158                            .as_ref()
1159                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1160                    {
1161                        ActionDecision::Refuse(format!(
1162                            "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",
1163                            q.id, run, run
1164                        ))
1165                    } else {
1166                        ActionDecision::Resume(run.clone())
1167                    }
1168                }
1169                Ok(s) => {
1170                    let assessment = s.assess_liveness_under(home, None, Timestamp::now());
1171                    if assessment.verdict == Liveness::Live {
1172                        ActionDecision::Refuse(assessment.live_driver_refusal())
1173                    } else {
1174                        match crate::handover::resume_refusal_under(&s, Some(home)) {
1175                            None => ActionDecision::Resume(run.clone()),
1176                            Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1177                                q.short(),
1178                                ask::short_id(run),
1179                                &reason.diagnostic(&s),
1180                            )),
1181                        }
1182                    }
1183                }
1184                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1185                    q.short(),
1186                    ask::short_id(run),
1187                    &format!("{e:#}"),
1188                )),
1189            }
1190        }
1191    }
1192}
1193
1194/// The fixed prose the daemon writes into [`Task::last_error`] and
1195/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1196/// `triage::Wording` and `land::Words`: only English and Japanese are
1197/// translated, anything else falls back to English.
1198///
1199/// Rendered when the reason is *generated*, so a reason keeps the language it
1200/// was written in if the setting changes later. The notification frame
1201/// (`Task <id> is held:`) is not here and stays English.
1202///
1203/// Deliberately **not** translated, because other code reads them back by
1204/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1205/// and `gate red`. IDs, node names, paths and external error text are embedded
1206/// as they are.
1207struct Phrases {
1208    /// `{}` = status label, then the detail.
1209    graph_stopped: fn(&str, &str) -> String,
1210    quorum_lost: &'static str,
1211    /// Followed by the seats' names.
1212    quota_took_out: &'static str,
1213    /// Followed by the status label.
1214    run_ended: &'static str,
1215    /// Followed by the question's short id.
1216    waiting_for_answer: &'static str,
1217    recovered_running: &'static str,
1218    no_run_to_recover: &'static str,
1219    could_not_start: &'static str,
1220    resume_not_latest: fn(&str, &str) -> String,
1221    resume_cannot_progress: fn(&str, &str, &str) -> String,
1222    resume_unreadable: fn(&str, &str, &str) -> String,
1223    /// A takeover refusal: the operator-facing text. English is the error's own
1224    /// `Display`; a translation keeps the machine detail apart in parentheses.
1225    handover_refused: fn(&crate::handover::Refused) -> String,
1226    /// Appended to a refused handover's hold reason (leading space included).
1227    handover_hint: &'static str,
1228    /// (seats that never answered, review rounds) for the review loop's
1229    /// "refusing to call it clean" stop.
1230    reviewers_never_answered: fn(usize, usize) -> String,
1231}
1232
1233const PHRASES_EN: Phrases = Phrases {
1234    graph_stopped: |status, detail| {
1235        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1236    },
1237    quorum_lost: "the judging panel lost its quorum",
1238    quota_took_out: "; quota took out ",
1239    run_ended: "run ended ",
1240    waiting_for_answer: " - waiting for operator answer to question ",
1241    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1242    no_run_to_recover: "task was `running` with no live daemon and no readable \
1243                        run to recover; held for a human to check what happened",
1244    could_not_start: "could not start the run: ",
1245    resume_not_latest: |q, run| {
1246        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1247    },
1248    resume_cannot_progress: |q, run, reason| {
1249        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1250    },
1251    resume_unreadable: |q, run, e| {
1252        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1253    },
1254    handover_refused: |r| r.to_string(),
1255    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1256    reviewers_never_answered: |missing, rounds| {
1257        format!(
1258            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1259             refusing to call it clean"
1260        )
1261    },
1262};
1263
1264const PHRASES_JA: Phrases = Phrases {
1265    graph_stopped: |status, detail| {
1266        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1267    },
1268    quorum_lost: "審査パネルが定足数を失いました",
1269    quota_took_out: "。クォータで脱落: ",
1270    run_ended: "run 終了: ",
1271    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1272    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1273    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1274                        何が起きたか人が確認するため保留にしました",
1275    could_not_start: "run を開始できませんでした: ",
1276    resume_not_latest: |q, run| {
1277        format!(
1278            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1279        )
1280    },
1281    resume_cannot_progress: |q, run, reason| {
1282        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1283    },
1284    resume_unreadable: |q, run, e| {
1285        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1286    },
1287    handover_refused: |r| {
1288        use crate::handover::Refused;
1289        match r {
1290            Refused::Foreign { branch, path, why } => format!(
1291                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1292                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1293                 から、やり直してください(詳細: {why})"
1294            ),
1295            Refused::Unsafe { branch, path, why } => format!(
1296                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1297                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1298                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1299            ),
1300            Refused::ReleaseFailed { branch, path, run } => format!(
1301                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1302                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1303                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1304            ),
1305        }
1306    },
1307    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1308    reviewers_never_answered: |missing, rounds| {
1309        format!(
1310            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1311             クリーンとは認めません"
1312        )
1313    },
1314};
1315
1316fn phrases(language: &str) -> &'static Phrases {
1317    if crate::lang::is_japanese(language) {
1318        &PHRASES_JA
1319    } else {
1320        &PHRASES_EN
1321    }
1322}
1323
1324/// The language of the repository a task belongs to, read best-effort for the
1325/// paths that have no run (and so no config of their own) to ask. An unreadable
1326/// config is English, not an error: a hold reason must still get written.
1327fn language_of(task: &Task, fallback: &Path) -> String {
1328    crate::lang::of_repo(&repo_for(task, fallback))
1329}
1330
1331/// The task an answered question speaks for: the one whose runs include the
1332/// question's run, or - for a conductor question, filed under the task's own
1333/// id - the task with that id.
1334pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1335    if q.node == crate::conduct::NODE {
1336        return tasks.iter().find(|t| t.id == q.run);
1337    }
1338    tasks.iter().find(|t| t.runs.contains(&q.run))
1339}
1340
1341/// Legacy conductor prose never becomes a maintenance command by inference.
1342/// Replace unsupported open labels under the question lock before dispatch.
1343fn repair_choice_offers(questions: &Questions) {
1344    let ownership = crate::task_chat::InquiryOwnership::default();
1345    for q in questions
1346        .list_for_effects_in(&ownership)
1347        .into_iter()
1348        .filter(|q| {
1349            q.status.open()
1350                && q.node == crate::conduct::NODE
1351                && q.choices
1352                    .iter()
1353                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1354        })
1355    {
1356        let _ = questions.update_in(&q.id, &ownership, |current| {
1357            if current.status.open() {
1358                crate::choice_effect::executable_conductor(current);
1359                if let Some(deputy) = &mut current.deputy {
1360                    deputy.brief = crate::deputy::brief(
1361                        &current.run,
1362                        &current.detail,
1363                        &current.choices,
1364                        &current.actions,
1365                    );
1366                }
1367            }
1368            Ok(())
1369        });
1370    }
1371}
1372
1373/// Apply answered typed choices. Only the daemon calls this in production;
1374/// deputies settle the question and never execute its actions.
1375pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1376    apply_maintenance_choices(queue, questions, home).await;
1377    apply_task_choice_actions(queue, questions, home);
1378}
1379
1380/// Apply bounded maintenance effects independently of question ownership: a
1381/// release watcher need not have a queue task, and a predecessor is another run.
1382async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1383    let ownership = crate::task_chat::InquiryOwnership::default();
1384    for q in questions.list_for_effects_in(&ownership) {
1385        // Read again under the same fence used by explicit settlement.
1386        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1387            continue;
1388        };
1389        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1390            continue;
1391        };
1392        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1393            continue;
1394        };
1395        // Receipt paths use question IDs, whose format is independent of run
1396        // IDs. Apply the question store's filename safety rule to both eras.
1397        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1398            continue;
1399        }
1400        if queue.list().iter().any(|task| {
1401            (task.id == q.run
1402                || task.runs.contains(&q.run)
1403                || q.routed_task.as_deref() == Some(&task.id))
1404                && task.stale_question(&q)
1405        }) {
1406            continue;
1407        }
1408        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1409            let tasks = queue.list();
1410            let owner = crate::task_chat::task_of(&q, &tasks);
1411            if let Some(owner) = owner
1412                && q.routed_task
1413                    .as_deref()
1414                    .is_none_or(|routed| routed == owner)
1415            {
1416                let result = crate::base_recovery_control::recover(
1417                    queue,
1418                    home,
1419                    crate::base_recovery_control::Request {
1420                        run: run.clone(),
1421                        head: stop.head.clone(),
1422                        actor: "decisions".into(),
1423                        request: q.id.clone(),
1424                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1425                        expected_stop: Some((stop.clone(), *episode)),
1426                        evidence_digest: None,
1427                    },
1428                )
1429                .await;
1430                if let Err(error) = result {
1431                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1432                    notices::raise_in(home, Notice::warn(
1433                        &format!("base-recovery:{}", q.id),
1434                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1435                    ).link(Link::Run { id: run.clone() }));
1436                }
1437            }
1438            continue;
1439        }
1440        let dir = home.join("choice-actions");
1441        if std::fs::create_dir_all(&dir).is_err() {
1442            continue;
1443        }
1444        let Ok(lock) = std::fs::OpenOptions::new()
1445            .create(true)
1446            .truncate(false)
1447            .write(true)
1448            .open(dir.join(format!("{}.lock", q.id)))
1449        else {
1450            continue;
1451        };
1452        if crate::pr_head::try_lock_file(&lock).is_err() {
1453            continue;
1454        }
1455        let fresh = !home
1456            .join("choice-actions")
1457            .join(format!("{}.json", q.id))
1458            .exists();
1459        let result = async {
1460            let receipt = dir.join(format!("{}.json", q.id));
1461            if receipt.exists() {
1462                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1463                anyhow::ensure!(
1464                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1465                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1466                );
1467                return Ok::<_, anyhow::Error>(());
1468            }
1469            // Never retry an uncertain external effect. The receipt is written
1470            // before calling gh, exactly like release_watch's rerun record.
1471            let record = |status: &str| -> anyhow::Result<()> {
1472                let tmp = receipt.with_extension("tmp");
1473                std::fs::write(
1474                    &tmp,
1475                    serde_json::to_vec(&serde_json::json!({
1476                        "action": action, "status": status,
1477                    }))?,
1478                )?;
1479                std::fs::rename(tmp, &receipt)?;
1480                Ok(())
1481            };
1482            let applied = async {
1483                match action {
1484                    ask::ChoiceAction::ResumeRun { run } => {
1485                        crate::resume::validate(home, run)?;
1486                        record("started")?;
1487                        let decided = q.answered_at.unwrap_or(q.asked_at);
1488                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1489                            crate::resume::validate_unqueued(home, run)?;
1490                            crate::resume::start(home, run.clone()).await?;
1491                        }
1492                    }
1493                    ask::ChoiceAction::ReleaseTask {
1494                        task,
1495                        held_at,
1496                        reason,
1497                    } => {
1498                        anyhow::ensure!(
1499                            queue.resolve_id(task)? == *task,
1500                            "task action requires an exact task ID"
1501                        );
1502                        let _claim = queue.claim(task)?;
1503                        let mut task = queue.get(task)?;
1504                        if task.action_applied(&q.id) {
1505                            return Ok(());
1506                        }
1507                        // Filing this conductor question temporarily wraps the
1508                        // original hold in a Blocked state. Restore only that
1509                        // exact blocker on the local copy before checking the
1510                        // hold binding; unrelated waits never authorize release.
1511                        if q.node == crate::conduct::NODE
1512                            && q.run == task.id
1513                            && task.status == TaskStatus::Blocked
1514                            && task.blocked_from == Some(TaskStatus::Held)
1515                            && task.blocked_by.as_slice() == [q.id.as_str()]
1516                        {
1517                            task.unblock(&q.id);
1518                        }
1519                        anyhow::ensure!(
1520                            task.status == TaskStatus::Held
1521                                && task.held_at == Some(*held_at)
1522                                && task.hold_reason.as_deref() == reason.as_deref()
1523                                && task
1524                                    .operator_decided_at
1525                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1526                            "task no longer has the hold this question names"
1527                        );
1528                        task.release_operator("choice", Some(&q.id));
1529                        task.mark_action_applied(&q.id);
1530                        queue.put(&mut task)?;
1531                    }
1532                    ask::ChoiceAction::AbandonRun { run } => {
1533                        record("started")?;
1534                        crate::driver::abandon_proven_dead(home, run)?;
1535                    }
1536                    ask::ChoiceAction::RerunChecks {
1537                        repo,
1538                        pr,
1539                        head,
1540                        runs,
1541                    } => {
1542                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1543                            .await?;
1544                    }
1545                    _ => unreachable!(),
1546                }
1547                Ok::<_, anyhow::Error>(())
1548            }
1549            .await;
1550            match applied {
1551                Ok(()) => record("applied"),
1552                Err(e) => {
1553                    record(&format!("refused or failed: {e:#}"))?;
1554                    Err(e)
1555                }
1556            }
1557        }
1558        .await;
1559        // Retire the originating blocker as well as the target operation.
1560        // A foreign resume leaves its issuer held instead of competing beside
1561        // the execution just started. Other successful maintenance lets the
1562        // original task retry its normal, guarded path.
1563        if home
1564            .join("choice-actions")
1565            .join(format!("{}.json", q.id))
1566            .exists()
1567            && let Some(listed) = task_of_question(&queue.list(), &q)
1568            && !listed.action_applied(&q.id)
1569            && let Ok(_claim) = queue.claim(&listed.id)
1570            && let Ok(mut origin) = queue.get(&listed.id)
1571        {
1572            if !origin.operator_held()
1573                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1574                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1575            {
1576                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1577                    origin.hold_machine(Some(format!(
1578                        "Maintenance choice {} settled; inspect its target before releasing this task",
1579                        q.id
1580                    )));
1581                } else {
1582                    origin.unblock(&q.id);
1583                }
1584            }
1585            origin.mark_action_applied(&q.id);
1586            let _ = queue.put(&mut origin);
1587        }
1588        if let Err(e) = result
1589            && fresh
1590        {
1591            notices::raise_in(
1592                home,
1593                Notice::warn(
1594                    &format!("action:{}", q.id),
1595                    format!("Choice action {} was not completed: {e:#}", q.id),
1596                )
1597                .link(if q.run_names_task() {
1598                    Link::Task { id: q.run.clone() }
1599                } else {
1600                    Link::Run { id: q.run.clone() }
1601                }),
1602            );
1603        }
1604    }
1605}
1606
1607/// Rerun the named failed workflow runs of a pull request, each at most once
1608/// per `request` (a question id, or a chat operation identity). The head,
1609/// lifecycle and failed state are re-read from the forge first; `started` is
1610/// called once those checks pass and before the first external call, and the
1611/// ledger entry is written before every `gh` call, so an uncertain result is
1612/// never repeated automatically.
1613pub(crate) async fn rerun_checks_once(
1614    home: &Path,
1615    request: &str,
1616    repo: &Path,
1617    pr: &str,
1618    head: &str,
1619    runs: &[String],
1620    started: impl FnOnce() -> anyhow::Result<()>,
1621) -> anyhow::Result<()> {
1622    use crate::release_watch::{GhForge, ReleaseForge};
1623    anyhow::ensure!(
1624        !runs.is_empty()
1625            && runs.len() <= 20
1626            && runs
1627                .iter()
1628                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1629            && !pr.starts_with('-'),
1630        "invalid rerun targets"
1631    );
1632    let snap = GhForge.snapshot(repo, pr).await?;
1633    anyhow::ensure!(
1634        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1635        "pull request head or lifecycle changed"
1636    );
1637    anyhow::ensure!(
1638        runs.iter().all(|r| snap
1639            .checks
1640            .iter()
1641            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1642        "named workflow is no longer failed on this pull request"
1643    );
1644    started()?;
1645    let dir = home.join("choice-actions");
1646    std::fs::create_dir_all(&dir)?;
1647    let rerun_lock = std::fs::OpenOptions::new()
1648        .create(true)
1649        .truncate(false)
1650        .write(true)
1651        .open(dir.join("reruns.lock"))?;
1652    crate::pr_head::try_lock_file(&rerun_lock)?;
1653    let ledger = dir.join("reruns.json");
1654    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1655        serde_json::from_slice(&std::fs::read(&ledger)?)?
1656    } else {
1657        Default::default()
1658    };
1659    for run in runs {
1660        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1661        if !recorded.insert(key) {
1662            continue;
1663        }
1664        let tmp = ledger.with_extension("tmp");
1665        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1666        std::fs::rename(tmp, &ledger)?;
1667        GhForge.rerun(repo, run).await?;
1668    }
1669    Ok(())
1670}
1671
1672/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1673///
1674/// Runs on every poll before the conductor looks at the queue. The task is
1675/// re-read under its claim, so a task somebody completed or held by hand in
1676/// the meantime is judged on what it is now. `Resume` releases the task and
1677/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1678/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1679/// ordinary `unfinished_run` logic resumes that same run.
1680pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1681    let tasks = queue.list();
1682    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1683    for q in questions.list_for_effects_in(&ownership) {
1684        // Read again under the same fence used by explicit settlement.
1685        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1686            continue;
1687        };
1688        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1689            continue;
1690        };
1691        // Dismissal is committed by the question writer, never a resume.
1692        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1693            continue;
1694        }
1695        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1696            continue;
1697        }
1698        let Some(listed) = task_of_question(&tasks, &q) else {
1699            if q.node == land::APPROVAL_NODE
1700                && q.resolution().as_deref().is_some_and(|choice| {
1701                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1702                })
1703            {
1704                notices::raise_in(
1705                    home,
1706                    Notice::warn(
1707                        &format!("repair-owner:{}", q.id),
1708                        format!(
1709                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1710                            q.run, q.run
1711                        ),
1712                    ).link(Link::Run { id: q.run.clone() }),
1713                );
1714            }
1715            continue;
1716        };
1717        if listed.action_applied(&q.id) {
1718            continue;
1719        }
1720        let Ok(_claim) = queue.claim(&listed.id) else {
1721            continue;
1722        };
1723        let Ok(mut task) = queue.get(&listed.id) else {
1724            continue;
1725        };
1726        // Work only on this local copy until the action can be committed.
1727        // In particular, a fresh lease below leaves the persisted task blocked.
1728        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1729            let blockers: Vec<_> = task
1730                .blocked_by
1731                .iter()
1732                .filter(|id| {
1733                    crate::queue::dependency(queue, questions, id)
1734                        == crate::queue::Dependency::Question(q.id.clone())
1735                })
1736                .cloned()
1737                .collect();
1738            if !blockers.is_empty() {
1739                for id in blockers {
1740                    task.unblock(&id);
1741                }
1742                let answer = match &q.answer {
1743                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1744                    None => String::new(),
1745                };
1746                task.record_answer(q.summary.clone(), answer);
1747            }
1748        }
1749        let language = language_of(&task, Path::new("."));
1750        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1751            RunState::load_under(id, home)
1752        });
1753        let completion = if matches!(decision, ActionDecision::Done) {
1754            match crate::task_completion::prepare_close(
1755                &task,
1756                home,
1757                CompletionActor::DaemonSettle,
1758                Some(format!(
1759                    "Question {}: {} — {}",
1760                    q.id,
1761                    q.summary,
1762                    q.resolution().unwrap_or_default()
1763                )),
1764                false,
1765            ) {
1766                Ok(context) => Some(context),
1767                Err(error) => {
1768                    decision = ActionDecision::Refuse(error.to_string());
1769                    None
1770                }
1771            }
1772        } else {
1773            None
1774        };
1775        let ran = matches!(
1776            decision,
1777            ActionDecision::Resume(_)
1778                | ActionDecision::Requeue
1779                | ActionDecision::Hold
1780                | ActionDecision::Done
1781        );
1782        if ran && asker_may_still_read(questions, &q, home) {
1783            // The asking process or its seat can still take the word; act
1784            // once it has gone quiet. Bound on the remaining window: the
1785            // check is not atomic with the write below, so an asker that
1786            // takes the word in between (at most one poll, never more than
1787            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1788            // and `Task::actions_applied` under the claim keeps the action to
1789            // one application. The waiter does not deliver an answer that
1790            // carries an action (`waiter::decide_owned`), so it cannot race.
1791            continue;
1792        }
1793        let done = matches!(decision, ActionDecision::Done);
1794        // Resume owes an execution pass; only these task-local effects finish
1795        // in this write. Stale/refused actions never acquire an effect receipt.
1796        let completed = matches!(
1797            decision,
1798            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1799        );
1800        match decision {
1801            ActionDecision::Skip => continue,
1802            ActionDecision::Resume(run) => {
1803                task.release_operator("choice", Some(&q.id));
1804                task.resume_override = Some(crate::queue::OperatorResume {
1805                    question_id: q.id.clone(),
1806                    at: Timestamp::now(),
1807                    conductor_rehold: None,
1808                    forced: true,
1809                    pinned_run: Some(run),
1810                });
1811            }
1812            ActionDecision::Stale => {}
1813            ActionDecision::Requeue => {
1814                task.release_operator("choice-requeue", Some(&q.id));
1815                task.requeue();
1816            }
1817            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1818            ActionDecision::Done => {
1819                task.succeed(completion.expect("done passed completion admission"));
1820            }
1821            ActionDecision::Refuse(why) => {
1822                let _ =
1823                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1824                if task.operator_held() {
1825                    // A rejected answer does not release the operator's hold
1826                    // or reclassify it as recoverable by the conductor.
1827                    task.hold_reason = Some(match task.hold_reason.take() {
1828                        Some(reason) => format!("{reason}\n\n{why}"),
1829                        None => why,
1830                    });
1831                } else {
1832                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1833                    task.hold_machine(Some(why));
1834                }
1835                notices::raise(
1836                    Notice::warn(
1837                        &format!("action:{}", q.id),
1838                        "An answered task action could not be applied; the task stays held.",
1839                    )
1840                    .link(Link::Task {
1841                        id: task.id.clone(),
1842                    }),
1843                );
1844            }
1845        }
1846        task.mark_action_applied(&q.id);
1847        if completed {
1848            task.decision_effects.insert(
1849                q.id.clone(),
1850                format!("decision: {}", q.resolution().expect("answered action")),
1851            );
1852        }
1853        // The applied id travels with the transition, so a failed save loses
1854        // neither and the answer is acted on at the next poll.
1855        record(queue, &mut task);
1856        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1857            supersede_prior_runs(&task, home);
1858        }
1859        // Delivery is only a note of who has read the answer; the task's own
1860        // mark above is the authority. Best effort.
1861        let _ = questions.update_in(&q.id, &ownership, |r| {
1862            r.answer_delivered = true;
1863            Ok(())
1864        });
1865    }
1866}
1867
1868/// Whether something may still read the answer to `q`: a fresh lease, or the
1869/// asking seat still listed as active in its run (its CLI can outlive the
1870/// `magi ask` that was killed).
1871fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1872    let now = Timestamp::now();
1873    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1874        return true;
1875    }
1876    q.node != crate::conduct::NODE
1877        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1878            s.seats_active()
1879                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1880        })
1881}
1882
1883/// Retire an unanswered conductor question after its task no longer refers to
1884/// it. Conductor questions use the task id in `Question::run`, so run-based
1885/// cleanup cannot observe a manual release or completion.
1886///
1887/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1888/// own question also carries a `run`, and a run id that happens to collide
1889/// with some task's id is not this loop's business — only a conductor
1890/// question actually uses the task id that way. One `Questions::list()` scan
1891/// is taken up front and matched against the in-memory task set, rather than
1892/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1893fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1894    let tasks = queue.list();
1895    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1896    let by_id: std::collections::BTreeMap<&str, &Task> =
1897        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1898    let referenced: Vec<&str> = tasks
1899        .iter()
1900        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1901        .collect();
1902
1903    for mut question in questions.list_for_effects_in(&ownership) {
1904        if !question.status.open()
1905            || question.node != crate::conduct::NODE
1906            || questions.held_reply_in(&question.id, &ownership)
1907        {
1908            continue;
1909        }
1910        // Keep questions a task still names, including when the reference
1911        // moved to a dependent task.
1912        // Preserve even ambiguous references: retiring a possibly referenced
1913        // question is unsafe until the operator disambiguates it.
1914        if referenced
1915            .iter()
1916            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1917        {
1918            continue;
1919        }
1920        let Some(task) = by_id.get(question.run.as_str()) else {
1921            continue;
1922        };
1923        question.abandon(format!(
1924            "task {} no longer waits for this answer",
1925            task.short()
1926        ));
1927        if let Err(e) = questions.put_in(&mut question, &ownership) {
1928            tracing::warn!(
1929                "could not retire question {} for task {}: {e:#}",
1930                question.short(),
1931                task.short()
1932            );
1933        }
1934    }
1935}
1936
1937/// What a finished run tells the queue about the task it came from.
1938///
1939/// A struct rather than a fourth and fifth boolean argument: the two flags
1940/// answer different questions about the same run, and a call site passing
1941/// `(…, true, false)` is one transposition away from refunding attempts
1942/// forever.
1943#[derive(Debug, Clone, Copy)]
1944pub struct Verdict {
1945    /// Where the graph stopped.
1946    pub status: RunStatus,
1947    /// The run opened a pull request.
1948    pub left_pr: bool,
1949    /// At least one seat was lost to a rate limit.
1950    pub quota_hit: bool,
1951    /// The run parked at a node boundary because it was asked to.
1952    pub parked: bool,
1953    /// The run never produced a single candidate a judge could look at.
1954    ///
1955    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1956    /// still have another candidate worth judging, in which case the loss was
1957    /// not the reason nothing came of the run. This is `true` only when the
1958    /// implement wave ended with nothing viable at all.
1959    pub no_viable_candidates: bool,
1960}
1961
1962/// Record a finished run against the task it came from.
1963///
1964/// Kept pure and separate from the loop because this mapping *is* the retry
1965/// policy, and a policy that can only be exercised by spawning a graph is a
1966/// policy nobody checks. The table:
1967///
1968/// | run status                           | task becomes        | attempt spent |
1969/// |---------------------------------------|---------------------|---------------|
1970/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1971/// | `Merged`, `Ready`                      | `Done`               | yes          |
1972/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1973/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1974/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1975/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1976/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1977/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1978/// | `Blocked` with a PR                    | `Held`               | yes          |
1979/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1980/// | `VerifiedNoop`                          | `Held`               | yes          |
1981/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1982///
1983/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1984/// deliberately: every candidate agreeing there is nothing to write is not a
1985/// machine fact about a rate limit, it is an unverified claim about the
1986/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1987/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1988/// claim could be wrong (a misread instruction, a stale check), and closing
1989/// the task automatically on an implementer's say-so would be the exact
1990/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1991/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1992/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1993/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1994/// claim regardless of whether the one already-spent attempt is refunded, and
1995/// [`Task::release`] resets the count to zero anyway the moment a human looks
1996/// at the evidence and lets it run again.
1997///
1998/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1999/// twice, together. A quorum lost to rate limits is a property of the machine
2000/// and not of the task, so the attempt is refunded and a reset quota picks
2001/// the work up where it stopped — and that is just as true when every
2002/// implement seat lost the same race and `after_implement` bails with nothing
2003/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
2004/// machine fact. The `no_viable_candidates` guard is what keeps that row
2005/// narrow: a `Failed` run that produced a real candidate which then lost for
2006/// some other reason still spends the attempt, exactly like the quorum lost
2007/// to judges that answered with the wrong shape is ordinary flakiness, and
2008/// refunding *that* takes the bound off the retry loop entirely: run e633
2009/// stalled with `quota: []` after two judges wrote unusable JSON, was
2010/// refunded, and the next attempt paid for a fresh hour-long implement wave
2011/// before it could fail the same way. `max_attempts` exists precisely so
2012/// that cannot repeat forever.
2013///
2014/// A non-terminal status means `execute` returned while the graph was still
2015/// mid-flight, which is a bug rather than a verdict; it is treated as a
2016/// failure so that a task cannot loop on it either.
2017///
2018/// `left_pr` splits the `Blocked` row, and it is the difference between a run
2019/// that failed and a run that finished into a gate. See [`Task::handed_off`].
2020pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
2021    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
2022}
2023
2024/// [`settle`], with the daemon's own fixed prose in `p`'s language.
2025fn settle_in(
2026    task: &mut Task,
2027    verdict: Verdict,
2028    detail: &str,
2029    max_attempts: usize,
2030    p: &Phrases,
2031    state: Option<&RunState>,
2032) {
2033    // A parked run is the operator's own doing, and its work is intact on
2034    // disk. The task goes back in line with its attempt refunded so the next
2035    // loop resumes the same run - which `one_task` prefers over competing
2036    // again - and so that swapping the binary a few times cannot exhaust a
2037    // budget meant for agents that actually misbehaved.
2038    if verdict.parked {
2039        task.park(detail);
2040        return;
2041    }
2042    let completion = |task: &Task| match state {
2043        Some(state) => CompletionContext::from_run(
2044            CompletionActor::DaemonSettle,
2045            Some(detail.to_owned()),
2046            task,
2047            state,
2048        ),
2049        None => CompletionContext::new(
2050            CompletionActor::DaemonSettle,
2051            Some(detail.to_owned()),
2052            &crate::run::home(),
2053            task,
2054        ),
2055    };
2056    match verdict.status {
2057        RunStatus::Merged | RunStatus::Ready
2058            if task.pr_recovery.as_ref().is_some_and(|s| {
2059                s.disposition != Some(crate::pr_recovery::Disposition::Review)
2060            }) =>
2061        {
2062            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()));
2063        }
2064        RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
2065        RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
2066        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
2067        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
2068            task.stall(detail)
2069        }
2070        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
2071        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
2072        RunStatus::Blocked => task.fail(detail, max_attempts),
2073        RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
2074            task.handed_off(detail)
2075        }
2076        RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
2077        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
2078    }
2079}
2080
2081/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
2082/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
2083/// itself has actually finished *and* its own last attempt is provably why:
2084/// this loads that run and requires `Merged`/`Ready` before touching
2085/// anything earlier in `runs`, since `Task::succeed` can also be called
2086/// directly on a task whose last attempt never landed at all.
2087///
2088/// Called right after whatever call set `task.status` to
2089/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
2090/// `reclaim`'s, but also every other place a task can be closed by hand
2091/// without the loop ever settling it itself: `magi task done`
2092/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
2093/// (`web::queue_done`). Closing a task by hand — after confirming a manual
2094/// GitHub merge, say, exactly the workflow this repository's own
2095/// "Landing a run's winner by hand" documents — is just as much "this task's
2096/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
2097/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
2098/// forever, which is the exact backlog this status exists to clear. `pub`
2099/// for those two out-of-module callers; everything else about this stays
2100/// internal bookkeeping.
2101///
2102/// A run something is still actually driving is left alone: a
2103/// task cannot be `Done` while one of its *own* attempts is still in flight,
2104/// so a live one at this point can only be an unrelated process — a manual
2105/// `--resume` of this old, now-moot run — and rewriting under it would just
2106/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
2107/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
2108/// pair `run_report`/`run_detail` use for the same question elsewhere:
2109/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
2110/// --resume` invoked by hand outside it, which `liveness` also checks via
2111/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
2112/// (already terminal in some other way, or itself mid-run) is left untouched
2113/// too.
2114///
2115/// Best-effort, like the rest of this module's bookkeeping: a load or save
2116/// failure here is a `tracing::warn`, not a failed settle, and the next time
2117/// this same task's completion is recorded — or a daemon restart replays
2118/// `reclaim_orphaned_running` — is another chance to catch up. There is no
2119/// separate reconciliation pass; if that gap ever matters in practice, one
2120/// can be added then.
2121///
2122/// `home` is a parameter, not the process-global [`crate::run::home`], for
2123/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2124/// calls this with `ui.home`, which is `crate::run::home()` in a real
2125/// process but a fixture's own directory under test — falling through to
2126/// the global there would read and write through whichever home some other
2127/// test in the same binary happened to pin into that `OnceLock` first, not
2128/// the run this call actually means.
2129pub fn supersede_prior_runs(task: &Task, home: &Path) {
2130    if task
2131        .completion_history
2132        .last()
2133        .is_some_and(|event| event.discard)
2134    {
2135        return;
2136    }
2137    let now = Timestamp::now();
2138    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2139    // right behind a `Merged`/`Ready` verdict) from one set directly by
2140    // `magi task done`/its web equivalent/the conductor on a task whose last
2141    // recorded attempt never actually landed - that requires reading the
2142    // run itself, which is exactly what this does before trusting anything
2143    // in `runs` is safe to relabel.
2144    let last_run_succeeded = task
2145        .runs
2146        .last()
2147        .and_then(|id| RunState::load_under(id, home).ok())
2148        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2149    for id in task.superseded_attempts(last_run_succeeded) {
2150        let mut state = match RunState::load_under(id, home) {
2151            Ok(s) => s,
2152            Err(e) => {
2153                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2154                continue;
2155            }
2156        };
2157        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2158            continue;
2159        }
2160        let daemon_claims = is_working_on(home, id, now);
2161        if state.liveness(daemon_claims) == Liveness::Live {
2162            continue;
2163        }
2164        state.status = RunStatus::Superseded;
2165        if let Err(e) = state.save_under(home) {
2166            tracing::warn!("could not mark run {id} superseded: {e:#}");
2167        }
2168    }
2169}
2170
2171/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2172/// finish the moment it was called, because one of its earlier attempts was
2173/// still live then - a `magi run --resume` invoked by hand on an old run,
2174/// most likely.
2175///
2176/// That skip is correct at the time (rewriting under a run something is
2177/// still actively saving would just be undone), but recording a completion
2178/// does not schedule another settlement, so without this nothing would look at it
2179/// again: if that manual process later ends anywhere other than
2180/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2181/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2182/// backlog this status exists to clear. Called on the same idle-only
2183/// cadence as [`janitor`], next to it rather than folded into it: this
2184/// walks `queue` and `janitor` never otherwise needs one.
2185///
2186/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2187/// more than one attempt, every pass: each call is a handful of local file
2188/// reads bounded by that task's own attempt count, the same order of cost
2189/// [`clean::fold_due`] already pays scanning every run on disk on the same
2190/// cadence, and a task already fully resolved costs one failed liveness
2191/// check turned no-op the moment its lingering attempt is no longer live.
2192fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2193    for task in queue.list() {
2194        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2195            continue;
2196        }
2197        supersede_prior_runs(&task, home);
2198    }
2199}
2200
2201/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2202/// task ends up held.
2203///
2204/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2205/// dead daemon never got back to) share this, so the two cannot drift into
2206/// disagreeing about which held tasks get a diagnostic.
2207fn settle_and_diagnose(
2208    task: &mut Task,
2209    verdict: Verdict,
2210    detail: &str,
2211    max_attempts: usize,
2212    state: &RunState,
2213) {
2214    let mut verdict = verdict;
2215    let mut detail = detail;
2216    if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2217        // Never allow an inconsistent or unsupported `VerifiedNoop` run state
2218        // to bypass settlement into a no-change handoff, and never rewrite the
2219        // historical run record on disk: settle the task as an ordinary failure.
2220        verdict.status = RunStatus::Failed;
2221        verdict.quota_hit = false;
2222        detail = "no-change result lacks verified evidence";
2223    }
2224    let p = phrases(&state.config.graph.language);
2225    // Shared by normal completion and crash recovery, under the task claim.
2226    // No new attempt can own the task until the old driver has exited.
2227    if let Some(d) = &state.merge_decision {
2228        use crate::merge_decision as md;
2229        if task
2230            .execution_runs()
2231            .last()
2232            .is_some_and(|id| id != &state.id)
2233        {
2234            return;
2235        }
2236        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2237            task.succeed(CompletionContext::from_run(
2238                CompletionActor::DaemonSettle,
2239                Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2240                task,
2241                state,
2242            ));
2243        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2244            if state.liveness(false) != Liveness::Dead {
2245                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2246                return;
2247            }
2248            let replacement = md::Replacement {
2249                question: d.question.clone(),
2250                run: state.id.clone(),
2251                pr: d.target.pr.clone(),
2252                agent: agent.to_owned(),
2253                context: format!(
2254                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2255                    d.target.pr,
2256                    state.id,
2257                    serde_json::to_string(&state.reviews).unwrap_or_default()
2258                ),
2259            };
2260            task.requeue();
2261            task.pr_recovery = None;
2262            task.review_of = None;
2263            task.replacement = Some(replacement);
2264        } else {
2265            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2266                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2267            } 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())) }));
2268        }
2269        task.mark_action_applied(&d.question);
2270        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2271            task.decision_effects
2272                .insert(d.question.clone(), format!("decision: {}", d.choice));
2273        }
2274        if let Some(pass) = state.passes.last() {
2275            task.record_pass_at(
2276                &state.id,
2277                pass.index,
2278                Some(pass.started_at),
2279                task.attempts,
2280                None,
2281            );
2282        }
2283        return;
2284    }
2285    if let Some(replacement) = &task.replacement
2286        && !state.parked
2287        && state.resource_block.is_none()
2288        && (state.viable().is_empty()
2289            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2290    {
2291        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)));
2292        return;
2293    }
2294    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2295        let mut agents: Vec<_> = state
2296            .quota
2297            .iter()
2298            .filter(|q| {
2299                q.cause == crate::agent::QuotaCause::Authentication
2300                    && state
2301                        .passes
2302                        .last()
2303                        .is_none_or(|pass| q.at >= pass.started_at)
2304            })
2305            .map(|q| q.agent.as_str())
2306            .collect();
2307        agents.sort_unstable();
2308        agents.dedup();
2309        if !agents.is_empty() {
2310            task.stall(detail);
2311            task.notice_cause("agent-authentication", None, None);
2312            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2313            return;
2314        }
2315    }
2316    let attempts_before = task.attempts;
2317    // A run that stopped because a shared resource stayed busy was never a
2318    // failure of the task or of an agent. Earlier nodes may have run; only
2319    // the blocked operation lacks a result. The attempt is
2320    // refunded and the task is held by the machine, under a reason `triage`
2321    // can re-check, so the same run resumes with the same agents once the
2322    // resource is free. A park request still wins (it is the operator's).
2323    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2324        let disk_checked_at = task.disk_checked_at;
2325        task.notice_cause(
2326            &format!("resource:{}:{}", block.kind, block.node),
2327            None,
2328            None,
2329        );
2330        task.last_error = Some(detail.to_owned());
2331        task.diagnostic = None;
2332        task.attempts = task.attempts.saturating_sub(1);
2333        if block.kind == "agent authentication" {
2334            task.hold_machine(Some(format!(
2335                "[authentication] {}; no attempt was spent",
2336                block.detail
2337            )));
2338        } else if block.kind == "agent usage limit" {
2339            // Usage limits keep the existing cooldown-and-resume policy.
2340            if let Some(agent) = &state.config.graph.selected_implementer {
2341                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.")));
2342            } else {
2343                task.status = TaskStatus::Failed;
2344                task.last_error = Some(block.detail.clone());
2345            }
2346        } else if block.kind == "disk pressure" {
2347            task.hold_machine(Some(format!(
2348                "{}{}",
2349                crate::disk::RUNNING_PRESSURE,
2350                block.detail
2351            )));
2352        } else {
2353            task.hold_machine(Some(format!(
2354                "{}{}; no attempt was spent; resume to retry the affected operation",
2355                crate::cache::RESOURCE_HOLD,
2356                block.description()
2357            )));
2358        }
2359        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2360            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2361        {
2362            task.mark_disk_capacity();
2363            task.disk_checked_at = disk_checked_at;
2364        }
2365        if let Some(pass) = state.passes.last() {
2366            task.record_pass_at(
2367                &state.id,
2368                pass.index,
2369                Some(pass.started_at),
2370                attempts_before,
2371                None,
2372            );
2373        }
2374        return;
2375    }
2376    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2377        state.parked
2378            && state.status == RunStatus::Landing
2379            && state
2380                .pr_pushed_head
2381                .as_ref()
2382                .is_none_or(|h| h == &hold.head)
2383            && task.execution_runs().last() == Some(&state.id)
2384    }) {
2385        // Settlement and crash recovery share this idempotency key. A later
2386        // explicit resume is a new pass and may refund its own attempt once.
2387        let pass = state.passes.last().map_or(0, |p| p.index);
2388        if !task
2389            .passes
2390            .iter()
2391            .any(|p| p.run == state.id && p.pass_index == pass)
2392        {
2393            task.attempts = task.attempts.saturating_sub(1);
2394        }
2395        task.hold_machine(Some(format!(
2396            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2397            hold.question
2398        )));
2399        task.last_error = Some(detail.to_owned());
2400        task.diagnostic = None;
2401        task.record_pass_at(
2402            &state.id,
2403            pass,
2404            state.passes.last().map(|p| p.started_at),
2405            attempts_before,
2406            Some(crate::run::ParkCause::Question),
2407        );
2408        return;
2409    }
2410    let unresolved = task.hold_notice_cause.clone();
2411    let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2412        .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2413    let mut reconsumed_head_e2e = false;
2414    if state.base_sync_blocked() {
2415        // No automatic retry may turn a retained sync stop into a new competition.
2416        task.hold_machine(Some(detail.to_owned()));
2417        task.last_error = Some(detail.to_owned());
2418    } else if state.land_sync_exhausted() {
2419        task.hold_machine(Some(format!("{detail} {}", state.land_sync_next_action())));
2420        task.last_error = Some(detail.to_owned());
2421    } else if !verdict.parked
2422        && task
2423            .pr_recovery
2424            .as_ref()
2425            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2426        && matches!(
2427            verdict.status,
2428            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2429        )
2430    {
2431        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2432            task.succeed(CompletionContext::from_run(
2433                CompletionActor::DaemonSettle,
2434                Some(detail.to_owned()),
2435                task,
2436                state,
2437            ));
2438        } else {
2439            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()));
2440        }
2441    } else if !verdict.parked
2442        && task.pr_recovery.is_some()
2443        && matches!(
2444            verdict.status,
2445            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2446        )
2447        && !verdict.quota_hit
2448    {
2449        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.")));
2450    } else if let Some(stop) = head_e2e_stop.clone() {
2451        // Conclusive current-head E2E red settles directly to one actionable
2452        // machine hold instead of cycling through runnable `Failed` passes.
2453        // Refund only when this pass provably reconsumed an earlier stop with
2454        // no new verification events, idempotently across reclaim/re-settle.
2455        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2456            reconsumed_head_e2e = true;
2457            let pass = state.passes.last().map_or(0, |p| p.index);
2458            if !task
2459                .passes
2460                .iter()
2461                .any(|p| p.run == state.id && p.pass_index == pass)
2462            {
2463                task.attempts = task.attempts.saturating_sub(1);
2464            }
2465        }
2466        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2467        task.hold_head_e2e(stop, reason, detail.to_owned());
2468    } else {
2469        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2470    }
2471    if !verdict.parked
2472        && !verdict.quota_hit
2473        && !reconsumed_head_e2e
2474        && matches!(
2475            verdict.status,
2476            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2477        )
2478    {
2479        task.recovery_failed(state);
2480    }
2481    if state.prep_failure.is_some() {
2482        // Minting a run whose candidates could not be prepared is not work
2483        // on a newly approved attempt. Keep the unresolved outcome anchor.
2484        task.hold_notice_cause = unresolved;
2485        task.startup_notice_cause("startup-candidates");
2486    }
2487    // Written here, where the refund (or not) is decided, so the history is a
2488    // fact and not a later guess from the run's status.
2489    if let Some(pass) = state.passes.last() {
2490        let parked = match &pass.end {
2491            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2492            _ => None,
2493        };
2494        task.record_pass_at(
2495            &state.id,
2496            pass.index,
2497            Some(pass.started_at),
2498            attempts_before,
2499            parked,
2500        );
2501    }
2502    if task.status == TaskStatus::Held {
2503        if state.base_sync_blocked() {
2504            task.base_sync_notice(state);
2505        } else if state.land_sync_exhausted() {
2506            task.land_sync_notice(state);
2507        } else if let Some(stop) = &head_e2e_stop {
2508            task.head_e2e_notice(stop);
2509        } else if state.prep_failure.is_none() {
2510            task.notice_cause(
2511                label(verdict.status),
2512                Some(&state.id),
2513                state.passes.last().map(|p| p.index),
2514            );
2515        }
2516        task.diagnostic = diagnostic(state);
2517        note_open_question(task, &state.id, p);
2518    }
2519}
2520
2521/// If `task` is held with a `magi ask` question still open on `run`, name the
2522/// question in [`Task::hold_reason`] rather than leaving the hold reading
2523/// only [`describe`]'s run summary.
2524///
2525/// This is the shape task 20260928-191407-05fd left underspecified: an
2526/// implementer settled a verified no-op and filed a question for the
2527/// operator, and the hold that followed said nothing about the question
2528/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2529/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2530/// marker) and must keep seeing it unchanged.
2531///
2532/// Best-effort: an unreadable question store must not stop a run from
2533/// settling, so this is a no-op rather than a propagated error when
2534/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2535fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2536    let Some(home) = crate::run::try_home() else {
2537        return;
2538    };
2539    let open = Questions::at(home.join("questions")).open_for(run);
2540    let Some(q) = open.first() else {
2541        return;
2542    };
2543    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2544    decisions.sort_unstable();
2545    task.notice_cause(
2546        &format!("questions:{}", decisions.join(",")),
2547        Some(run),
2548        None,
2549    );
2550    let base = task.hold_reason.clone().unwrap_or_default();
2551    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2552}
2553
2554/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2555/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2556/// by some other means entirely, like a manual `magi run` resume that
2557/// finishes the graph outside the queue's bookkeeping.
2558///
2559/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2560/// `settle` is separate from `attempt`: a task recovered this way must land
2561/// exactly where a live daemon would have put it — the same policy table,
2562/// not a second one that quietly drifts from it — and that is only checkable
2563/// without spawning a real run.
2564fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2565    if let Some(request) = task.sync_only.clone() {
2566        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2567        return;
2568    }
2569    match last_run {
2570        Some(state) => {
2571            let verdict = Verdict {
2572                status: state.status,
2573                left_pr: state.pr.is_some(),
2574                quota_hit: state.quota.iter().any(|loss| {
2575                    state
2576                        .passes
2577                        .last()
2578                        .is_none_or(|pass| loss.at >= pass.started_at)
2579                }),
2580                parked: state.parked,
2581                no_viable_candidates: state.viable().is_empty(),
2582            };
2583            let detail = format!(
2584                "{}{}",
2585                phrases(&state.config.graph.language).recovered_running,
2586                describe(&state)
2587            );
2588            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2589        }
2590        None => {
2591            // No run, so no config of its own: `language` is the task's
2592            // repository's setting, read by the caller.
2593            let why = phrases(language).no_run_to_recover;
2594            task.last_error = Some(why.to_owned());
2595            // The phone shows `hold_reason`, so a task held by the machine
2596            // says why there too and not only in `last_error`.
2597            task.notice_cause("missing-run", None, None);
2598            task.hold_machine(Some(why.to_owned()));
2599        }
2600    }
2601}
2602
2603/// Find every task left at `running` that no live process is actually
2604/// driving, and settle each one against whatever its last run became.
2605///
2606/// # Why a claim is proof, not a guess
2607///
2608/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2609/// `running`, and the guard is held for the task's whole time in that status:
2610/// `attempt` does not return, and the loop does not move past the scope
2611/// holding the claim, until the run has settled. So a `running` task whose
2612/// lock is gone cannot have a live owner — this process or any other —
2613/// without needing a staleness threshold or a pid check the way
2614/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2615/// task that never got as far as `running` at all. Taking the claim here is
2616/// the whole test: it either fails, because something really does hold it
2617/// and the task is left alone, or it succeeds, which is the proof — and it is
2618/// kept for the rest of the decision so nothing else can start a competing
2619/// run while this one is being written.
2620///
2621/// Called on every poll, not only at startup, for the reason
2622/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2623/// keep noticing this, not only on the one morning it happened to restart.
2624fn reclaim_orphaned_running(
2625    queue: &Queue,
2626    max_attempts: usize,
2627    live_workers: &std::collections::BTreeSet<String>,
2628) -> Vec<String> {
2629    let mut reclaimed = Vec::new();
2630    for listed in queue.list() {
2631        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2632            continue;
2633        }
2634        let Ok(_claim) = queue.claim(&listed.id) else {
2635            continue;
2636        };
2637        // Re-read under the claim: a release or an edit landed by a human
2638        // between the listing above and the claim just taken must not be
2639        // clobbered by a decision based on the stale copy.
2640        let Ok(mut task) = queue.get(&listed.id) else {
2641            continue;
2642        };
2643        if task.status != TaskStatus::Running {
2644            continue;
2645        }
2646        let last_run = task
2647            .execution_runs()
2648            .last()
2649            .and_then(|id| RunState::load(id).ok());
2650        // `execute` normally abandons a run's own open questions the moment
2651        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2652        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2653        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2654        // with the question still `open`, because the process died before
2655        // reaching that call. `reclaim` itself stays pure on purpose (see its
2656        // own doc), so the same cleanup runs here instead, against the run
2657        // this reclaim is already reading. `settle_run` costs nothing when
2658        // `execute` already got there first.
2659        if let Some(state) = &last_run
2660            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2661        {
2662            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2663        }
2664        let language = if last_run.is_none() {
2665            language_of(&task, Path::new("."))
2666        } else {
2667            String::new()
2668        };
2669        reclaim(&mut task, last_run, max_attempts, &language);
2670        if task.status == TaskStatus::Done {
2671            supersede_prior_runs(&task, &crate::run::home());
2672        }
2673        record(queue, &mut task);
2674        reclaimed.push(task.id.clone());
2675    }
2676    reclaimed
2677}
2678
2679/// Find every run whose `run.json` is provably dead — every seat it still
2680/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2681/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2682/// not merely "no daemon claims it" — and fail it, clearing the leftover
2683/// active seats so the run stops reading as `implementing` (or whichever
2684/// node) forever.
2685///
2686/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2687/// `running`, using whatever `run.json` already says — but nothing in that
2688/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2689/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2690/// never got back to sits exactly where it was left: `active` full of seats
2691/// nobody will ever answer for, `status` stuck on whatever node was in
2692/// flight. `magi show` already tells an operator this in prose (`no live
2693/// daemon claims this run right now`); this is what makes that fact durable
2694/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2695/// stay stuck once nothing is driving it.
2696///
2697/// Runs on every poll, not only at startup, for the reason
2698/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2699/// daemon up for days must keep noticing a run some other, now-dead, daemon
2700/// left behind just as readily as one it trips over on the way up.
2701///
2702/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2703/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2704/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2705/// `runs` directory instead: `home` here is a parameter precisely so a test
2706/// can point it away from the operator's real history (see [`drive`]'s own
2707/// doc), and a scan that fell through to the global home anyway would walk
2708/// whichever directory some *other* process or test pinned into that
2709/// `OnceLock` first — mutating runs this call was never handed.
2710fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2711    reclaim_abandoned_runs_with(
2712        home,
2713        now,
2714        crate::proc::pid_status,
2715        crate::proc::process_started_at,
2716    )
2717}
2718
2719/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2720/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2721/// for the identical reason: this sweep's real damage (wiping a run's active
2722/// seats and failing it) has to be provable against an injected answer in a
2723/// test, not just the real process table.
2724fn reclaim_abandoned_runs_with<F, G>(
2725    home: &Path,
2726    now: Timestamp,
2727    query: F,
2728    identity: G,
2729) -> Vec<String>
2730where
2731    F: Fn(u32) -> Option<bool>,
2732    G: Fn(u32) -> Option<String>,
2733{
2734    let mut abandoned = Vec::new();
2735    for entry in std::fs::read_dir(home.join("runs"))
2736        .into_iter()
2737        .flatten()
2738        .flatten()
2739    {
2740        let id = entry.file_name().to_string_lossy().into_owned();
2741        if !crate::run::is_run_id(&id) {
2742            continue;
2743        }
2744        // Serialize the proof and save with claims and takeover: a new
2745        // execution must not be overwritten after the liveness observation.
2746        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2747            continue;
2748        };
2749        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2750        // that module's docs for why a run this cannot parse is left alone
2751        // rather than guessed at. A different schema number is not that: this
2752        // touches only `status` and `active`, never a field whose meaning a
2753        // schema bump changed, so an old record's values serve this exactly
2754        // as well as a current one's (see `clean::read_state`'s own doc for
2755        // the same reasoning applied to folding).
2756        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2757            continue;
2758        };
2759        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2760            continue;
2761        };
2762        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2763            continue;
2764        }
2765        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2766        // it", which is also the normal, healthy shape of a manual `magi
2767        // run` / `magi review` sharing this same home — this scan walks
2768        // every run on disk, not only ones this daemon itself started. Such
2769        // a run's active seats can legitimately sit past their own timeout
2770        // for a little while (the CLI finishing up, its result still being
2771        // collected) without the process driving it having died. `liveness`
2772        // is what actually tells the two apart, by corroborating
2773        // `driver_pid` against the process it names — see its own doc. Only
2774        // its strongest, provable answer licenses wiping this run's active
2775        // seats and failing it out from under whatever is still running it.
2776        let daemon_claims = is_working_on(home, &id, now);
2777        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2778            != crate::run::Liveness::Dead
2779        {
2780            continue;
2781        }
2782        state.abandon("daemon");
2783        if let Err(e) = state.save_under(home) {
2784            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2785            continue;
2786        }
2787        // This run never passes through `Runner::execute` again, so its end
2788        // is announced here.
2789        if let Some(notice) = notices::run_ended(&state) {
2790            notices::raise_in(home, notice);
2791        }
2792        // The seat that asked is gone for good now, exactly like any other
2793        // door `graph::Runner::settle_questions` closes the moment `status`
2794        // lands somewhere non-resumable - see that method's own doc. Nothing
2795        // else reaches this one before the next `janitor()` startup pass
2796        // (`clean::abandon_settled_questions`), and a daemon that stays up
2797        // for days must not leave an open question badging the operator
2798        // until it happens to restart.
2799        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2800            tracing::warn!("abandon questions for {id}: {e:#}");
2801        }
2802        abandoned.push(id);
2803    }
2804    abandoned
2805}
2806
2807#[derive(Debug, Clone, Serialize, Deserialize)]
2808struct TaskWorker {
2809    opts: Opts,
2810    queue: PathBuf,
2811    task: String,
2812    #[serde(default)]
2813    lane: PermitKind,
2814    #[serde(default)]
2815    standalone: bool,
2816}
2817
2818#[doc(hidden)]
2819pub struct TaskWorkerLease {
2820    pub job: crate::worker::Job,
2821    dir: PathBuf,
2822    lease: Option<crate::worker::Lease>,
2823}
2824
2825impl TaskWorkerLease {
2826    pub fn release_lease(&mut self) {
2827        self.lease = None;
2828    }
2829}
2830
2831impl Drop for TaskWorkerLease {
2832    fn drop(&mut self) {
2833        self.release_lease();
2834        let _ = std::fs::remove_dir_all(&self.dir);
2835    }
2836}
2837
2838/// Reserve a task worker without launching a process, for integration tests.
2839#[doc(hidden)]
2840pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2841    let request = TaskWorker {
2842        opts: Opts::default(),
2843        queue: home.join("queue"),
2844        task: task.to_owned(),
2845        lane: PermitKind::default(),
2846        standalone: true,
2847    };
2848    let (job, lease) = crate::worker::running_fixture(
2849        home,
2850        &format!("task:{task}"),
2851        serde_json::to_value(request)?,
2852    )?;
2853    Ok(TaskWorkerLease {
2854        dir: home.join("workers").join("jobs").join(&job.id),
2855        job,
2856        lease: Some(lease),
2857    })
2858}
2859
2860fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2861    Ok(crate::worker::active(home)?
2862        .into_iter()
2863        .filter(|job| job.kind == "task")
2864        .collect())
2865}
2866
2867fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2868    task_jobs(home)?
2869        .into_iter()
2870        .filter_map(
2871            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2872                Ok(request) if !request.standalone => Some(Ok(job)),
2873                Ok(_) => None,
2874                Err(error) => Some(Err(error.into())),
2875            },
2876        )
2877        .collect()
2878}
2879
2880/// Whether an independent scheduler can be controlled without its web parent.
2881#[must_use]
2882pub fn managed(home: &Path) -> bool {
2883    match crate::worker::active(home) {
2884        Err(error) => {
2885            tracing::error!("cannot determine scheduler ownership: {error:#}");
2886            true
2887        }
2888        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2889        Ok(_) => {
2890            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2891                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2892        }
2893    }
2894}
2895
2896/// Start a detached, singleton scheduler using this executable generation.
2897pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2898    anyhow::ensure!(
2899        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2900        "the scheduler is stopping; wait for retirement before starting it again"
2901    );
2902    crate::worker::spawn(
2903        home,
2904        "scheduler",
2905        "scheduler",
2906        serde_json::to_value(opts.absolute()?)?,
2907    )
2908    .await
2909}
2910
2911fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2912    home.join("worker-parks").join(format!("{}.json", job.id))
2913}
2914
2915fn request_task_park(
2916    home: &Path,
2917    job: &crate::worker::Job,
2918    cause: crate::run::ParkCause,
2919) -> Result<()> {
2920    let path = park_request_path(home, job);
2921    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2922    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2923    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2924}
2925
2926/// Stop dispatch immediately; only an explicit park reaches existing workers.
2927pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2928    if control == crate::worker::Control::Park {
2929        for job in owned_task_jobs(home)? {
2930            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2931        }
2932    }
2933    crate::worker::request(home, "scheduler", control)
2934}
2935
2936/// Resolve what a restart would replace without signalling the scheduler.
2937pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2938    if let Some(job) = crate::worker::active(home)?
2939        .into_iter()
2940        .find(|job| job.kind == "scheduler")
2941    {
2942        return serde_json::from_value(job.payload)
2943            .context("read detached scheduler options")
2944            .map(Some);
2945    }
2946    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2947        && crate::worker::try_lease(home, "scheduler")?.is_none()
2948    {
2949        let path = home.join("scheduler-options.json");
2950        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2951        return serde_json::from_slice(&body)
2952            .context("decode detached scheduler options")
2953            .map(Some);
2954    }
2955    Ok(None)
2956}
2957
2958/// Replace the scheduler, leaving all active task and conversation jobs alone.
2959pub async fn restart_detached(home: &Path) -> Result<()> {
2960    let Some(opts) = scheduler_restart_options(home)? else {
2961        return Ok(());
2962    };
2963    request_control(home, crate::worker::Control::Stop)?;
2964    loop {
2965        let reserved = crate::worker::active(home)?
2966            .iter()
2967            .any(|job| job.kind == "scheduler");
2968        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2969            break;
2970        }
2971        tokio::time::sleep(Duration::from_millis(100)).await;
2972    }
2973    spawn_detached(home, &opts).await?;
2974    Ok(())
2975}
2976
2977/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2978pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2979    let opts: Opts = serde_json::from_value(payload)?;
2980    let _ = home;
2981    serve_until(opts, Stop::new()).await
2982}
2983
2984/// Execute and settle one task with the queue claim owned by this process.
2985pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2986    let request: TaskWorker = serde_json::from_value(payload)?;
2987    let queue = Queue::at(request.queue);
2988    let key = format!("task:{}", request.task);
2989    let job = task_jobs(home)?
2990        .into_iter()
2991        .find(|job| job.key == key)
2992        .context("task worker reservation is missing")?;
2993    let park_path = park_request_path(home, &job);
2994    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2995    // our durable reservation. Never execute before that ownership hand-off.
2996    let _claim = loop {
2997        match queue.claim(&request.task) {
2998            Ok(claim) => break claim,
2999            // Only contention (the claim file exists) is worth waiting out; an
3000            // I/O failure must end this worker instead of pinning its lane.
3001            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
3002                return Err(e.context("claim the task for its worker"));
3003            }
3004            Err(_) => {
3005                sweep_stale_claims(&queue, STALE_CLAIM);
3006                tokio::time::sleep(Duration::from_millis(50)).await;
3007            }
3008        }
3009    };
3010    let mut task = queue.get(&request.task)?;
3011    if !task.status.runnable()
3012        || (!request.standalone
3013            && request.lane
3014                != permit_kind(
3015                    land_resume_state(&task) == LandResume::Ready,
3016                    task.immediate,
3017                    task.urgent,
3018                ))
3019    {
3020        return Ok(());
3021    }
3022    let stop = Stop::new();
3023    let watcher = {
3024        let home = home.to_path_buf();
3025        let stop = stop.clone();
3026        let park_path = park_path.clone();
3027        tokio::spawn(async move {
3028            loop {
3029                if crate::worker::control(&home, &key).ok().flatten().is_some() {
3030                    let cause = std::fs::read(&park_path)
3031                        .ok()
3032                        .and_then(|body| serde_json::from_slice(&body).ok())
3033                        .unwrap_or(crate::run::ParkCause::Operator);
3034                    stop.park(cause);
3035                    return;
3036                }
3037                tokio::time::sleep(Duration::from_millis(200)).await;
3038            }
3039        })
3040    };
3041    let quota = if request.standalone {
3042        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3043    } else {
3044        let status = Arc::new(Mutex::new(Status::new()));
3045        Box::pin(attempt(
3046            &request.opts,
3047            &queue,
3048            &status,
3049            &stop,
3050            crate::graph::Pause::new(),
3051            &mut task,
3052        ))
3053        .await
3054    };
3055    watcher.abort();
3056    let _ = std::fs::remove_file(park_path);
3057    persist_cooldown(home, &quota).await?;
3058    Ok(())
3059}
3060
3061/// Launch the standalone task worker with a claim-to-reservation handoff.
3062/// Returns only after the worker owns a durable execution reservation.
3063pub async fn spawn_claimed(
3064    home: &Path,
3065    opts: &Opts,
3066    queue: &Queue,
3067    task: &Task,
3068    claim: crate::queue::Claim,
3069) -> Result<crate::worker::Job> {
3070    let request = TaskWorker {
3071        opts: opts.absolute()?,
3072        queue: std::path::absolute(queue.root())?,
3073        task: task.id.clone(),
3074        lane: permit_kind(
3075            land_resume_state(task) == LandResume::Ready,
3076            task.immediate,
3077            task.urgent,
3078        ),
3079        standalone: true,
3080    };
3081    let job = crate::worker::spawn(
3082        home,
3083        "task",
3084        &format!("task:{}", task.id),
3085        serde_json::to_value(request)?,
3086    )
3087    .await?;
3088    drop(claim);
3089    Ok(job)
3090}
3091
3092/// Transfer a standalone caller's claim only after the detached worker is live,
3093/// then follow that worker to its final (non-automatically-retrying) outcome.
3094pub async fn run_detached_claimed(
3095    opts: &Opts,
3096    queue: &Queue,
3097    task: &mut Task,
3098    claim: crate::queue::Claim,
3099) -> Result<()> {
3100    let home = crate::run::home();
3101    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3102    loop {
3103        // Reconcile execution leases even without a scheduler. A dead worker
3104        // must become a reported failure, never an infinite persisted wait.
3105        crate::worker::active(&home)?;
3106        let current = crate::worker::get(&home, &job.id)?;
3107        if matches!(
3108            current.status,
3109            crate::worker::Status::Finished | crate::worker::Status::Failed
3110        ) {
3111            *task = queue.get(&task.id)?;
3112            anyhow::ensure!(
3113                current.status != crate::worker::Status::Failed,
3114                "task worker failed: {}",
3115                current.result.as_deref().unwrap_or("unknown failure")
3116            );
3117            return Ok(());
3118        }
3119        tokio::time::sleep(Duration::from_millis(200)).await;
3120    }
3121}
3122
3123async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3124    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3125        let _lease = loop {
3126            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3127                break lease;
3128            }
3129            tokio::time::sleep(Duration::from_millis(10)).await;
3130        };
3131        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3132            let path = home.join("task-quota-cooldown.json");
3133            let temporary = path.with_extension("json.tmp");
3134            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3135            std::fs::rename(temporary, path)?;
3136        }
3137    }
3138    Ok(())
3139}
3140
3141fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3142    match std::fs::read(home.join("task-quota-cooldown.json")) {
3143        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3144        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3145        Err(error) => Err(error.into()),
3146    }
3147}
3148
3149/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3150///
3151/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3152/// sets, so there is one loop body rather than two that drift apart the first
3153/// time the retry policy changes on only one of them.
3154pub async fn serve(opts: Opts) -> Result<()> {
3155    tracing::info!(
3156        "automatic update and restart requires magi web; standalone serve does not restart"
3157    );
3158    serve_until(opts, Stop::new()).await
3159}
3160
3161/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3162///
3163/// A stop retires dispatch promptly, including while a worker launch is being
3164/// acknowledged. Already reserved workers own their attempts independently and
3165/// finish with their started executable. Explicit park additionally forwards
3166/// durable park requests; neither scheduler retirement nor update does so.
3167///
3168/// While the queue is empty the stop is honoured within one wakeup rather than
3169/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3170/// caller that taps stop does not sit through the remainder of a sleep.
3171pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3172    let opts = opts.absolute()?;
3173    let home = crate::run::home();
3174    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3175        .context("another scheduler already owns this home")?;
3176    if let Some(reading) = read_status(&home)
3177        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3178    {
3179        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3180    }
3181    if !crate::worker::active(&home)?
3182        .iter()
3183        .any(|job| job.kind == "scheduler")
3184    {
3185        crate::worker::clear_control(&home, "scheduler")?;
3186    }
3187    std::fs::write(
3188        home.join("scheduler-options.json"),
3189        serde_json::to_vec(&opts)?,
3190    )?;
3191    let control = {
3192        let home = home.clone();
3193        let stop = stop.clone();
3194        tokio::spawn(async move {
3195            loop {
3196                match crate::worker::control(&home, "scheduler").ok().flatten() {
3197                    Some(crate::worker::Control::Park) => {
3198                        let _ = request_control(&home, crate::worker::Control::Park);
3199                        stop.park(crate::run::ParkCause::Operator);
3200                        break;
3201                    }
3202                    Some(crate::worker::Control::Stop) => {
3203                        stop.stop();
3204                        break;
3205                    }
3206                    None => {}
3207                }
3208                tokio::time::sleep(Duration::from_millis(100)).await;
3209            }
3210        })
3211    };
3212    let signal = {
3213        let stop = stop.clone();
3214        tokio::spawn(async move {
3215            if tokio::signal::ctrl_c().await.is_ok() {
3216                stop.stop();
3217                tracing::info!("scheduler shutdown requested; independent workers continue");
3218            }
3219        })
3220    };
3221
3222    let worktrees_root = opts
3223        .worktrees_root
3224        .clone()
3225        .unwrap_or_else(crate::run::default_worktree_root);
3226    let outcome = drive(
3227        &opts,
3228        &Queue::open(),
3229        &status_path(),
3230        &crate::run::home(),
3231        &worktrees_root,
3232        &stop,
3233    )
3234    .await;
3235
3236    signal.abort();
3237    control.abort();
3238    outcome
3239}
3240
3241/// The loop proper: setup, poll, teardown, with the queue and the status file
3242/// supplied rather than discovered.
3243///
3244/// All three of `home`, `worktrees_root` and the queue/status paths are
3245/// parameters rather than resolved here, for the same reason:
3246/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3247/// so a unit test that pinned it would fight every other test in the binary,
3248/// and a loop that resolved its own worktree bay could only be exercised
3249/// against the operator's real `~/wt/<repo>` - publishing over a live
3250/// daemon's status file, claiming tasks out of a live backlog, and, since
3251/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3252/// whatever the operator actually has on disk.
3253async fn drive(
3254    opts: &Opts,
3255    queue: &Queue,
3256    status_file: &Path,
3257    home: &Path,
3258    worktrees_root: &Path,
3259    stop: &Stop,
3260) -> Result<()> {
3261    // The status file is a *snapshot*, not a stream of events: a reader only
3262    // ever wants the latest values, and every tick rewrites the whole file
3263    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3264    // while an mpsc channel would force the loop to re-send unchanged fields on
3265    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3266    // for no gain. The lock is only ever held across a field assignment, never
3267    // across an await.
3268    let recovery_cfg = prepare(&opts.repo, opts).ok();
3269    let daemon_cfg = recovery_cfg
3270        .as_ref()
3271        .map(|c| c.daemon.clone())
3272        .unwrap_or_default();
3273    let reconciled = crate::driver::reconcile(home);
3274    if !reconciled.is_empty() {
3275        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3276    }
3277    let mut initial_status = Status::new();
3278    let owned = owned_task_jobs(home)?;
3279    initial_status.current = current_work(home, Timestamp::now())
3280        .into_iter()
3281        .filter(|current| {
3282            owned
3283                .iter()
3284                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3285        })
3286        .collect();
3287    initial_status.idle = initial_status.current.is_empty();
3288    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3289        recovery_cfg.as_ref(),
3290        daemon_cfg.max_deputies,
3291    ));
3292    let status = Arc::new(Mutex::new(initial_status));
3293    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3294    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3295
3296    // Read once at startup, not per task: how many runs this loop drives at
3297    // once is a property of the machine running it, not of whichever
3298    // repository a given task happens to name - see
3299    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3300    // fact in the same sense the agent roster is.
3301    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3302
3303    tracing::info!(
3304        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3305        queue.root().display(),
3306        opts.poll.as_secs(),
3307        opts.max_attempts,
3308        concurrency,
3309        if daemon_cfg.pause_for_interrupts {
3310            ", interrupts enabled"
3311        } else {
3312            ""
3313        }
3314    );
3315
3316    let outcome = tokio::select! {
3317        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3318            max_concurrent: concurrency,
3319            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3320            recovery_cfg,
3321        }) => outcome,
3322        () = async {
3323            while !stop.stopped() {
3324                tokio::time::sleep(Duration::from_millis(25)).await;
3325            }
3326        } => {
3327            if stop.parking() {
3328                request_control(home, crate::worker::Control::Park)?;
3329            }
3330            Ok(())
3331        }
3332    };
3333
3334    stop.busy.store(0, Ordering::SeqCst);
3335    beat.abort();
3336    clear_status_at(status_file);
3337    outcome
3338}
3339
3340/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3341/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3342pub(crate) fn release_watch_settings_from_config(
3343    home: &Path,
3344    repo: &Path,
3345    cfg: &Config,
3346) -> (Vec<PathBuf>, u64) {
3347    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3348        .into_iter()
3349        .map(|r| r.path)
3350        .collect();
3351    // Repositories the daemon has worked in, wherever they live: a task may
3352    // name one outside `[repos] roots`, and its release PR must be watched too.
3353    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3354        .list()
3355        .into_iter()
3356        .map(|t| t.repo)
3357        .collect();
3358    let runs = home.join("runs");
3359    for id in crate::run::list_ids_in(&runs) {
3360        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3361            .ok()
3362            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3363            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3364        known.extend(repo);
3365    }
3366    for k in known {
3367        let k = k.canonicalize().unwrap_or(k);
3368        if k.join(".git").exists() && !paths.contains(&k) {
3369            paths.push(k);
3370        }
3371    }
3372    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3373    if !paths.contains(&own) {
3374        paths.push(own);
3375    }
3376    (paths, cfg.daemon.release_stall_minutes)
3377}
3378
3379/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3380const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3381
3382/// Refresh the status file on a fixed tick.
3383///
3384/// Separate from the loop because a run takes tens of minutes: a status file
3385/// written only between tasks would look stale for the whole of every run, and
3386/// a reader would report the daemon dead exactly while it was busiest.
3387async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3388    loop {
3389        tokio::time::sleep(HEARTBEAT).await;
3390        let snapshot = {
3391            let mut guard = lock(&status);
3392            guard.updated_at = Timestamp::now();
3393            guard.clone()
3394        };
3395        if let Err(e) = write_status_to(&path, &snapshot) {
3396            // A failed heartbeat must not take the daemon down: the loop is the
3397            // product, the status file is only the window onto it.
3398            tracing::warn!("could not refresh the daemon status file: {e:#}");
3399        }
3400    }
3401}
3402
3403/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3404/// if so, whether that wait is over.
3405#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3406enum LandResume {
3407    /// The task's last run is not parked on a land approval; schedule it
3408    /// like any other candidate.
3409    NotLanding,
3410    /// Parked in `land`, waiting on a question nobody has answered yet.
3411    /// Left alone: attempting it now would only re-observe the same pull
3412    /// request and park again, spending a `gh` call on a decision that has
3413    /// not changed since the last time this was checked.
3414    StillWaiting,
3415    /// Parked in `land`, and the question is settled - answered or
3416    /// abandoned. Resuming this is the one kind of candidate that must not
3417    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3418    Ready,
3419}
3420
3421/// Classify a runnable candidate by whether it is parked on a land-merge
3422/// approval. Read-only - no claim taken, nothing written - so it is cheap
3423/// enough to call on every candidate, every poll.
3424fn land_resume_state(task: &Task) -> LandResume {
3425    if task.sync_only.is_some() {
3426        return LandResume::NotLanding;
3427    }
3428    let Some(run_id) = task.execution_runs().last() else {
3429        return LandResume::NotLanding;
3430    };
3431    let Ok(state) = RunState::load(run_id) else {
3432        return LandResume::NotLanding;
3433    };
3434    if !state.parked {
3435        return LandResume::NotLanding;
3436    }
3437    if state.status == RunStatus::Landing
3438        && state.land_approval.as_ref().is_some_and(|binding| {
3439            ask::Questions::open()
3440                .get_for_effects(&binding.question)
3441                .is_ok_and(|q| {
3442                    q.run == state.id
3443                        && q.resolution()
3444                            .as_deref()
3445                            .is_some_and(crate::merge_decision::stops)
3446                })
3447        })
3448    {
3449        return LandResume::Ready;
3450    }
3451    if !implementers_match(task, &state) {
3452        return LandResume::NotLanding;
3453    }
3454    // Parked in `land` on the merge approval, or at `merge` on the owner's
3455    // word about a title/body the posting gate withheld. Told apart by the
3456    // run's own record, not by a status both can share.
3457    let node = if state.status == RunStatus::Landing {
3458        land::APPROVAL_NODE
3459    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3460        crate::github_text::ASK_NODE
3461    } else {
3462        return LandResume::NotLanding;
3463    };
3464    let store = ask::Questions::open();
3465    let waiting = store
3466        .list_for_effects()
3467        .into_iter()
3468        .filter(|q| &q.run == run_id && q.node == node)
3469        .max_by(|a, b| a.id.cmp(&b.id));
3470    let Some(mut q) = waiting else {
3471        return LandResume::Ready;
3472    };
3473    if !q.status.open() {
3474        // Repair spends agent resources and must obey concurrency and quota
3475        // waits; only a merge/hold decision may use the decision-only lane.
3476        if q.resolution().as_deref() == Some(land::REPAIR) {
3477            return if state.liveness(false) == Liveness::Live {
3478                LandResume::StillWaiting
3479            } else {
3480                LandResume::NotLanding
3481            };
3482        }
3483        return LandResume::Ready;
3484    }
3485    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3486    // nobody ever answered; land's approval bypasses that wait entirely (see
3487    // `land::approval_gate`), so the same deadline has to be enforced here
3488    // instead, or `graph.answer_timeout` silently stops meaning anything for
3489    // a land approval and a run can sit `StillWaiting` forever with nobody
3490    // told to look at it.
3491    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3492    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3493    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3494        q.abandon(format!(
3495            "no answer within {}s of asking",
3496            timeout.as_secs().max(1)
3497        ));
3498        // If this can't be persisted, do not treat the wait as settled on a
3499        // guess: fall through and try again next poll.
3500        if store.put(&mut q).is_ok() {
3501            return LandResume::Ready;
3502        }
3503    }
3504    LandResume::StillWaiting
3505}
3506
3507/// How often the loop rechecks for new work while something it already
3508/// started is still running, rather than sleeping out the whole
3509/// [`Opts::poll`] interval.
3510///
3511/// Short on purpose: this is what lets a land-merge approval that comes back
3512/// while another task is mid-competition be noticed and resumed within a
3513/// fraction of a second, not within the next multi-second poll.
3514const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3515
3516/// How often [`poll`] rechecks the shared build cache against its cap at a
3517/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3518/// waiting for the queue to run dry.
3519///
3520/// A queue that never empties means the `janitor` call at the bottom of this
3521/// loop's fully-idle branch can go unreached for as long as the backlog
3522/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3523/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3524/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3525/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3526/// backlog of short tasks does not pay for that walk on every poll.
3527const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3528
3529/// State of [`poll`]'s own interrupt-scheduling sequence - see
3530/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3531/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3532/// both kept free of `Task`'s non-identity fields on purpose: every decision
3533/// here turns only on task ids and which ones are in flight, so the "never
3534/// more than one run at once" and "exactly one resume" invariants can be
3535/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3536/// queue - which is exactly the coverage this feature's first two attempts
3537/// were missing.
3538///
3539/// Persisted after every transition, so scheduler replacement preserves the
3540/// interrupt's exclusive turn and the interrupted task's priority resume.
3541#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3542enum Interrupt {
3543    /// No interrupt sequence in progress. Ordinary dispatch applies.
3544    Idle,
3545    /// `interrupt_task` is runnable and exactly one other run is in flight;
3546    /// `parked` names that one task's id. Dispatch is withheld from
3547    /// everyone, including `interrupt_task` itself, until it has left
3548    /// flight - only then is `interrupt_task` let through.
3549    ///
3550    /// `parked` is a `Vec` rather than a bare id for symmetry with
3551    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3552    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3553    /// when exactly one run is in flight, so it is guaranteed to hold
3554    /// exactly one entry in practice - see that branch's own doc for why
3555    /// more than one is deliberately never attempted.
3556    Parking {
3557        parked: Vec<String>,
3558        interrupt_task: String,
3559    },
3560    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3561    /// withheld from everyone until it leaves flight - merged, failed, held,
3562    /// it makes no difference - at which point the sequence moves to
3563    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3564    /// going straight to `Idle` would hand `parked` back to ordinary
3565    /// priority-order dispatch, where a higher-priority task filed in the
3566    /// meantime could start ahead of it.
3567    Running {
3568        parked: Vec<String>,
3569        interrupt_task: String,
3570    },
3571    /// `interrupt_task` left flight; `parked` still names the one run this
3572    /// sequence owes a resume. Dispatch is withheld from everyone except
3573    /// that task - see [`interrupt_gate`] - so the resume this feature
3574    /// promises is never raced by, or run alongside, an unrelated candidate.
3575    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3576    /// own doc on abandonment - the moment it is no longer runnable at all.
3577    Resuming { parked: Vec<String> },
3578}
3579
3580/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3581/// and `runnable` are read-only snapshots of this tick's reality, and the
3582/// only side effect the caller still owes the world is asking whichever
3583/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3584/// site.
3585///
3586/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3587/// accepted rather than a narrower type because that is what [`poll`] already
3588/// has on hand from [`runnable`], and building a second, smaller list on
3589/// every tick just to satisfy this signature would cost more than it proves.
3590///
3591/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3592/// back to a task they are waiting on no longer being [`runnable`] - held,
3593/// blocked, deleted, or finished by some other means entirely, all of which
3594/// an operator can do to a task sitting in the queue with no claim on it at
3595/// all, at any moment, interrupt sequence or not. Without this check the
3596/// sequence would wait forever for a dispatch that can never come, and
3597/// `interrupt_gate` would withhold every other task in the queue right along
3598/// with it - a single `magi task hold` on the wrong id turning into a
3599/// daemon that never dispatches anything again.
3600fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3601    match state {
3602        Interrupt::Idle => {
3603            // Not just "something to interrupt": exactly one thing. More
3604            // than one run in flight only happens above the default
3605            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3606            // one resume, never run alongside anything else" only because
3607            // it is only ever seeded with exactly one id - see
3608            // `Interrupt::Resuming`'s own doc on why releasing more than one
3609            // parked id back to ordinary dispatch cannot be made safe
3610            // against that same setting's own extra concurrency slots.
3611            // Waiting here for the herd to settle to one is the
3612            // simplification this feature's own constraints ask for rather
3613            // than a second concurrency model to reconcile with the first.
3614            if in_flight.len() != 1 {
3615                return Interrupt::Idle;
3616            }
3617            match runnable.iter().find(|t| t.interrupt) {
3618                Some(t) => Interrupt::Parking {
3619                    parked: in_flight.to_vec(),
3620                    interrupt_task: t.id.clone(),
3621                },
3622                None => Interrupt::Idle,
3623            }
3624        }
3625        Interrupt::Parking {
3626            parked,
3627            interrupt_task,
3628        } => {
3629            if in_flight.iter().any(|id| parked.contains(id)) {
3630                // Still waiting for what was in flight to actually stop.
3631                Interrupt::Parking {
3632                    parked,
3633                    interrupt_task,
3634                }
3635            } else if in_flight.contains(&interrupt_task) {
3636                Interrupt::Running {
3637                    parked,
3638                    interrupt_task,
3639                }
3640            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3641                // The parked run(s) are gone, but the interrupt task has not
3642                // been dispatched yet on this tick - `interrupt_gate` is
3643                // what lets it through next.
3644                Interrupt::Parking {
3645                    parked,
3646                    interrupt_task,
3647                }
3648            } else {
3649                // The interrupt task itself is no longer runnable - see this
3650                // function's own doc on abandonment. The parked run(s) still
3651                // get their guaranteed resume; there is simply no interrupt
3652                // to run ahead of them any longer.
3653                Interrupt::Resuming { parked }
3654            }
3655        }
3656        Interrupt::Running {
3657            parked,
3658            interrupt_task,
3659        } => {
3660            if in_flight.contains(&interrupt_task) {
3661                Interrupt::Running {
3662                    parked,
3663                    interrupt_task,
3664                }
3665            } else {
3666                // The interrupt task's own run reached a terminal status,
3667                // whichever one - this is the *only* trigger that moves the
3668                // sequence on, driven straight off the same in-flight
3669                // bookkeeping `poll` already reaps every tick, not a second,
3670                // independent poll of anything.
3671                Interrupt::Resuming { parked }
3672            }
3673        }
3674        Interrupt::Resuming { parked } => {
3675            if in_flight.iter().any(|id| parked.contains(id)) {
3676                // One of the parked runs has been dispatched - the resume
3677                // this sequence owed is fulfilled. Whatever else is left in
3678                // `parked` (ordinarily nothing, at the default concurrency
3679                // of one) rejoins ordinary priority-order dispatch, same as
3680                // any other runnable task.
3681                Interrupt::Idle
3682            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3683                Interrupt::Resuming { parked }
3684            } else {
3685                // Abandonment (see this function's own doc): nothing left in
3686                // `parked` is even runnable any longer.
3687                Interrupt::Idle
3688            }
3689        }
3690    }
3691}
3692
3693/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3694/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3695/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3696/// indistinguishable from any other runnable task - exactly the "off does
3697/// nothing" this feature promises.
3698fn advance_interrupt_tick(
3699    enabled: bool,
3700    state: Interrupt,
3701    in_flight: &[String],
3702    runnable: &[Task],
3703) -> Interrupt {
3704    if !enabled {
3705        return Interrupt::Idle;
3706    }
3707    advance_interrupt(state, in_flight, runnable)
3708}
3709
3710/// Which of this tick's runnable candidates the interrupt sequence actually
3711/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3712/// each half is assertable on its own: this is the half that keeps a
3713/// competition and an interrupt from ever running at the same moment.
3714fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3715    match state {
3716        Interrupt::Idle => candidates,
3717        Interrupt::Parking {
3718            parked,
3719            interrupt_task,
3720        } => {
3721            if in_flight.iter().any(|id| parked.contains(id)) {
3722                Vec::new()
3723            } else {
3724                candidates
3725                    .into_iter()
3726                    .filter(|t| &t.id == interrupt_task)
3727                    .collect()
3728            }
3729        }
3730        Interrupt::Running { .. } => Vec::new(),
3731        // At most one: even if `parked` names more than one id (more than
3732        // one run was in flight when the sequence began, only possible
3733        // above the default `max_concurrent_runs = 1`), only the first match
3734        // is offered. Capping this to a single candidate - not merely to
3735        // `parked`'s own ids - is what makes "exactly one resume, never two
3736        // dispatched together" true regardless of how many ordinary slots
3737        // happen to be free this tick.
3738        Interrupt::Resuming { parked } => candidates
3739            .into_iter()
3740            .find(|t| parked.contains(&t.id))
3741            .into_iter()
3742            .collect(),
3743    }
3744}
3745
3746/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3747/// bundled into one parameter so `poll`'s own signature stays readable -
3748/// see [`drive`]'s call site for where these are actually read.
3749struct DispatchLimits {
3750    /// How many *ordinary* candidates run at once. See
3751    /// [`crate::config::Daemon::max_concurrent_runs`].
3752    max_concurrent: usize,
3753    /// See [`crate::config::Daemon::pause_for_interrupts`].
3754    pause_for_interrupts: bool,
3755    recovery_cfg: Option<Config>,
3756}
3757
3758/// Which semaphore, if any, dispatching a candidate should draw its permit
3759/// from.
3760///
3761/// Pure and separate from [`poll`]'s loop body for the same reason
3762/// [`advance_interrupt`] is: the choice between "decision-only land resume",
3763/// "owner-selected immediate lane", "spend the one urgent slot" and "spend an
3764/// ordinary slot" is explicit and directly unit-testable.
3765#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3766pub(crate) enum PermitKind {
3767    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3768    /// Checked first - a task can be both a land resume and marked
3769    /// [`Task::immediate`] or [`Task::urgent`], and the resume's own
3770    /// decision-only lane takes precedence.
3771    None,
3772    /// [`Task::immediate`]: owner-selected immediate execution lane.
3773    /// Consumes no semaphore permit and does not count against ordinary or
3774    /// urgent capacity, allowing multiple immediate tasks to dispatch even
3775    /// when both ordinary and urgent lanes are full. Kept distinct from
3776    /// [`PermitKind::None`] so decision-only resumes and immediate runs stay
3777    /// separable in persisted worker reservations and diagnostics.
3778    Immediate,
3779    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3780    /// (never in addition to trying) the ordinary pool. This is what lets
3781    /// an urgent task dispatch while every ordinary slot is already checked
3782    /// out, and what stops a second urgent task from opening a third run: it
3783    /// waits on this same one-slot semaphore rather than falling through to
3784    /// the ordinary one.
3785    Urgent,
3786    /// The ordinary `max_concurrent_runs` pool - unaffected by any of the
3787    /// above.
3788    #[default]
3789    Ordinary,
3790}
3791
3792impl PermitKind {
3793    pub(crate) fn label(self) -> &'static str {
3794        match self {
3795            Self::None => "decision",
3796            Self::Immediate => "immediate",
3797            Self::Urgent => "urgent",
3798            Self::Ordinary => "ordinary",
3799        }
3800    }
3801}
3802
3803/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3804/// own boolean, already computed by the caller from [`land_resume_state`].
3805/// Precedence: decision resume (`None`) > `Immediate` > `Urgent` > `Ordinary`.
3806fn permit_kind(priority: bool, immediate: bool, urgent: bool) -> PermitKind {
3807    if priority {
3808        PermitKind::None
3809    } else if immediate {
3810        PermitKind::Immediate
3811    } else if urgent {
3812        PermitKind::Urgent
3813    } else {
3814        PermitKind::Ordinary
3815    }
3816}
3817
3818fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3819    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3820        (0usize, 0usize),
3821        |(ordinary, urgent), request| match request.lane {
3822            PermitKind::Ordinary => (ordinary + 1, urgent),
3823            PermitKind::Urgent => (ordinary, urgent + 1),
3824            PermitKind::Immediate | PermitKind::None => (ordinary, urgent),
3825        },
3826    );
3827    (
3828        limit.saturating_sub(ordinary),
3829        1usize.saturating_sub(urgent),
3830    )
3831}
3832
3833/// Why a runnable candidate was not dispatched. This does not alter policy.
3834#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3835enum SkipReason {
3836    ClaimUnavailable,
3837    RereadFailed,
3838    NoLongerRunnable,
3839    WaitingOnLanding,
3840    CoolingDown,
3841    OrdinaryCapacity,
3842    UrgentCapacity,
3843    InterruptGate,
3844}
3845
3846impl SkipReason {
3847    fn key(self) -> &'static str {
3848        match self {
3849            Self::ClaimUnavailable => "claim_unavailable",
3850            Self::RereadFailed => "reread_failed",
3851            Self::NoLongerRunnable => "no_longer_runnable",
3852            Self::WaitingOnLanding => "waiting_on_landing",
3853            Self::CoolingDown => "cooling_down",
3854            Self::OrdinaryCapacity => "ordinary_capacity",
3855            Self::UrgentCapacity => "urgent_capacity",
3856            Self::InterruptGate => "interrupt_gate",
3857        }
3858    }
3859
3860    fn describe(self) -> &'static str {
3861        match self {
3862            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3863            Self::RereadFailed => "could not re-read it",
3864            Self::NoLongerRunnable => "no longer runnable",
3865            Self::WaitingOnLanding => "waiting on landing",
3866            Self::CoolingDown => "quota cooldown",
3867            Self::OrdinaryCapacity => "no free ordinary slot",
3868            Self::UrgentCapacity => "urgent slot busy",
3869            Self::InterruptGate => "withheld by the interrupt sequence",
3870        }
3871    }
3872}
3873
3874/// A reason count from a completed dispatch scan.
3875#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3876pub struct DispatchReasonCount {
3877    /// Stable string key, so readers can preserve future reasons.
3878    pub reason: String,
3879    /// Candidates skipped for this reason.
3880    pub count: usize,
3881}
3882
3883/// Observations from a completed scan, not a fresh queue estimate.
3884#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3885pub struct DispatchWait {
3886    /// Runnable candidates before the interrupt gate.
3887    pub runnable: usize,
3888    /// Counts in descending order, with stable reason order for ties.
3889    pub reasons: Vec<DispatchReasonCount>,
3890}
3891
3892type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3893
3894fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3895    if runnable == 0 {
3896        return None;
3897    }
3898    let mut counts = std::collections::BTreeMap::new();
3899    for (_, reason) in skips {
3900        *counts.entry(*reason).or_insert(0usize) += 1;
3901    }
3902    let mut counts: Vec<_> = counts.into_iter().collect();
3903    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3904    Some(DispatchWait {
3905        runnable,
3906        reasons: counts
3907            .into_iter()
3908            .map(|(reason, count)| DispatchReasonCount {
3909                reason: reason.key().to_owned(),
3910                count,
3911            })
3912            .collect(),
3913    })
3914}
3915
3916fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3917    before
3918        .iter()
3919        .filter(|id| !after.iter().any(|task| &task.id == *id))
3920        .map(|id| (id.clone(), SkipReason::InterruptGate))
3921        .collect()
3922}
3923
3924fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3925    if *previous == current {
3926        return false;
3927    }
3928    *previous = current;
3929    true
3930}
3931
3932/// Read-only task-level admission view shared by CLI (`magi task list` / `show`)
3933/// and Web (`TaskView`). Distinguishes configured mode, active persisted
3934/// reservation lane, and concrete blockers without ever mutating state.
3935#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3936pub struct TaskAdmission {
3937    /// Configured dispatch mode from the task record (`"immediate"`, `"urgent"`, `"ordinary"`).
3938    pub mode: &'static str,
3939    /// Persisted active worker reservation lane, if currently reserved/running
3940    /// (`"decision"`, `"immediate"`, `"urgent"`, `"ordinary"`).
3941    #[serde(default, skip_serializing_if = "Option::is_none")]
3942    pub reservation_lane: Option<&'static str>,
3943    /// True when the active worker reservation is standalone (`magi run`/`review`).
3944    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
3945    pub standalone: bool,
3946    /// Admission state: `"next_poll"`, `"waiting"`, `"running"`, `"completed"`, `"unknown"`.
3947    pub state: &'static str,
3948    /// Human-readable admission status label (e.g. `"Immediate: next poll"`,
3949    /// `"Immediate: waiting — ..."`).
3950    pub label: String,
3951    /// Concrete blocker or unconfirmed-state diagnostic when waiting/unknown/resource-blocked.
3952    #[serde(default, skip_serializing_if = "Option::is_none")]
3953    pub blocker: Option<String>,
3954}
3955
3956/// One read-only snapshot of scheduler, worker, cooldown, and interrupt state
3957/// captured once per list or detail request.
3958#[derive(Debug, Clone)]
3959pub struct AdmissionSnapshot {
3960    now: Timestamp,
3961    daemon: std::result::Result<Option<Reading>, String>,
3962    scheduler_running: bool,
3963    active_workers:
3964        std::result::Result<std::collections::BTreeMap<String, (PermitKind, bool)>, String>,
3965    owned_in_flight: Vec<String>,
3966    owned_ordinary_count: usize,
3967    urgent_busy: bool,
3968    cache_service_active: bool,
3969    cooldown_until: std::result::Result<Option<Timestamp>, String>,
3970    interrupt: std::result::Result<Interrupt, String>,
3971}
3972
3973fn read_status_checked(home: &Path) -> std::result::Result<Option<Reading>, String> {
3974    let path = home.join("daemon.json");
3975    match std::fs::read_to_string(&path) {
3976        Ok(body) => serde_json::from_str(&body)
3977            .map(Some)
3978            .map_err(|e| format!("parse {}: {e}", path.display())),
3979        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
3980        Err(e) => Err(format!("read {}: {e}", path.display())),
3981    }
3982}
3983
3984fn read_interrupt_checked(home: &Path) -> std::result::Result<Interrupt, String> {
3985    let path = home.join("scheduler-interrupt.json");
3986    match std::fs::read(&path) {
3987        Ok(body) => {
3988            serde_json::from_slice(&body).map_err(|e| format!("parse {}: {e}", path.display()))
3989        }
3990        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Interrupt::Idle),
3991        Err(e) => Err(format!("read {}: {e}", path.display())),
3992    }
3993}
3994
3995fn skip_reason_label(key: &str) -> String {
3996    match key {
3997        "claim_unavailable" => "claimed by another process".to_owned(),
3998        "reread_failed" => "could not re-read task".to_owned(),
3999        "no_longer_runnable" => "no longer runnable".to_owned(),
4000        "waiting_on_landing" => "waiting on merge/posting approval".to_owned(),
4001        "cooling_down" => "quota cooldown".to_owned(),
4002        "ordinary_capacity" => "no free ordinary slot".to_owned(),
4003        "urgent_capacity" => "urgent slot busy".to_owned(),
4004        "interrupt_gate" => "withheld by active interrupt sequence".to_owned(),
4005        other => other.replace('_', " "),
4006    }
4007}
4008
4009/// Pure read-only companion to [`land_resume_state`]: reads `home` explicitly
4010/// and never abandons or writes any question file.
4011fn land_resume_state_readonly(task: &Task, home: &Path, now: Timestamp) -> LandResume {
4012    if task.sync_only.is_some() {
4013        return LandResume::NotLanding;
4014    }
4015    let Some(run_id) = task.execution_runs().last() else {
4016        return LandResume::NotLanding;
4017    };
4018    let Ok(state) = RunState::load_under(run_id, home) else {
4019        return LandResume::NotLanding;
4020    };
4021    if !state.parked {
4022        return LandResume::NotLanding;
4023    }
4024    let store = ask::Questions::at(home.join("questions"));
4025    if state.status == RunStatus::Landing
4026        && state.land_approval.as_ref().is_some_and(|binding| {
4027            store.get_for_effects(&binding.question).is_ok_and(|q| {
4028                q.run == state.id
4029                    && q.resolution()
4030                        .as_deref()
4031                        .is_some_and(crate::merge_decision::stops)
4032            })
4033        })
4034    {
4035        return LandResume::Ready;
4036    }
4037    if !implementers_match(task, &state) {
4038        return LandResume::NotLanding;
4039    }
4040    let node = if state.status == RunStatus::Landing {
4041        land::APPROVAL_NODE
4042    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
4043        crate::github_text::ASK_NODE
4044    } else {
4045        return LandResume::NotLanding;
4046    };
4047    let waiting = store
4048        .list_for_effects()
4049        .into_iter()
4050        .filter(|q| &q.run == run_id && q.node == node)
4051        .max_by(|a, b| a.id.cmp(&b.id));
4052    let Some(q) = waiting else {
4053        return LandResume::Ready;
4054    };
4055    if !q.status.open() {
4056        if q.resolution().as_deref() == Some(land::REPAIR) {
4057            return if is_working_on(home, &state.id, now) {
4058                LandResume::StillWaiting
4059            } else {
4060                LandResume::NotLanding
4061            };
4062        }
4063        return LandResume::Ready;
4064    }
4065    LandResume::StillWaiting
4066}
4067
4068impl AdmissionSnapshot {
4069    /// Capture scheduler, worker, cooldown, and interrupt state once, read-only.
4070    #[must_use]
4071    pub fn capture(home: &Path, now: Timestamp) -> Self {
4072        let daemon = read_status_checked(home);
4073        let scheduler_running = daemon
4074            .as_ref()
4075            .ok()
4076            .and_then(Option::as_ref)
4077            .is_some_and(|reading| reading.running(now));
4078        let mut cache_service_active = false;
4079        let mut owned_in_flight = Vec::new();
4080        let mut owned_ordinary_count = 0usize;
4081        let mut urgent_busy = false;
4082        let active_workers = match crate::worker::observe_active_detailed(home) {
4083            Ok(entries) => {
4084                let mut map = std::collections::BTreeMap::new();
4085                let mut parse_err = None;
4086                for entry in entries {
4087                    if entry.job.key == "service:daemon-cache" {
4088                        cache_service_active = true;
4089                        continue;
4090                    }
4091                    if entry.job.kind != "task" {
4092                        continue;
4093                    }
4094                    match serde_json::from_value::<TaskWorker>(entry.job.payload) {
4095                        Ok(request) => {
4096                            if !request.standalone {
4097                                owned_in_flight.push(request.task.clone());
4098                                match request.lane {
4099                                    PermitKind::Ordinary => owned_ordinary_count += 1,
4100                                    PermitKind::Urgent => urgent_busy = true,
4101                                    PermitKind::Immediate | PermitKind::None => {}
4102                                }
4103                            }
4104                            map.entry(request.task)
4105                                .and_modify(|existing: &mut (PermitKind, bool)| {
4106                                    if existing.1 && !request.standalone {
4107                                        *existing = (request.lane, request.standalone);
4108                                    }
4109                                })
4110                                .or_insert((request.lane, request.standalone));
4111                        }
4112                        Err(e) => {
4113                            parse_err = Some(format!(
4114                                "invalid task worker payload for {}: {e}",
4115                                entry.job.id
4116                            ));
4117                            break;
4118                        }
4119                    }
4120                }
4121                match parse_err {
4122                    Some(err) => Err(err),
4123                    None => Ok(map),
4124                }
4125            }
4126            Err(e) => Err(format!("{e:#}")),
4127        };
4128        let cooldown_until = read_cooldown(home).map_err(|e| format!("{e:#}"));
4129        let interrupt = read_interrupt_checked(home);
4130        Self {
4131            now,
4132            daemon,
4133            scheduler_running,
4134            active_workers,
4135            owned_in_flight,
4136            owned_ordinary_count,
4137            urgent_busy,
4138            cache_service_active,
4139            cooldown_until,
4140            interrupt,
4141        }
4142    }
4143
4144    fn format_waiting(task: &Task, reason: &str) -> String {
4145        if task.immediate {
4146            format!("Immediate: waiting — {reason}")
4147        } else if task.urgent {
4148            format!("Urgent: waiting — {reason}")
4149        } else {
4150            format!("Waiting — {reason}")
4151        }
4152    }
4153
4154    /// Evaluate admission for `task` using this pre-captured snapshot.
4155    /// Read-only: never mutates queue, run, worker, or question files.
4156    #[must_use]
4157    pub fn evaluate(
4158        &self,
4159        task: &Task,
4160        queue: &Queue,
4161        inv: Option<&crate::blockers::Inventory>,
4162        home: &Path,
4163    ) -> TaskAdmission {
4164        let mode = if task.immediate {
4165            "immediate"
4166        } else if task.urgent {
4167            "urgent"
4168        } else {
4169            "ordinary"
4170        };
4171
4172        if task.status == TaskStatus::Done {
4173            return TaskAdmission {
4174                mode,
4175                reservation_lane: None,
4176                standalone: false,
4177                state: "completed",
4178                label: "Completed".to_owned(),
4179                blocker: None,
4180            };
4181        }
4182
4183        if let Ok(workers) = &self.active_workers
4184            && let Some(&(lane, standalone)) = workers.get(&task.id)
4185        {
4186            let lane_label = lane.label();
4187            let base = if standalone {
4188                format!("Running (standalone, {lane_label} lane)")
4189            } else {
4190                format!("Running ({lane_label} lane)")
4191            };
4192            let resource_blocker = task
4193                .execution_runs()
4194                .last()
4195                .and_then(|run_id| RunState::load_under(run_id, home).ok())
4196                .and_then(|state| state.resource_wait)
4197                .map(|wait| {
4198                    if wait.holder.trim().is_empty() {
4199                        format!("waiting for {}", wait.kind)
4200                    } else {
4201                        format!("waiting for {} ({})", wait.kind, wait.holder)
4202                    }
4203                });
4204            let label = match &resource_blocker {
4205                Some(reason) => format!("{base} — {reason}"),
4206                None => base,
4207            };
4208            return TaskAdmission {
4209                mode,
4210                reservation_lane: Some(lane_label),
4211                standalone,
4212                state: "running",
4213                label,
4214                blocker: resource_blocker,
4215            };
4216        }
4217
4218        if task.status == TaskStatus::Running {
4219            if self.active_workers.is_err() {
4220                let reason = "worker state unreadable".to_owned();
4221                return TaskAdmission {
4222                    mode,
4223                    reservation_lane: None,
4224                    standalone: false,
4225                    state: "unknown",
4226                    label: Self::format_waiting(task, &reason),
4227                    blocker: Some(reason),
4228                };
4229            }
4230            return TaskAdmission {
4231                mode,
4232                reservation_lane: None,
4233                standalone: false,
4234                state: "running",
4235                label: "Running".to_owned(),
4236                blocker: None,
4237            };
4238        }
4239
4240        if task.status == TaskStatus::Blocked {
4241            let waits = inv.map(|i| i.waits_on(task)).unwrap_or_default();
4242            let reason = if !waits.is_empty() {
4243                format!("waiting on dependencies ({})", waits.join(", "))
4244            } else if let Some(block_reason) = &task.block_reason {
4245                format!("blocked ({block_reason})")
4246            } else if !task.blocked_by.is_empty() {
4247                let ids: Vec<_> = task
4248                    .blocked_by
4249                    .iter()
4250                    .map(|id| crate::run::short_of(id))
4251                    .collect();
4252                format!("waiting on dependencies ({})", ids.join(", "))
4253            } else {
4254                "blocked on unresolved dependencies".to_owned()
4255            };
4256            return TaskAdmission {
4257                mode,
4258                reservation_lane: None,
4259                standalone: false,
4260                state: "waiting",
4261                label: Self::format_waiting(task, &reason),
4262                blocker: Some(reason),
4263            };
4264        }
4265
4266        if task.status == TaskStatus::Held {
4267            let reason = match &task.machine_hold_cause {
4268                Some(crate::queue::MachineHoldCause::DiskCapacity { reason, .. }) => {
4269                    format!("disk admission ({reason})")
4270                }
4271                Some(crate::queue::MachineHoldCause::HeadE2e { .. }) => {
4272                    let detail = task
4273                        .hold_reason
4274                        .as_deref()
4275                        .unwrap_or("current head verify.e2e failed");
4276                    format!("head e2e hold ({detail})")
4277                }
4278                None if task.hold_source == Some(crate::queue::HoldSource::Machine) => {
4279                    let detail = task.hold_reason.as_deref().unwrap_or("held by daemon");
4280                    if let Some(rest) = detail.strip_prefix("[resource] ") {
4281                        format!("resource hold ({rest})")
4282                    } else if let Some(rest) = detail.strip_prefix("[config] ") {
4283                        format!("config hold ({rest})")
4284                    } else {
4285                        format!("machine hold ({detail})")
4286                    }
4287                }
4288                None => match task.hold_reason.as_deref() {
4289                    Some(reason) if !reason.trim().is_empty() => format!("held ({reason})"),
4290                    _ => "held (release required)".to_owned(),
4291                },
4292            };
4293            return TaskAdmission {
4294                mode,
4295                reservation_lane: None,
4296                standalone: false,
4297                state: "waiting",
4298                label: Self::format_waiting(task, &reason),
4299                blocker: Some(reason),
4300            };
4301        }
4302
4303        // Runnable (`Queued` | `Failed` | `Parked`): evaluate non-concurrency
4304        // gates first, never claiming dispatchability on unconfirmed state and
4305        // never attributing ordinary/urgent capacity waits to immediate tasks.
4306        if self.active_workers.is_err() {
4307            let reason = "worker state unreadable".to_owned();
4308            return TaskAdmission {
4309                mode,
4310                reservation_lane: None,
4311                standalone: false,
4312                state: "unknown",
4313                label: Self::format_waiting(task, &reason),
4314                blocker: Some(reason),
4315            };
4316        }
4317
4318        if queue.is_claimed(&task.id) {
4319            let reason = "claimed by another process".to_owned();
4320            return TaskAdmission {
4321                mode,
4322                reservation_lane: None,
4323                standalone: false,
4324                state: "waiting",
4325                label: Self::format_waiting(task, &reason),
4326                blocker: Some(reason),
4327            };
4328        }
4329
4330        if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, task) {
4331            let reason = format!("head e2e stop ({})", hold.reason);
4332            return TaskAdmission {
4333                mode,
4334                reservation_lane: None,
4335                standalone: false,
4336                state: "waiting",
4337                label: Self::format_waiting(task, &reason),
4338                blocker: Some(reason),
4339            };
4340        }
4341
4342        let resume = land_resume_state_readonly(task, home, self.now);
4343        if resume == LandResume::StillWaiting {
4344            let reason = "waiting on merge/posting approval".to_owned();
4345            return TaskAdmission {
4346                mode,
4347                reservation_lane: None,
4348                standalone: false,
4349                state: "waiting",
4350                label: Self::format_waiting(task, &reason),
4351                blocker: Some(reason),
4352            };
4353        }
4354        let priority = resume == LandResume::Ready;
4355        let effective_lane = permit_kind(priority, task.immediate, task.urgent);
4356
4357        match &self.interrupt {
4358            Err(_) => {
4359                let reason = "interrupt state unreadable".to_owned();
4360                return TaskAdmission {
4361                    mode,
4362                    reservation_lane: None,
4363                    standalone: false,
4364                    state: "unknown",
4365                    label: Self::format_waiting(task, &reason),
4366                    blocker: Some(reason),
4367                };
4368            }
4369            Ok(interrupt)
4370                if *interrupt != Interrupt::Idle
4371                    && interrupt_gate(interrupt, &self.owned_in_flight, vec![task.clone()])
4372                        .is_empty() =>
4373            {
4374                let reason = "withheld by active interrupt sequence".to_owned();
4375                return TaskAdmission {
4376                    mode,
4377                    reservation_lane: None,
4378                    standalone: false,
4379                    state: "waiting",
4380                    label: Self::format_waiting(task, &reason),
4381                    blocker: Some(reason),
4382                };
4383            }
4384            Ok(_) => {}
4385        }
4386
4387        if effective_lane != PermitKind::None {
4388            match &self.cooldown_until {
4389                Err(_) => {
4390                    let reason = "quota cooldown state unreadable".to_owned();
4391                    return TaskAdmission {
4392                        mode,
4393                        reservation_lane: None,
4394                        standalone: false,
4395                        state: "unknown",
4396                        label: Self::format_waiting(task, &reason),
4397                        blocker: Some(reason),
4398                    };
4399                }
4400                Ok(Some(until)) if self.now < *until => {
4401                    let secs = (until.as_second() - self.now.as_second()).max(1);
4402                    let reason = format!("quota cooldown ({secs}s remaining)");
4403                    return TaskAdmission {
4404                        mode,
4405                        reservation_lane: None,
4406                        standalone: false,
4407                        state: "waiting",
4408                        label: Self::format_waiting(task, &reason),
4409                        blocker: Some(reason),
4410                    };
4411                }
4412                Ok(_) => {}
4413            }
4414        }
4415
4416        if self.cache_service_active {
4417            let reason = "waiting for cache maintenance service".to_owned();
4418            return TaskAdmission {
4419                mode,
4420                reservation_lane: None,
4421                standalone: false,
4422                state: "waiting",
4423                label: Self::format_waiting(task, &reason),
4424                blocker: Some(reason),
4425            };
4426        }
4427
4428        if self.daemon.is_err() {
4429            let reason = "scheduler status unreadable".to_owned();
4430            return TaskAdmission {
4431                mode,
4432                reservation_lane: None,
4433                standalone: false,
4434                state: "unknown",
4435                label: Self::format_waiting(task, &reason),
4436                blocker: Some(reason),
4437            };
4438        }
4439
4440        if self.scheduler_running
4441            && let Ok(Some(reading)) = &self.daemon
4442            && let Some(skip_key) = reading.dispatch_skips.get(&task.id)
4443        {
4444            let stale_capacity_skip = match effective_lane {
4445                PermitKind::None | PermitKind::Immediate => {
4446                    matches!(skip_key.as_str(), "ordinary_capacity" | "urgent_capacity")
4447                }
4448                PermitKind::Urgent => skip_key == "ordinary_capacity",
4449                PermitKind::Ordinary => skip_key == "urgent_capacity",
4450            };
4451            if !stale_capacity_skip {
4452                let reason = skip_reason_label(skip_key);
4453                return TaskAdmission {
4454                    mode,
4455                    reservation_lane: None,
4456                    standalone: false,
4457                    state: "waiting",
4458                    label: Self::format_waiting(task, &reason),
4459                    blocker: Some(reason),
4460                };
4461            }
4462        }
4463
4464        if !self.scheduler_running {
4465            let reason = "scheduler not running".to_owned();
4466            return TaskAdmission {
4467                mode,
4468                reservation_lane: None,
4469                standalone: false,
4470                state: "waiting",
4471                label: Self::format_waiting(task, &reason),
4472                blocker: Some(reason),
4473            };
4474        }
4475
4476        match effective_lane {
4477            PermitKind::Immediate => TaskAdmission {
4478                mode,
4479                reservation_lane: None,
4480                standalone: false,
4481                state: "next_poll",
4482                label: "Immediate: next poll".to_owned(),
4483                blocker: None,
4484            },
4485            PermitKind::None => TaskAdmission {
4486                mode,
4487                reservation_lane: None,
4488                standalone: false,
4489                state: "next_poll",
4490                label: if task.immediate {
4491                    "Immediate: next poll".to_owned()
4492                } else {
4493                    "Decision resume: next poll".to_owned()
4494                },
4495                blocker: None,
4496            },
4497            PermitKind::Urgent => {
4498                if self.urgent_busy {
4499                    let reason = "urgent slot busy".to_owned();
4500                    TaskAdmission {
4501                        mode,
4502                        reservation_lane: None,
4503                        standalone: false,
4504                        state: "waiting",
4505                        label: Self::format_waiting(task, &reason),
4506                        blocker: Some(reason),
4507                    }
4508                } else {
4509                    TaskAdmission {
4510                        mode,
4511                        reservation_lane: None,
4512                        standalone: false,
4513                        state: "next_poll",
4514                        label: "Urgent: next poll".to_owned(),
4515                        blocker: None,
4516                    }
4517                }
4518            }
4519            PermitKind::Ordinary => {
4520                if self.owned_ordinary_count == 0 {
4521                    TaskAdmission {
4522                        mode,
4523                        reservation_lane: None,
4524                        standalone: false,
4525                        state: "next_poll",
4526                        label: "Ordinary: next poll".to_owned(),
4527                        blocker: None,
4528                    }
4529                } else {
4530                    TaskAdmission {
4531                        mode,
4532                        reservation_lane: None,
4533                        standalone: false,
4534                        state: "waiting",
4535                        label: "Queued (ordinary lane)".to_owned(),
4536                        blocker: None,
4537                    }
4538                }
4539            }
4540        }
4541    }
4542}
4543
4544struct DispatchClaim {
4545    task: Task,
4546    claim: crate::queue::Claim,
4547    lane: PermitKind,
4548    permit: Option<tokio::sync::OwnedSemaphorePermit>,
4549}
4550
4551/// Claim and re-read before choosing a lane: a queue listing may predate an
4552/// immediate or urgent toggle. All unsuccessful paths release the claim
4553/// without an attempt.
4554fn claim_dispatch(
4555    queue: &Queue,
4556    candidate: &Task,
4557    cooling_down: bool,
4558    ordinary: &Arc<tokio::sync::Semaphore>,
4559    urgent: &Arc<tokio::sync::Semaphore>,
4560) -> std::result::Result<DispatchClaim, SkipReason> {
4561    let claim = queue
4562        .claim(&candidate.id)
4563        .map_err(|_| SkipReason::ClaimUnavailable)?;
4564    let task = match queue.get(&candidate.id) {
4565        Ok(t) if t.status.runnable() => t,
4566        Ok(_) => return Err(SkipReason::NoLongerRunnable),
4567        Err(e) => {
4568            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
4569            return Err(SkipReason::RereadFailed);
4570        }
4571    };
4572    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
4573        let mut held = task;
4574        hold.apply(&mut held);
4575        record(queue, &mut held);
4576        return Err(SkipReason::NoLongerRunnable);
4577    }
4578    let resume = land_resume_state(&task);
4579    if resume == LandResume::StillWaiting {
4580        return Err(SkipReason::WaitingOnLanding);
4581    }
4582    let priority = resume == LandResume::Ready;
4583    if !priority && cooling_down {
4584        return Err(SkipReason::CoolingDown);
4585    }
4586    // Never borrow an ordinary slot when the single urgent slot is busy.
4587    // Immediate tasks consume neither ordinary nor urgent permits.
4588    // Keep scanning other candidates when either pool has no free slot.
4589    let lane = permit_kind(priority, task.immediate, task.urgent);
4590    let permit = match lane {
4591        PermitKind::None | PermitKind::Immediate => None,
4592        PermitKind::Urgent => Some(
4593            Arc::clone(urgent)
4594                .try_acquire_owned()
4595                .map_err(|_| SkipReason::UrgentCapacity)?,
4596        ),
4597        PermitKind::Ordinary => Some(
4598            Arc::clone(ordinary)
4599                .try_acquire_owned()
4600                .map_err(|_| SkipReason::OrdinaryCapacity)?,
4601        ),
4602    };
4603    // Persist the dispatch order under the claim, before config discovery or
4604    // coordination waits can reorder concurrent starts.
4605    let stamp = Timestamp::now();
4606    let mut task = task;
4607    task.dispatched_at = Some(stamp);
4608    if let Err(e) = queue.modify(&task.id, |t| {
4609        t.dispatched_at = Some(stamp);
4610        true
4611    }) {
4612        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
4613    }
4614    Ok(DispatchClaim {
4615        task,
4616        claim,
4617        lane,
4618        permit,
4619    })
4620}
4621
4622/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
4623/// teardown and cannot skip the teardown on an early return.
4624///
4625/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
4626/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
4627/// land approval that has since been answered is dispatched outside that
4628/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
4629/// the whole point of parking there is that it must not queue behind
4630/// whatever else the loop happens to be running, even at the default of one.
4631/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
4632/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
4633/// these exemptions is still subject to the interrupt gate below, urgent
4634/// included: a land-resume or urgent candidate is exactly as much "something
4635/// else running" as an ordinary one from the interrupt sequence's point of
4636/// view, and letting either slip through while a run is being parked, or
4637/// while the interrupt task itself has the floor, is precisely the second
4638/// run 75dd's own "at most one run, ever, at once" guarantee must never
4639/// allow - see [`Interrupt`]'s own doc.
4640#[derive(Serialize, Deserialize)]
4641struct ServiceWorker {
4642    opts: Opts,
4643    queue: PathBuf,
4644    worktrees_root: PathBuf,
4645    operation: String,
4646}
4647
4648fn load_conductor(home: &Path) -> Result<Conductor> {
4649    match std::fs::read(home.join("conductor-state.json")) {
4650        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
4651        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
4652        Err(error) => Err(error.into()),
4653    }
4654}
4655
4656fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
4657    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
4658        .into_iter()
4659        .map(|c| c.task)
4660        .collect();
4661    let stalled = stalled_tasks(queue, home, Timestamp::now());
4662    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4663    let finished = finished_tasks(queue)
4664        .into_iter()
4665        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4666        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4667        .collect();
4668    let queued = queued_tasks(queue)
4669        .into_iter()
4670        .filter(|t| !live.contains(&t.id))
4671        .collect();
4672    (queued, stalled, finished)
4673}
4674
4675// Separate latest dispatch and worker receipts expose version handoff and skips
4676// without erasing the last completed scan or treating observations as authority.
4677fn retention_service_receipt(
4678    home: &Path,
4679    operation: &str,
4680    phase: &str,
4681    outcome: &str,
4682    detail: &str,
4683    cfg: Option<&Config>,
4684) {
4685    retention_service_receipt_with(
4686        home,
4687        operation,
4688        phase,
4689        outcome,
4690        detail,
4691        cfg,
4692        serde_json::Value::Null,
4693    );
4694}
4695
4696/// [`retention_service_receipt`] plus `extra`: an object whose fields (the
4697/// fold turn's per-outcome counts and cursor, a retention pass's failures) are
4698/// added to the same receipt file rather than to a store of their own.
4699fn retention_service_receipt_with(
4700    home: &Path,
4701    operation: &str,
4702    phase: &str,
4703    outcome: &str,
4704    detail: &str,
4705    cfg: Option<&Config>,
4706    extra: serde_json::Value,
4707) {
4708    if !matches!(operation, "housekeeping" | "disk-pressure" | "fold") {
4709        return;
4710    }
4711    let mut receipt = serde_json::json!({"checked_at": Timestamp::now(),
4712        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4713        "operation": operation, "outcome": outcome, "detail": detail,
4714        "auto_fold": cfg.map(|c| c.disk.auto_fold),
4715        "reclaim_free_bytes": cfg.map(|c| c.disk.reclaim_threshold()),
4716        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4717    if let (Some(receipt), serde_json::Value::Object(extra)) = (receipt.as_object_mut(), extra) {
4718        receipt.extend(extra);
4719    }
4720    if let Err(error) = crate::fold_evidence::atomic_write(
4721        &home.join(format!("source-eviction-{operation}-{phase}.json")),
4722        &serde_json::to_vec(&receipt).expect("service receipt"),
4723    ) {
4724        tracing::warn!("retention service receipt failed: {error:#}");
4725    }
4726}
4727
4728/// What a retention pass reported, for the service receipt: the same report
4729/// `retention.json` holds, reduced to what says whether the pass ran. On a
4730/// platform without process containment this carries the refusal.
4731fn retention_summary(report: &crate::retention::Report) -> serde_json::Value {
4732    let clip = |text: &String| text.chars().take(300).collect::<String>();
4733    serde_json::json!({"retention": {
4734        "checked_at": report.checked_at,
4735        "freed_bytes": report.freed_bytes,
4736        "retired": report.retired,
4737        "retained": report.retained.len(),
4738        "failure_count": report.failures.len(),
4739        "failures": report.failures.iter().take(8).map(clip).collect::<Vec<_>>(),
4740    }})
4741}
4742
4743/// Why the finished-run folding turn exists, and what keeps it safe.
4744///
4745/// `housekeeping` (which folds finished runs through `clean::fold_due`) has
4746/// only ever been admitted on a fully idle machine: it was written as "the
4747/// janitor, called when a task just ended" (e2c10827, "the disk is quiet ...
4748/// folding worktrees and pruning a cache mid-build would race the very compile
4749/// the prune exists to keep"), and the idle gate survived when the loop was
4750/// split into services. Nothing in that reasoning is about folding: it is
4751/// about the shared cache prune, `fold_orphaned_worktrees` (a run that has no
4752/// `run.json` yet is indistinguishable from an orphan) and `worktree_prune`,
4753/// which stay idle-only. Folding a *finished* run is already done beside live
4754/// runs of the same repository by `Runner::fold_losers`, `magi fold` and the
4755/// phone's fold route, because `graph::fold_run_when` takes the run's owner lock
4756/// and execution lease, a per-worktree output lease and the repository
4757/// coordination lease itself, acts on the run record it reloads once it holds
4758/// them (a handover in between cannot be undone), and `clean::eligibility`
4759/// refuses anything a live claim holds. So a queue that is never empty must not
4760/// mean runs are never folded (issue 1275): this turn is admitted exactly where
4761/// housekeeping is not, in bounded passes (`clean::BUSY_FOLD_BOUNDS`).
4762const FOLD_TURN_INTERVAL_SECS: u64 = 120;
4763
4764/// Idle housekeeping: no worker busy and nothing runnable.
4765fn housekeeping_eligible(busy: bool, runnable: bool) -> bool {
4766    !busy && !runnable
4767}
4768
4769/// Exactly the machines [`housekeeping_eligible`] never reaches (see
4770/// [`FOLD_TURN_INTERVAL_SECS`] for why folding may run beside live work),
4771/// and only with a startup configuration that has `auto_fold` on (like the
4772/// cache and fetch services, an unreadable one means no service).
4773fn fold_turn_eligible(busy: bool, runnable: bool, cfg: Option<&Config>) -> bool {
4774    !housekeeping_eligible(busy, runnable) && cfg.is_some_and(|cfg| cfg.disk.auto_fold)
4775}
4776
4777async fn start_service(
4778    home: &Path,
4779    opts: &Opts,
4780    queue: &Queue,
4781    worktrees_root: &Path,
4782    operation: &str,
4783    cfg: Option<&Config>,
4784    busy: bool,
4785) -> Result<()> {
4786    // Fetch policy is live configuration, unlike question recovery capacity.
4787    // Reload before both cadence and eligibility, including disabled -> enabled.
4788    let fetch_cfg = if operation == "fetch" {
4789        match prepare(&opts.repo, opts) {
4790            Ok(cfg) => Some(cfg),
4791            Err(error) => {
4792                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4793                return Ok(());
4794            }
4795        }
4796    } else {
4797        None
4798    };
4799    let cfg = fetch_cfg.as_ref().or(cfg);
4800    let ticks = home.join("service-ticks");
4801    std::fs::create_dir_all(&ticks)?;
4802    let receipt = ticks.join(format!("daemon-{operation}"));
4803    let last = std::fs::read(&receipt)
4804        .ok()
4805        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4806    let interval = match operation {
4807        "disk-pressure" => 30,
4808        "fold" => FOLD_TURN_INTERVAL_SECS,
4809        "chat-goals" | "decisions" => 60,
4810        "cache" => CACHE_CHECK_INTERVAL_SECS,
4811        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4812        _ => opts.poll.as_secs().max(1),
4813    };
4814    let now = Timestamp::now();
4815    if !cache_check_due(last, now, interval) {
4816        retention_service_receipt(
4817            home,
4818            operation,
4819            "dispatch",
4820            "skipped",
4821            "cadence not due",
4822            cfg,
4823        );
4824        return Ok(());
4825    }
4826    let key = format!("service:daemon-{operation}");
4827    let active = crate::worker::active(home)?;
4828    if active.iter().any(|job| job.key == key) {
4829        retention_service_receipt(
4830            home,
4831            operation,
4832            "dispatch",
4833            "skipped",
4834            "service worker already active",
4835            cfg,
4836        );
4837        return Ok(());
4838    }
4839    // Both fold the same runs; the run's owner lock already makes a collision
4840    // harmless, but one of them at a time keeps the receipts unambiguous.
4841    let sibling = match operation {
4842        "housekeeping" => Some("service:daemon-fold"),
4843        "fold" => Some("service:daemon-housekeeping"),
4844        _ => None,
4845    };
4846    if sibling.is_some_and(|sibling| active.iter().any(|job| job.key == sibling)) {
4847        retention_service_receipt(
4848            home,
4849            operation,
4850            "dispatch",
4851            "skipped",
4852            "another finished-run folding service is active",
4853            cfg,
4854        );
4855        return Ok(());
4856    }
4857    let eligible = match operation {
4858        "conductor" => {
4859            let (queued, stalled, finished) = conductor_work(queue, home);
4860            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4861                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4862        }
4863        "maintenance" => {
4864            queue.list().iter().any(|task| {
4865                crate::triage::disk_wait_eligible(task)
4866                    && task
4867                        .disk_checked_at
4868                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4869            }) || Questions::at(home.join("questions"))
4870                .list_for_effects()
4871                .iter()
4872                .any(|q| {
4873                    q.chosen_action().is_some_and(|action| action.maintenance())
4874                        && !home
4875                            .join("choice-actions")
4876                            .join(format!("{}.json", q.id))
4877                            .exists()
4878                })
4879        }
4880        "housekeeping" => housekeeping_eligible(busy, !runnable(queue).is_empty()),
4881        "fold" => fold_turn_eligible(busy, !runnable(queue).is_empty(), cfg),
4882        "cache" => {
4883            !busy
4884                && !runnable(queue).is_empty()
4885                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4886        }
4887        "disk-pressure" => busy,
4888        "fetch" => {
4889            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4890        }
4891        "decisions" => home.join("notifications/task-inquiries").is_dir(),
4892        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4893            .list()
4894            .iter()
4895            .any(|talk| {
4896                talk.status.open()
4897                    && talk.pending.is_empty()
4898                    && talk.pending_attachments.is_empty()
4899                    && talk.goals.iter().any(|goal| goal.active())
4900            }),
4901        _ => false,
4902    };
4903    if !eligible {
4904        retention_service_receipt(
4905            home,
4906            operation,
4907            "dispatch",
4908            "skipped",
4909            match operation {
4910                "housekeeping" => "active work or runnable task queue",
4911                "fold" if cfg.is_none() => "startup configuration unavailable",
4912                "fold" if cfg.is_some_and(|cfg| !cfg.disk.auto_fold) => "auto_fold disabled",
4913                "fold" => "idle machine; housekeeping owns finished-run folding",
4914                _ => "no active work; idle housekeeping owns scan",
4915            },
4916            cfg,
4917        );
4918        return Ok(());
4919    }
4920    retention_service_receipt(
4921        home,
4922        operation,
4923        "dispatch",
4924        "launching",
4925        "eligible and cadence due",
4926        cfg,
4927    );
4928    let request = ServiceWorker {
4929        opts: opts.absolute()?,
4930        queue: std::path::absolute(queue.root())?,
4931        worktrees_root: std::path::absolute(worktrees_root)?,
4932        operation: operation.to_owned(),
4933    };
4934    if let Err(error) = launch_service(home, &key, request).await {
4935        retention_service_receipt(
4936            home,
4937            operation,
4938            "dispatch",
4939            "error",
4940            &format!("worker launch: {error:#}"),
4941            cfg,
4942        );
4943        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4944    }
4945    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4946    Ok(())
4947}
4948
4949/// Hand `request` to a detached `daemon-service` worker reservation.
4950///
4951/// Unit tests have no `magi` executable to pin and exec as a worker, so they
4952/// may run the very same [`run_service_worker`] inline instead (and nothing
4953/// else differs: admission, cadence and receipts above are the production path).
4954async fn launch_service(home: &Path, key: &str, request: ServiceWorker) -> Result<()> {
4955    #[cfg(test)]
4956    if INLINE_SERVICES.with(std::cell::Cell::get) {
4957        return run_service_worker(home, serde_json::to_value(request)?).await;
4958    }
4959    crate::worker::spawn(home, "daemon-service", key, serde_json::to_value(request)?).await?;
4960    Ok(())
4961}
4962
4963#[cfg(test)]
4964thread_local! {
4965    static INLINE_SERVICES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
4966}
4967
4968/// One bounded pass of finished-run folding (`clean::fold_turn`) with its
4969/// per-outcome counts and cursor in the service receipt. It reserves no agent
4970/// seat and takes only the locks `graph::fold_run` takes for one run at a time.
4971async fn fold_service_turn(home: &Path, opts: &Opts) {
4972    let worker = |outcome: &str, detail: &str, cfg: Option<&Config>, extra| {
4973        retention_service_receipt_with(home, "fold", "worker", outcome, detail, cfg, extra);
4974    };
4975    let cfg = match prepare(&opts.repo, opts) {
4976        Ok(cfg) => cfg,
4977        Err(error) => {
4978            worker(
4979                "error",
4980                &format!("configuration: {error:#}"),
4981                None,
4982                serde_json::Value::Null,
4983            );
4984            return;
4985        }
4986    };
4987    if !cfg.disk.auto_fold {
4988        worker(
4989            "skipped",
4990            "auto_fold disabled",
4991            Some(&cfg),
4992            serde_json::Value::Null,
4993        );
4994        return;
4995    }
4996    worker(
4997        "running",
4998        "finished-run fold turn",
4999        Some(&cfg),
5000        serde_json::Value::Null,
5001    );
5002    let turn = clean::fold_turn(
5003        &home.join("runs"),
5004        home,
5005        &cfg.disk,
5006        Timestamp::now(),
5007        clean::BUSY_FOLD_BOUNDS,
5008    )
5009    .await;
5010    if turn.folded > 0 || turn.failed > 0 || turn.unreadable > 0 {
5011        tracing::info!(
5012            folded = turn.folded,
5013            failed = turn.failed,
5014            unreadable = turn.unreadable,
5015            "housekeep: finished-run fold turn"
5016        );
5017    }
5018    worker(
5019        "completed",
5020        "finished-run fold turn",
5021        Some(&cfg),
5022        serde_json::json!({ "fold": turn }),
5023    );
5024}
5025
5026/// Finite maintenance jobs survive scheduler replacement without duplicating
5027/// agent calls or cancelling an operation between its effect and receipt.
5028pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
5029    let request: ServiceWorker = serde_json::from_value(payload)?;
5030    let opts = &request.opts;
5031    let queue = Queue::at(request.queue);
5032    let questions = Questions::at(home.join("questions"));
5033    match request.operation.as_str() {
5034        "decisions" => crate::chat_control::retire_obsolete_decisions(&queue, home).await?,
5035        "chat-goals" => {
5036            let talks = crate::talk::Talks::at(home.join("talks"));
5037            crate::chat_goal_runtime::sweep(&talks, false).await;
5038        }
5039        "maintenance" => {
5040            apply_maintenance_choices(&queue, &questions, home).await;
5041            triage::monitor_disk_waits(
5042                &queue,
5043                &questions,
5044                opts.config.as_deref(),
5045                Timestamp::now(),
5046            );
5047        }
5048        "conductor" => {
5049            let path = home.join("conductor-state.json");
5050            let mut conductor = load_conductor(home)?;
5051            let (queued, stalled, finished) = conductor_work(&queue, home);
5052            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
5053                && conductor.worth_a_look(&queue, &stalled, &finished)
5054            {
5055                let cfg = prepare(&opts.repo, opts)?;
5056                conductor
5057                    .maybe_run(
5058                        &cfg,
5059                        &opts.repo,
5060                        &queue,
5061                        &questions,
5062                        home,
5063                        &queued,
5064                        &stalled,
5065                        &finished,
5066                        opts.max_attempts,
5067                    )
5068                    .await;
5069                let temporary = path.with_extension("json.tmp");
5070                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
5071                std::fs::rename(temporary, path)?;
5072            }
5073        }
5074        "fetch" => {
5075            let cfg = prepare(&opts.repo, opts)?;
5076            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
5077                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
5078                tracing::debug!("fetch origins: {outcome:?}");
5079            }
5080        }
5081        "cache" => {
5082            if task_jobs(home)?.is_empty() {
5083                let mut checked = None;
5084                maybe_prune_cache_between_runs(
5085                    &opts.repo,
5086                    opts,
5087                    home,
5088                    &Stop::new(),
5089                    &mut checked,
5090                    Timestamp::now(),
5091                )
5092                .await;
5093            }
5094        }
5095        "disk-pressure" => {
5096            if let Ok(cfg) = prepare(&opts.repo, opts) {
5097                retention_service_receipt(
5098                    home,
5099                    "disk-pressure",
5100                    "worker",
5101                    "running",
5102                    "retention sweep",
5103                    Some(&cfg),
5104                );
5105                let report = crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5106                retention_service_receipt_with(
5107                    home,
5108                    "disk-pressure",
5109                    "worker",
5110                    "retention swept",
5111                    "retention sweep finished; cache cleanup follows",
5112                    Some(&cfg),
5113                    retention_summary(&report),
5114                );
5115                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
5116                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
5117                }
5118                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
5119                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
5120                }
5121                for current in current_work(home, Timestamp::now()) {
5122                    if let Ok(state) = RunState::load_under(&current.run, home)
5123                        && let Some(reason) = disk_gate(&state.repo, &state.config)
5124                    {
5125                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
5126                            job.key.strip_prefix("task:") == Some(current.task.as_str())
5127                        }) {
5128                            request_task_park(
5129                                home,
5130                                &job,
5131                                crate::run::ParkCause::Interrupt {
5132                                    reason: reason.clone(),
5133                                },
5134                            )?;
5135                        }
5136                        notices::raise_in(
5137                            home,
5138                            Notice::warn(
5139                                "disk:pressure",
5140                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
5141                            ),
5142                        );
5143                    }
5144                }
5145            } else {
5146                retention_service_receipt(
5147                    home,
5148                    "disk-pressure",
5149                    "worker",
5150                    "error",
5151                    "configuration could not be loaded",
5152                    None,
5153                );
5154            }
5155        }
5156        "fold" => fold_service_turn(home, opts).await,
5157        "housekeeping" => {
5158            if task_jobs(home)?.is_empty() {
5159                match prepare(&opts.repo, opts) {
5160                    Ok(cfg) => {
5161                        retention_service_receipt(
5162                            home,
5163                            "housekeeping",
5164                            "worker",
5165                            "running",
5166                            "retention sweep",
5167                            Some(&cfg),
5168                        );
5169                        let report =
5170                            crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5171                        retention_service_receipt_with(
5172                            home,
5173                            "housekeeping",
5174                            "worker",
5175                            "retention swept",
5176                            "retention sweep finished; janitor follows",
5177                            Some(&cfg),
5178                            retention_summary(&report),
5179                        );
5180                    }
5181                    Err(error) => retention_service_receipt(
5182                        home,
5183                        "housekeeping",
5184                        "worker",
5185                        "error",
5186                        &format!("configuration: {error:#}"),
5187                        None,
5188                    ),
5189                }
5190                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
5191                resweep_superseded_attempts(&queue, home);
5192                triage_held(&queue, home, opts).await;
5193            } else {
5194                retention_service_receipt(
5195                    home,
5196                    "housekeeping",
5197                    "worker",
5198                    "skipped",
5199                    "task worker became active",
5200                    None,
5201                );
5202            }
5203        }
5204        operation => bail!("unknown daemon service {operation}"),
5205    }
5206    Ok(())
5207}
5208
5209/// Only a different request under the same key is a dispatch handoff race.
5210/// Our own unacknowledged reservation is a startup failure, not competing work:
5211/// stop dispatch without fencing it, so an already detached child may still run.
5212fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
5213    let key = format!("task:{}", request.task);
5214    let payload = serde_json::to_value(request)?;
5215    if crate::worker::active(home)?
5216        .iter()
5217        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
5218    {
5219        tracing::warn!(
5220            "task {} acquired a competing worker reservation: {error:#}",
5221            crate::run::short_of(&request.task)
5222        );
5223        return Ok(());
5224    }
5225    tracing::error!("task worker startup stopped dispatch: {error:#}");
5226    notices::raise_in(
5227        home,
5228        Notice::error(
5229            "loop:worker-startup",
5230            // Startup diagnostics may contain private child-process details;
5231            // keep them in the local error/log rather than the chat or notifier.
5232            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),
5233        ).link(Link::Task { id: request.task.clone() }),
5234    );
5235    Err(error).with_context(|| {
5236        format!(
5237            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
5238            crate::run::short_of(&request.task)
5239        )
5240    })
5241}
5242
5243async fn poll(
5244    opts: &Opts,
5245    queue: &Queue,
5246    status: &Arc<Mutex<Status>>,
5247    home: &Path,
5248    worktrees_root: &Path,
5249    stop: &Stop,
5250    limits: DispatchLimits,
5251) -> Result<()> {
5252    let mut attempted = Vec::new();
5253    let mut settling_once_services = false;
5254    let interrupt_path = home.join("scheduler-interrupt.json");
5255    let mut interrupt = match std::fs::read(&interrupt_path) {
5256        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
5257        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
5258        Err(error) => return Err(error.into()),
5259    };
5260    let mut previous = std::collections::BTreeSet::<String>::new();
5261    let mut previous_skips = DispatchSkips::new();
5262    while !stop.stopped() {
5263        let jobs: Vec<_> = crate::worker::active(home)?
5264            .into_iter()
5265            .filter(|job| job.kind == "task")
5266            .collect();
5267        let requests: Vec<_> = jobs
5268            .iter()
5269            .map(|job| {
5270                serde_json::from_value::<TaskWorker>(job.payload.clone())
5271                    .with_context(|| format!("read live task worker {}", job.id))
5272            })
5273            .collect::<Result<_>>()?;
5274        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
5275        let owned: std::collections::BTreeSet<_> = requests
5276            .iter()
5277            .filter(|r| !r.standalone)
5278            .map(|r| r.task.clone())
5279            .collect();
5280        let current: Vec<_> = requests
5281            .iter()
5282            .zip(&jobs)
5283            .filter(|(request, _)| !request.standalone)
5284            .map(|(request, job)| Current {
5285                worker: Some(job.id.clone()),
5286                task: request.task.clone(),
5287                run: queue
5288                    .get(&request.task)
5289                    .ok()
5290                    .and_then(|task| task.execution_runs().last().cloned())
5291                    .unwrap_or_default(),
5292            })
5293            .collect();
5294        {
5295            let mut snapshot = lock(status);
5296            snapshot.polls += 1;
5297            snapshot.completed += previous.difference(&owned).count();
5298            snapshot.current = current;
5299            snapshot.idle = owned.is_empty();
5300            snapshot.dispatch_wait = None;
5301        }
5302        previous = owned.clone();
5303        stop.busy.store(owned.len(), Ordering::SeqCst);
5304
5305        // Slots are reconstructed from durable reservations and OS-held worker
5306        // leases, not this scheduler's lifetime or mutable task urgency.
5307        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
5308        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
5309        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
5310        let mut permits = Vec::new();
5311        sweep_stale_claims(queue, STALE_CLAIM);
5312        reclaim_orphaned_running(queue, opts.max_attempts, &live);
5313        reclaim_abandoned_runs(home, Timestamp::now());
5314        let questions = Questions::at(home.join("questions"));
5315
5316        // Deterministic: no model, run before the conductor sees anything so
5317        // its input reflects the queue's current, already-resolved state.
5318        crate::task_chat::sweep(
5319            queue,
5320            &crate::talk::Talks::at(home.join("talks")),
5321            &questions,
5322            home,
5323        );
5324        if let Err(error) = crate::task_inquiry::Outbox::at(home)
5325            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
5326        {
5327            tracing::warn!("task inquiry delivery remains pending: {error:#}");
5328        }
5329        repair_choice_offers(&questions);
5330        resolve_blockers(queue, &questions);
5331        apply_task_choice_actions(queue, &questions, home);
5332        triage::apply_answers(queue, &questions);
5333        reconcile_task_questions(queue, &questions);
5334        let talks = crate::talk::Talks::at(home.join("talks"));
5335        crate::chat_notify::sweep(queue, &talks, home);
5336        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
5337        crate::chat_watch::sweep(home, &talks);
5338        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
5339            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
5340        }
5341        let mut turns = tokio::task::JoinSet::new();
5342        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
5343        // start_turns dispatches detached turns; no paid work lives in this set.
5344        while turns.join_next().await.is_some() {}
5345
5346        crate::consult::start_services(
5347            home,
5348            &opts.repo,
5349            limits.recovery_cfg.as_ref(),
5350            opts.config.as_deref(),
5351        )
5352        .await?;
5353        for operation in [
5354            "conductor",
5355            "maintenance",
5356            "housekeeping",
5357            "disk-pressure",
5358            "fold",
5359            "cache",
5360            "fetch",
5361            "chat-goals",
5362            "decisions",
5363        ] {
5364            // Once an idle --once drain starts settling services, subsequent
5365            // scans only consume their effects. An expired cadence receipt
5366            // must not start another service and keep the drain alive.
5367            if settling_once_services {
5368                break;
5369            }
5370            if operation == "chat-goals" && stop.parking() {
5371                continue;
5372            }
5373            start_service(
5374                home,
5375                opts,
5376                queue,
5377                worktrees_root,
5378                operation,
5379                limits.recovery_cfg.as_ref(),
5380                !live.is_empty(),
5381            )
5382            .await?;
5383        }
5384        let latest = crate::worker::active(home)?;
5385        if latest.iter().any(|job| job.key == "service:daemon-cache")
5386            || latest
5387                .iter()
5388                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
5389        {
5390            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5391            continue;
5392        }
5393        let candidates: Vec<Task> = runnable(queue)
5394            .into_iter()
5395            .filter(|task| !live.contains(&task.id))
5396            .filter(|task| !opts.once || !attempted.contains(&task.id))
5397            .collect();
5398        let in_flight: Vec<_> = owned.iter().cloned().collect();
5399        let prior_interrupt = std::mem::discriminant(&interrupt);
5400        interrupt = advance_interrupt_tick(
5401            limits.pause_for_interrupts,
5402            interrupt,
5403            &in_flight,
5404            &candidates,
5405        );
5406        // Same-variant transitions preserve their identities. Only an actual
5407        // transition needs a durable write, atomically before sending controls.
5408        if prior_interrupt != std::mem::discriminant(&interrupt) {
5409            let temporary = interrupt_path.with_extension("json.tmp");
5410            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
5411            std::fs::rename(temporary, &interrupt_path)?;
5412        }
5413        if let Interrupt::Parking {
5414            parked,
5415            interrupt_task,
5416        } = &interrupt
5417        {
5418            for job in jobs.iter().filter(|job| {
5419                parked
5420                    .iter()
5421                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
5422            }) {
5423                if crate::worker::control(home, &job.key)?.is_none() {
5424                    request_task_park(
5425                        home,
5426                        job,
5427                        crate::run::ParkCause::Interrupt {
5428                            reason: format!(
5429                                "task {} asked to run first",
5430                                crate::run::short_of(interrupt_task)
5431                            ),
5432                        },
5433                    )?;
5434                }
5435            }
5436        }
5437        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
5438        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
5439        let mut skips = interrupt_skips(&candidate_ids, &candidates);
5440        // Stable-partition immediate candidates ahead of non-immediate ones
5441        // for this poll scan only; shared `dispatch_order` stays unchanged so
5442        // upgrade-resume and ordinary priority ordering are preserved.
5443        let (mut immediate_candidates, other_candidates): (Vec<Task>, Vec<Task>) =
5444            candidates.into_iter().partition(|task| task.immediate);
5445        immediate_candidates.extend(other_candidates);
5446        let candidates = immediate_candidates;
5447        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
5448        let mut known_jobs: std::collections::BTreeSet<String> =
5449            jobs.iter().map(|job| job.id.clone()).collect();
5450        let mut started = false;
5451        let mut resync = false;
5452        for candidate in candidates {
5453            if stop.stopped() {
5454                break;
5455            }
5456            let DispatchClaim {
5457                task,
5458                claim,
5459                lane,
5460                permit,
5461            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
5462                Ok(claim) => claim,
5463                Err(reason) => {
5464                    skips.insert((candidate.id, reason));
5465                    continue;
5466                }
5467            };
5468            if crate::worker::active(home)?
5469                .iter()
5470                .any(|job| job.kind == "task" && !known_jobs.contains(&job.id))
5471            {
5472                drop(claim);
5473                resync = true;
5474                break;
5475            }
5476            let request = TaskWorker {
5477                opts: opts.absolute()?,
5478                queue: std::path::absolute(queue.root())?,
5479                task: task.id.clone(),
5480                lane,
5481                standalone: false,
5482            };
5483            // Keep the claim until spawn acknowledges the worker's durable
5484            // reservation. The worker then claims and re-reads before attempt.
5485            let job = match crate::worker::spawn(
5486                home,
5487                "task",
5488                &format!("task:{}", task.id),
5489                serde_json::to_value(&request)?,
5490            )
5491            .await
5492            {
5493                Ok(job) => job,
5494                Err(error) => {
5495                    task_worker_spawn_error(home, &request, error)?;
5496                    drop(claim);
5497                    resync = true;
5498                    break;
5499                }
5500            };
5501            known_jobs.insert(job.id);
5502            drop(claim);
5503            permits.extend(permit);
5504            attempted.push(task.id);
5505            started = true;
5506            // Interrupt transitions depend on the exact in-flight set (in
5507            // particular the transition from zero to one worker). Re-scan
5508            // before admitting another task, as for ordinary dispatch.
5509            if limits.pause_for_interrupts || lane != PermitKind::Immediate {
5510                break;
5511            }
5512        }
5513        if !resync && !stop.stopped() {
5514            let per_task_skips: std::collections::BTreeMap<String, String> = skips
5515                .iter()
5516                .map(|(id, reason)| (id.clone(), reason.key().to_owned()))
5517                .collect();
5518            {
5519                let mut snapshot = lock(status);
5520                snapshot.dispatch_skips = per_task_skips;
5521                if !started {
5522                    snapshot.dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
5523                }
5524            }
5525            if changed_dispatch_skips(&mut previous_skips, skips) {
5526                if previous_skips.is_empty() {
5527                    tracing::info!("dispatch skips cleared");
5528                }
5529                for (task, reason) in &previous_skips {
5530                    tracing::info!(
5531                        task,
5532                        reason = reason.key(),
5533                        "task {} skipped: {}",
5534                        crate::run::short_of(task),
5535                        reason.describe()
5536                    );
5537                }
5538            }
5539        }
5540        if started || resync {
5541            continue;
5542        }
5543        if owned.is_empty() && opts.once {
5544            settling_once_services = true;
5545            // These finite services can own queue claims or publish answers.
5546            // A skipped claim is not an idle queue until they have finished;
5547            // scan again afterwards so their changes are actually scheduled.
5548            if crate::worker::active(home)?.iter().any(|job| {
5549                job.kind == "daemon-service"
5550                    && matches!(
5551                        job.key.as_str(),
5552                        "service:daemon-housekeeping"
5553                            | "service:daemon-conductor"
5554                            | "service:daemon-maintenance"
5555                    )
5556            }) {
5557                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5558                continue;
5559            }
5560            break;
5561        }
5562        stop.idle(if live.is_empty() {
5563            opts.poll
5564        } else {
5565            RECHECK_WHILE_BUSY.min(opts.poll)
5566        })
5567        .await;
5568    }
5569    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
5570    // every queue claim and Runner driver lease through outcome settlement.
5571    stop.busy.store(0, Ordering::SeqCst);
5572    {
5573        let mut snapshot = lock(status);
5574        snapshot.dispatch_wait = None;
5575        snapshot.dispatch_skips.clear();
5576    }
5577    Ok(())
5578}
5579
5580/// A maintenance pass may briefly own the same record while a worker starts.
5581/// Wait without blocking the executor or charging an agent attempt, then read
5582/// ownership again under the acquired lock. Other I/O failures still fail closed.
5583async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
5584    let busy = |error: &anyhow::Error| {
5585        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
5586            error.kind() == std::io::ErrorKind::WouldBlock
5587                || cfg!(windows) && error.raw_os_error() == Some(33)
5588        })
5589    };
5590    match crate::pr_head::owner_lock(home, id) {
5591        Ok(lock) => return Ok(lock),
5592        Err(error) if busy(&error) => {}
5593        Err(error) => return Err(error),
5594    }
5595    let wait = RunState::load_under(id, home)?
5596        .config
5597        .graph
5598        .timeout_resource_wait;
5599    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
5600}
5601
5602/// Historical successors do not revoke a still-resumable public owner. Scan
5603/// under the same lock as publication/driver claims, and fail closed on unknown
5604/// history before spending another attempt.
5605pub(crate) async fn public_resume_owner(
5606    home: &Path,
5607    runs: &[String],
5608    repo: &Path,
5609) -> Result<Option<RunState>> {
5610    let mut owner = None;
5611    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
5612        let _lock = resume_owner_lock(home, id).await?;
5613        let state = RunState::load_under(id, home)?;
5614        if state.released()
5615            || state.retired_to.is_some()
5616            || state.pr_taken_over_by.is_some()
5617            || !crate::handover::landing_checkpoint(&state)
5618        {
5619            continue;
5620        }
5621        anyhow::ensure!(
5622            crate::git::toplevel(&state.repo).await?.canonicalize()?
5623                == crate::git::toplevel(repo).await?.canonicalize()?,
5624            "public owner repository differs; inspect run lineage"
5625        );
5626        anyhow::ensure!(
5627            owner.is_none(),
5628            "multiple retained public owners; inspect run lineage"
5629        );
5630        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
5631            anyhow::bail!(reason.diagnostic(&state));
5632        }
5633        let claimed = is_working_on_other(home, id, Timestamp::now())?;
5634        anyhow::ensure!(
5635            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
5636            "public owner's driver is live or unknown; wait before retrying"
5637        );
5638        owner = Some(state);
5639    }
5640    Ok(owner)
5641}
5642
5643/// Run one claimed task to a terminal status and record the outcome.
5644///
5645/// Every transition is flushed to the queue as it happens, so the state on disk
5646/// is what actually occurred rather than what this process still intends to
5647/// write.
5648async fn attempt(
5649    opts: &Opts,
5650    queue: &Queue,
5651    status: &Arc<Mutex<Status>>,
5652    stop: &Stop,
5653    interrupt_pause: crate::graph::Pause,
5654    task: &mut Task,
5655) -> Vec<QuotaLoss> {
5656    if let Some(request) = task.sync_only.clone() {
5657        Box::pin(attempt_sync_only(
5658            queue,
5659            status,
5660            stop,
5661            interrupt_pause,
5662            task,
5663            request,
5664        ))
5665        .await;
5666        return Vec::new();
5667    }
5668    let repo = repo_for(task, &opts.repo);
5669    tracing::info!(
5670        "task {} — {} (repo {})",
5671        task.short(),
5672        task.title,
5673        repo.display()
5674    );
5675
5676    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
5677        Ok(owner) => owner,
5678        Err(e) => {
5679            task.hold_machine(Some(format!(
5680                "Cannot verify existing public owner: {e:#}; no attempt started."
5681            )));
5682            record(queue, task);
5683            return Vec::new();
5684        }
5685    };
5686    let resume_runs = public_owner
5687        .as_ref()
5688        .map(|s| vec![s.id.clone()])
5689        .unwrap_or_else(|| task.execution_runs().to_vec());
5690
5691    // A stop spends no agent resources and uses the saved landing owner.
5692    // Current roster edits, missing attachments or a failed config fetch must
5693    // never turn it into a new implementation, or prevent a PR from closing.
5694    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
5695        && previous
5696            .merge_decision
5697            .as_ref()
5698            .is_some_and(|decision| !decision.closed)
5699        && previous.status != RunStatus::Landing
5700        && !crate::merge_decision::resumable_hold(&previous)
5701    {
5702        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)));
5703        record(queue, task);
5704        return Vec::new();
5705    }
5706    let stop_owner = resume_runs
5707        .last()
5708        .and_then(|id| RunState::load(id).ok())
5709        .filter(|state| {
5710            crate::merge_decision::resumable_hold(state)
5711                || state.status == RunStatus::Landing
5712                    && state.land_approval.as_ref().is_some_and(|binding| {
5713                        Questions::open()
5714                            .get_for_effects(&binding.question)
5715                            .is_ok_and(|q| {
5716                                q.run == state.id
5717                                    && q.resolution()
5718                                        .as_deref()
5719                                        .is_some_and(crate::merge_decision::stops)
5720                            })
5721                    })
5722        });
5723    if let Some(owner) = stop_owner {
5724        let mut runner = match Runner::resume(&owner.id) {
5725            Ok(runner) => runner,
5726            Err(e) => {
5727                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
5728                record(queue, task);
5729                return Vec::new();
5730            }
5731        };
5732        runner.on_pause(stop.pause());
5733        runner.watch_interrupt(interrupt_pause);
5734        let quota_before = runner.state.quota.clone();
5735        let before_start = task.clone();
5736        task.start(owner.id.clone());
5737        if let Err(error) = queue.put(task) {
5738            *task = before_start;
5739            let error = runner.fail_startup("task-start", error);
5740            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5741                task.record_startup_failure(failure.clone());
5742            }
5743            task.hold_manual(Some(format!(
5744                "Could not persist task start; no agents dispatched: {error:#}"
5745            )));
5746            record(queue, task);
5747            return Vec::new();
5748        }
5749        lock(status).current.push(Current {
5750            worker: None,
5751            task: task.id.clone(),
5752            run: owner.id,
5753        });
5754        runner.state.carry_dispatched_resumes(task);
5755        runner.state.next_pass_task_entry = true;
5756        let result = runner.execute().await;
5757        return finish_attempt(
5758            opts.max_attempts,
5759            queue,
5760            task,
5761            &runner.state,
5762            &quota_before,
5763            result,
5764        );
5765    }
5766
5767    if let Some(owner) = &public_owner
5768        && (task.fresh_start || !may_resume_run(owner, task))
5769    {
5770        task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. For a closed unmerged PR with a cancelled approval and selected replacement, use magi task recover-pr {} --retire-closed-run {} --cancelled-decision <inquiry-id>. No attempt started.", owner.id, task.id, owner.id)));
5771        record(queue, task);
5772        return Vec::new();
5773    }
5774
5775    if let Some(state) = task
5776        .execution_runs()
5777        .last()
5778        .and_then(|id| RunState::load(id).ok())
5779        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
5780    {
5781        task.hold_machine(Some(reason));
5782        record(queue, task);
5783        return Vec::new();
5784    }
5785
5786    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
5787        && !task.fresh_start
5788        && task.pr_recovery.is_none()
5789    {
5790        // A pinned infrastructure resume continues the saved reservation;
5791        // it does not authorize another base-sync interval.
5792        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
5793            && task.review_branch.is_none()
5794            && task.assignment_accepts(&held)
5795            && compatible_run_instruction(&held, task)
5796            && task
5797                .resume_override
5798                .as_ref()
5799                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
5800        // Exhaustion authorization still takes the owner lock and execution
5801        // lease and rechecks liveness, retained HEAD and ownership.
5802        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
5803        {
5804            true
5805        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
5806            let home = queue.root().parent().expect("queue has a home");
5807            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
5808                Ok(()) => true,
5809                Err(error) => {
5810                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
5811                    false
5812                }
5813            }
5814        } else {
5815            false
5816        };
5817        if !authorized {
5818            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())));
5819            // Retain the existing stop identity when an old release reached the queue.
5820            task.base_sync_notice(&held);
5821            task.resume_override = None;
5822            record(queue, task);
5823            return Vec::new();
5824        }
5825    }
5826    if !task.fresh_start && task.pr_recovery.is_none() {
5827        let home = queue.root().parent().expect("queue has a home");
5828        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
5829            crate::land_sync_recovery::dispatch_check(queue, home, task).await
5830        {
5831            task.hold_machine(Some(reason));
5832            task.land_sync_notice(state.as_ref());
5833            task.resume_override = None;
5834            record(queue, task);
5835            return Vec::new();
5836        }
5837    }
5838    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
5839        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
5840            hold.apply(task);
5841            record(queue, task);
5842            return Vec::new();
5843        }
5844        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
5845            run,
5846            stop_id,
5847            generation,
5848            approval_at,
5849        }) => Some((run, stop_id, generation, approval_at)),
5850        None => None,
5851    };
5852    let unfinished = (!task.fresh_start)
5853        .then(|| unfinished_run(&resume_runs, task.short()))
5854        .flatten()
5855        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
5856    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
5857    if task.repair_grants.last().is_some_and(|receipt| {
5858        task.execution_runs().last() == Some(&receipt.request.run)
5859            && task.operator_decided_at == receipt.decision
5860            && previous
5861                .as_ref()
5862                .is_none_or(|run| run.id != receipt.request.run)
5863    }) {
5864        task.hold_unrequested_retry(Some(
5865            "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(),
5866        ));
5867        record(queue, task);
5868        return Vec::new();
5869    }
5870    if let Some(id) = &task.disk_resume_run
5871        && unfinished.as_ref() != Some(id)
5872    {
5873        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()));
5874        record(queue, task);
5875        return Vec::new();
5876    }
5877
5878    if !task.fresh_start
5879        && task.pr_recovery.is_none()
5880        && task.review_branch.is_none()
5881        && task.resume_override.is_none()
5882        && previous
5883            .as_ref()
5884            .is_some_and(|run| run.retired_to.is_some())
5885        && unfinished.is_none()
5886    {
5887        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()));
5888        record(queue, task);
5889        return Vec::new();
5890    }
5891
5892    let saved_recovery = previous.as_ref().filter(|run| {
5893        task.replacement.is_none()
5894            && task.pr_recovery.as_ref().is_some_and(|selected| {
5895                selected
5896                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5897                    .is_ok()
5898                    && selected_starter(selected, Some(run), unfinished.as_deref())
5899                        == Starter::Resume(run.id.clone())
5900            })
5901    });
5902
5903    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
5904    // failure here is the network's or the operator's, not the task's: hold
5905    // without spending an attempt, never fall back to a possibly stale copy.
5906    let explicit = match &task.overrides {
5907        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5908        Some(_) => opts.config.as_deref(),
5909        None => opts.config.as_deref(),
5910    };
5911    let (mut config, layers) = if let Some(run) = saved_recovery {
5912        // A matching resume owns its resolved configuration and evidence;
5913        // current layers and inherited overrides only configure new work.
5914        let mut saved = run.clone();
5915        if let Err(e) = saved.configure_recovery_resume() {
5916            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
5917            record(queue, task);
5918            return Vec::new();
5919        }
5920        (saved.config, Vec::new())
5921    } else {
5922        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
5923            Ok(loaded) => loaded,
5924            Err(e) => {
5925                let reason = format!("[config] {e:#}");
5926                record_config_failure(task, &e);
5927                task.last_error = Some(reason.clone());
5928                task.hold_machine(Some(reason));
5929                record(queue, task);
5930                return Vec::new();
5931            }
5932        };
5933        if let Err(e) = apply_options(&mut config, opts, task) {
5934            task.hold_manual(Some(format!(
5935                "[config] {e:#}; correct the merge override before releasing the task"
5936            )));
5937            record(queue, task);
5938            return Vec::new();
5939        }
5940        if let Some(selected) = &task.pr_recovery
5941            && let Err(e) = selected.configure(&mut config)
5942        {
5943            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
5944            record(queue, task);
5945            return Vec::new();
5946        }
5947        (config, layers)
5948    };
5949    let config_evidence = crate::pr_recovery::ConfigEvidence {
5950        layers,
5951        overrides: task.overrides.clone(),
5952        daemon_merge: task
5953            .overrides
5954            .as_ref()
5955            .is_none_or(|o| o.inherit_daemon_options)
5956            .then(|| opts.merge.clone())
5957            .flatten(),
5958    };
5959    apply_task_implementers(&mut config, task);
5960    if let Some(replacement) = &task.replacement {
5961        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
5962            old.liveness(false) == Liveness::Dead
5963                && old.merge_decision.as_ref().is_some_and(|d| {
5964                    d.closed
5965                        && d.question == replacement.question
5966                        && d.replacement_run.as_ref().is_none_or(|run| {
5967                            task.execution_runs().last() == Some(run)
5968                                && RunState::load(run).is_ok_and(|current| {
5969                                    current.replaces.as_ref().is_some_and(|pin| {
5970                                        pin.question == replacement.question
5971                                            && pin.agent == replacement.agent
5972                                    })
5973                                })
5974                        })
5975                })
5976        });
5977        if !safe {
5978            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()));
5979            record(queue, task);
5980            return Vec::new();
5981        }
5982        match config.agent(&replacement.agent) {
5983            Ok(agent) if crate::agent::installed(agent) => {}
5984            _ => {
5985                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)));
5986                record(queue, task);
5987                return Vec::new();
5988            }
5989        }
5990        config.graph.implementers = 1;
5991        config.graph.land_approval = true;
5992        config.merge.mode = MergeMode::Pr;
5993        config.graph.selected_implementer = Some(replacement.agent.clone());
5994    }
5995    let p = phrases(&config.graph.language);
5996    let start_failed = p.could_not_start;
5997    // Resolve once for both admission and settlement. The inputs are the
5998    // task's explicit sources (never prose), plus an explicit review source's
5999    // current head; review-only runs may rebase later, and neither fact can
6000    // refund a failed automatic generation.
6001    if let Ok(base) =
6002        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
6003            .await
6004        && let Ok(head) =
6005            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
6006    {
6007        let mut inputs = crate::queue::recovery_inputs(&task.sources);
6008        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
6009            let source = crate::git::rev_parse(&repo, branch)
6010                .await
6011                .unwrap_or_default();
6012            inputs.push_str(&format!(";review:{branch}:{source}"));
6013        }
6014        if let Some(reason) = task
6015            .recovery_exhausted(
6016                &head,
6017                &inputs,
6018                task.attempt_limit
6019                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
6020            )
6021            .filter(|_| {
6022                !task.repair_grants.last().is_some_and(|receipt| {
6023                    RunState::load(&receipt.request.run)
6024                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
6025                })
6026            })
6027        {
6028            task.hold_recovery_budget(
6029                reason,
6030                crate::queue::RecoveryAdmission { base: head, inputs },
6031            );
6032            record(queue, task);
6033            return Vec::new();
6034        }
6035        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
6036    }
6037
6038    // A resumable run of this task is carried on, never re-competed. The
6039    // candidates are built and paid for, and a fresh competition races a
6040    // second implementation against them.
6041    //
6042    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
6043    // started 3cbf on the same task a moment later, duplicating two and a
6044    // half hours of agent work. Then b25f stalled on a judge that timed out
6045    // and one that answered with no JSON - `quota: 0`, so nothing the machine
6046    // was to blame for - and 4043 started **one second** later, buying three
6047    // fresh implementations to reach the same panel. `RunStatus::resumable`
6048    // rather than `!done()` is what catches the second case: a stall is
6049    // terminal, and its cheap recovery re-asks only the absent seats.
6050    //
6051    // A load failure is warned about rather than silently read as "not
6052    // resumable": the alternative is exactly what let a schema mismatch on
6053    // run `eba2` fall through to a full re-competition with nobody told why.
6054    // `crate::conduct` is what actually offers a better answer than
6055    // `Runner::start` here (see `Recovery::Review`), once this task's next
6056    // failure shows it up as `held`/`failed` with the run state unreadable.
6057    // Keep a retained review selection intact until disk admission succeeds.
6058    let consume_review = !previous
6059        .as_ref()
6060        .is_some_and(|state| crate::repair_budget::pending(task, state));
6061    let review_branch = consume_review
6062        .then(|| review_branch_for(task, previous.as_ref()))
6063        .flatten();
6064    let branch_exists = match review_branch {
6065        Some(branch) => crate::git::branch_exists(&repo, branch)
6066            .await
6067            .unwrap_or(false),
6068        None => false,
6069    };
6070    // An explicit `magi review <branch>` is reviewed whatever happens to the
6071    // branch unless an explicit implementer change requires fresh work. An
6072    // unfinished run of the same task still wins, so a retry resumes.
6073    let proposed = review_retry_starter(
6074        task,
6075        previous.as_ref(),
6076        review_branch,
6077        branch_exists,
6078        unfinished.as_deref(),
6079    );
6080    let retry_selected = task.replacement.is_some()
6081        && task.resumption.is_some()
6082        && !task.fresh_start
6083        && previous.as_ref().is_some_and(|run| {
6084            run.replaces.is_some()
6085                && ((run.status == RunStatus::Failed && run.viable().is_empty())
6086                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
6087        });
6088    let stop_pin = task
6089        .resume_override
6090        .as_ref()
6091        .filter(|pin| {
6092            Questions::open()
6093                .get_for_effects(&pin.question_id)
6094                .is_ok_and(|q| {
6095                    q.node == land::APPROVAL_NODE
6096                        && q.resolution()
6097                            .as_deref()
6098                            .is_some_and(crate::merge_decision::stops)
6099                })
6100        })
6101        .and_then(|pin| pin.pinned_run.clone());
6102    let granted_run = task.repair_grants.last().and_then(|receipt| {
6103        let state = RunState::load(&receipt.request.run).ok()?;
6104        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
6105    });
6106    let starter = if let Some(run) = granted_run {
6107        Starter::Resume(run)
6108    } else if let Some(owner) = &public_owner {
6109        Starter::Resume(owner.id.clone())
6110    } else if let Some(run) = stop_pin {
6111        // Stop actions resume their exact owner even after seat-count edits;
6112        // they must never fall through to implementation or a takeover.
6113        Starter::Resume(run)
6114    } else if retry_selected {
6115        Starter::Resume(previous.as_ref().unwrap().id.clone())
6116    } else if let Some(selected) = &task.pr_recovery {
6117        if selected
6118            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
6119            .is_ok()
6120        {
6121            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
6122        } else {
6123            Starter::Review(selected.branch.clone())
6124        }
6125    } else {
6126        starter_with_implementers(task, previous.as_ref(), proposed)
6127    };
6128    // A retained execution still writes to its saved output volume. A newer
6129    // repository policy only selects the volume for a fresh run.
6130    let disk_reason = match &starter {
6131        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
6132            || {
6133                RunState::load(id)
6134                    .ok()
6135                    .and_then(|run| disk_gate(&run.repo, &run.config))
6136            },
6137            |run| disk_gate(&run.repo, &run.config),
6138        ),
6139        _ => disk_gate(&repo, &config),
6140    };
6141    if let Some(reason) = disk_reason {
6142        task.notice_cause("disk-space", None, None);
6143        task.last_error = Some(reason.clone());
6144        let disk_checked_at = task.disk_checked_at;
6145        task.hold_machine(Some(reason.clone()));
6146        if matches!(starter, Starter::Resume(_)) {
6147            task.mark_disk_capacity();
6148        } else {
6149            task.mark_startup_disk_capacity();
6150        }
6151        task.disk_checked_at = disk_checked_at;
6152        record(queue, task);
6153        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
6154        notices::raise(
6155            Notice::warn(
6156                &format!("disk:{}", repo.display()),
6157                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
6158            )
6159            .link(Link::Task {
6160                id: task.id.clone(),
6161            }),
6162        );
6163        return Vec::new();
6164    }
6165    let review_branch = if consume_review {
6166        let valid = review_branch.is_some();
6167        task.review_instruction = None;
6168        task.review_branch.take().filter(|_| valid)
6169    } else {
6170        None
6171    };
6172    // An explicit resume pin must never degrade into a new competition or
6173    // takeover, including when its run stops being eligible after the answer.
6174    if let Some(pin) = &task.resume_override
6175        && let Some(run) = &pin.pinned_run
6176        && starter != Starter::Resume(run.clone())
6177    {
6178        let run = run.clone();
6179        task.notice_cause("resume-owner", Some(&run), None);
6180        task.hold_machine(Some(format!(
6181            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
6182            task.id
6183        )));
6184        record(queue, task);
6185        return Vec::new();
6186    }
6187    // Automatic disk recovery resumes its retained run or stops: a changed
6188    // seat count or review branch must not turn it into a new competition.
6189    // No attempt is spent here.
6190    if let Some(run) = &task.disk_resume_run
6191        && starter != Starter::Resume(run.clone())
6192    {
6193        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()));
6194        record(queue, task);
6195        return Vec::new();
6196    }
6197    if task.replacement.is_some()
6198        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
6199        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
6200    {
6201        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()));
6202        record(queue, task);
6203        return Vec::new();
6204    }
6205    if let Some((ref run, ..)) = head_e2e_approval
6206        && starter != Starter::Resume(run.clone())
6207    {
6208        task.hold_machine(Some(format!(
6209            "Conclusive head_e2e stop on run {run} cannot resume safely with current task settings; inspect `magi show {run}` before retrying. No replacement competition was started."
6210        )));
6211        record(queue, task);
6212        return Vec::new();
6213    }
6214    if let Some(reason) = retained_attempt_hold(
6215        task,
6216        &starter,
6217        config.disk.retained_attempt_limit,
6218        RunState::load,
6219    ) {
6220        // The review choice was consumed above. Preserve it across this hold
6221        // so a later release cannot silently become a fresh implementation.
6222        if let Starter::Review(branch) = &starter {
6223            task.review_branch = Some(branch.clone());
6224        }
6225        task.hold_unrequested_retry(Some(reason));
6226        record(queue, task);
6227        return Vec::new();
6228    }
6229    // Absolute paths of the files the task was filed with, re-read from the
6230    // task now so a file attached while it was held reaches a resumed run
6231    // too. A stored name whose file has gone is an error before any agent is
6232    // paid for, never a silent omission the implementer cannot notice.
6233    let attachments = match task_attachments(queue, task) {
6234        Ok(a) => a,
6235        Err(e) => {
6236            task.attempts += 1;
6237            task.fail_startup_target(
6238                "startup-attachments",
6239                e.name.clone(),
6240                format!("{start_failed}{e:#}"),
6241                opts.max_attempts,
6242            );
6243            record(queue, task);
6244            return Vec::new();
6245        }
6246    };
6247    let startup_pause = stop.pause();
6248    let startup_interrupt = interrupt_pause.clone();
6249    let wait = crate::repo_lock::WaitPolicy::new(
6250        Duration::from_secs(config.graph.timeout_resource_wait),
6251        move || startup_pause.parked() || startup_interrupt.parked(),
6252    );
6253    // Startup includes review takeover and recovery. Do not embed its large
6254    // future in both the wait scope and the surrounding attempt stack frame.
6255    let started = wait.scope(Box::pin(async { match &starter {
6256        Starter::Review(_) if task.pr_recovery.is_some() => {
6257            let selected = task.pr_recovery.clone().expect("selected recovery");
6258            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
6259                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
6260                    .await
6261                    .map(|mut r| {
6262                        r.state.attachments = attachments.clone();
6263                        r
6264                    }),
6265                Err(e) => Err(e),
6266            }
6267        }
6268        Starter::Review(branch) => {
6269            tracing::info!(
6270                "task {} reopens `{branch}` as a review-only pass",
6271                task.short()
6272            );
6273            // Every earlier attempt is superseded by the one being minted
6274            // now, so a branch one of them still holds may be taken over.
6275            let takeover = crate::handover::Takeover {
6276                earlier: task.earlier_attempts().to_vec(),
6277                home: crate::run::home(),
6278                choice: take_divergence_answer(branch, &config.merge.remote, task),
6279                task_instruction: Some(instruction_for(task)),
6280            };
6281            Runner::review_taking_over(
6282                &repo,
6283                branch,
6284                config,
6285                Some(takeover),
6286                crate::run::Origin::queue(&task.id),
6287            )
6288            .await
6289        }
6290        Starter::Resume(id) => {
6291            tracing::info!("resuming run {id} rather than competing again");
6292            Runner::resume(id).and_then(|mut r| {
6293                if retry_selected {
6294                    // The explicit queue release retries this same pinned
6295                    // implementation, preserving the attempt and worktrees.
6296                    for candidate in &mut r.state.candidates {
6297                        candidate.failed = None;
6298                        candidate.empty = false;
6299                        candidate.commits = 0;
6300                    }
6301                    r.state.status = RunStatus::Implementing;
6302                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
6303                }
6304                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
6305                    r.state.sources = task.sources.clone();
6306                }
6307                if r.state.prep_failure.is_some() {
6308                    let approval = task
6309                        .resumption
6310                        .as_ref()
6311                        .context("preparation retry requires an explicit task release")?;
6312                    r.retry_preparation(approval.at)?;
6313                }
6314                if let Some(instruction) =
6315                    prepare_instruction(&starter, Some(&r.state.instruction), task)
6316                {
6317                    r.state.instruction = instruction;
6318                }
6319                r.state.attachments = attachments.clone();
6320                if task.replacement.is_some() {
6321                    r.state.config.merge.mode = MergeMode::Pr;
6322                    r.state.config.graph.land_approval = true;
6323                }
6324                // Replacements publish a new PR and ask again. Selected PR
6325                // recoveries keep their saved disposition; ordinary runs can
6326                // retain the task's merge override.
6327                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
6328                    .overrides
6329                    .as_ref()
6330                    .and_then(|o| o.merge.as_deref())
6331                    .and_then(|m| merge_mode(m).ok())
6332                {
6333                    r.state.config.merge.mode = mode;
6334                }
6335                Ok(r)
6336            })
6337        }
6338        Starter::Start => {
6339            if let Some(branch) = &review_branch {
6340                tracing::warn!(
6341                    "conductor chose review for task {} but branch `{branch}` no longer \
6342                     exists; requeuing as a fresh competition instead",
6343                    task.short()
6344                );
6345            }
6346            let instruction = prepare_instruction(&starter, None, task)
6347                .unwrap_or_else(|| task.instruction.clone());
6348            Runner::start_naming(
6349                &repo,
6350                instruction,
6351                &task.title,
6352                config,
6353                crate::run::Origin::queue(&task.id),
6354            )
6355            .await
6356            .map(|mut r| {
6357                r.state.attachments = attachments.clone();
6358                r.state.sources = task.sources.clone();
6359                r
6360            })
6361        }
6362    }})).await;
6363    if let Err(error) = &started
6364        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
6365    {
6366        task.record_startup_failure(failure.clone());
6367    }
6368    let mut runner = match started {
6369        Ok(r) => r,
6370        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6371            let detail = format!("{e:#}");
6372            task.last_error = Some(detail.clone());
6373            if e.is::<crate::build_target::AdmissionDiskWait>()
6374                && let Starter::Review(branch) = &starter
6375                && review_branch.is_some()
6376            {
6377                task.review_branch = Some(branch.clone());
6378                task.review_instruction = Some(task.instruction.clone());
6379            }
6380            if stop.parking() || interrupt_pause.parked() {
6381                let attempts = task.attempts;
6382                task.park(e.to_string());
6383                // Startup has not spent an attempt to refund.
6384                task.attempts = attempts;
6385            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
6386                let disk_checked_at = task.disk_checked_at;
6387                task.hold_machine(Some(detail));
6388                task.mark_startup_disk_capacity();
6389                task.disk_checked_at = disk_checked_at;
6390            } else {
6391                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
6392            }
6393            record(queue, task);
6394            return Vec::new();
6395        }
6396        // A branch an earlier attempt still holds and magi will not release
6397        // by itself is the operator's call, not a failed attempt: hold the
6398        // task with the reason, spend nothing, and say so on the bell.
6399        Err(e) if task.pr_recovery.is_some() => {
6400            task.startup_notice_cause("startup-public-head");
6401            task.attempts += 1;
6402            task.last_error = Some(format!("{start_failed}{e:#}"));
6403            task.hold_unrequested_retry(Some(format!(
6404                "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."
6405            )));
6406            record(queue, task);
6407            return Vec::new();
6408        }
6409        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
6410            let detail = match e.downcast_ref::<crate::handover::Refused>() {
6411                Some(r) => (p.handover_refused)(r),
6412                None => format!("{e:#}"),
6413            };
6414            task.startup_notice_cause("startup-handover");
6415            let reason = format!("{start_failed}{detail}");
6416            task.last_error = Some(reason.clone());
6417            // Consumed above by `take`; keep it so the released task retries
6418            // as a review of this same branch.
6419            let branch = match &starter {
6420                Starter::Review(branch) => Some(branch.clone()),
6421                _ => None,
6422            };
6423            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
6424            // one page; the guidance rides in the reason, fixed per state so a
6425            // re-put never changes the wording and relights it.
6426            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
6427            record(queue, task);
6428            tracing::warn!(
6429                "holding {} for a branch it cannot take over: {e:#}",
6430                task.short()
6431            );
6432            return Vec::new();
6433        }
6434        // A branch that differs between here and the remote in ways magi
6435        // cannot prove are the same change is a decision for the owner, not a
6436        // failed attempt: ask with both sides laid out, spend no attempt, and
6437        // let the answer requeue the task.
6438        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
6439            let d = e
6440                .downcast_ref::<crate::reconcile::Diverged>()
6441                .expect("checked by the guard");
6442            let mut q = ask::Question::new(
6443                task.id.clone(),
6444                crate::reconcile::NODE.to_owned(),
6445                crate::reconcile::SEAT.to_owned(),
6446                d.summary(),
6447                d.detail(),
6448                d.choices(),
6449            );
6450            match Questions::open().put(&mut q) {
6451                Ok(()) => {
6452                    task.last_error = Some(format!("{e:#}"));
6453                    // Consumed above by `take`; the answer has to reach a review
6454                    // of this same branch, so keep pointing the task at it.
6455                    task.review_branch = Some(d.branch.clone());
6456                    task.review_instruction = Some(task.instruction.clone());
6457                    task.block(vec![q.id.clone()], Some(d.summary()));
6458                }
6459                Err(put) => {
6460                    tracing::warn!("could not file the divergence question: {put:#}");
6461                    task.attempts += 1;
6462                    task.fail_startup(
6463                        "startup-question-store",
6464                        format!("{start_failed}{e:#}"),
6465                        opts.max_attempts,
6466                    );
6467                }
6468            }
6469            record(queue, task);
6470            return Vec::new();
6471        }
6472        Err(e) => {
6473            // The answer was stale and nothing was applied: keep pointing at
6474            // the branch so the next attempt asks again against its new tips.
6475            // Nothing went wrong with the task, so no attempt is spent: a
6476            // budget one short of its limit must not hold it instead of
6477            // letting the question be asked again.
6478            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
6479                && let Starter::Review(branch) = &starter
6480            {
6481                task.review_branch = Some(branch.clone());
6482                task.review_instruction = Some(task.instruction.clone());
6483                task.last_error = Some(format!("{start_failed}{e:#}"));
6484                task.status = crate::queue::TaskStatus::Failed;
6485                record(queue, task);
6486                return Vec::new();
6487            }
6488            task.attempts += 1;
6489            task.last_error = Some(format!("{start_failed}{e:#}"));
6490            task.startup_notice_cause("startup-source");
6491            task.hold_unrequested_retry(Some(format!(
6492                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
6493            )));
6494            record(queue, task);
6495            return Vec::new();
6496        }
6497    };
6498    if !matches!(starter, Starter::Resume(_))
6499        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
6500    {
6501        runner
6502            .state
6503            .event("build-cache", format!("{mode} selected by {source}"));
6504    }
6505    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
6506        runner.state.recovery_config = Some(config_evidence);
6507    }
6508    if let Some(replacement) = &task.replacement {
6509        if matches!(starter, Starter::Start) {
6510            runner.state.instruction.push_str(&format!(
6511                "\n\n# Replacement review context\n{}",
6512                replacement.context
6513            ));
6514        }
6515        runner.state.replaces = Some(replacement.clone());
6516        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
6517        if let Ok(mut old) = RunState::load(&replacement.run)
6518            && let Some(d) = &mut old.merge_decision
6519        {
6520            d.replacement_run = Some(runner.state.id.clone());
6521            old.event(
6522                "replacement",
6523                format!(
6524                    "replacement run {} owns the next attempt; old PR remains closed",
6525                    runner.state.id
6526                ),
6527            );
6528            if let Err(e) = old.save() {
6529                let error = runner.fail_startup("replacement-history", e);
6530                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6531                    task.record_startup_failure(failure.clone());
6532                }
6533                task.hold_manual(Some(format!(
6534                    "Could not link replacement history: {error:#}; no agents dispatched"
6535                )));
6536                record(queue, task);
6537                return Vec::new();
6538            }
6539        }
6540    }
6541    runner.state.task_instruction = Some(task.instruction.clone());
6542    // The follow-up depth is fixed now, while the task certainly exists:
6543    // deleting it later must not reset the cap (`crate::followup`).
6544    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
6545    if runner.state.origin_chat.is_none() {
6546        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
6547    }
6548    // A stop that means "park" reaches the graph through this handle.
6549    runner.on_pause(stop.pause());
6550    // `poll`'s interrupt scheduler reaches this one run - and no other -
6551    // through this handle. See `Pause`'s own doc for why these are never
6552    // the same one.
6553    runner.watch_interrupt(interrupt_pause);
6554
6555    // `start` has minted the run, so the task can now point at it. Persisting
6556    // `Running` before `execute` is what makes a crash mid-run legible.
6557    let run = runner.state.id.clone();
6558    let before_start = task.clone();
6559    task.start(run.clone());
6560    if let Err(error) = queue.put(task) {
6561        *task = before_start;
6562        let error = runner.fail_startup("task-start", error);
6563        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6564            task.record_startup_failure(failure.clone());
6565        }
6566        task.hold_manual(Some(format!(
6567            "Could not persist task start; no agents dispatched: {error:#}"
6568        )));
6569        record(queue, task);
6570        return Vec::new();
6571    }
6572    if task.status != TaskStatus::Running {
6573        // Queue::put kept a newer hold or continuation instead of this start.
6574        return Vec::new();
6575    }
6576    lock(status).current.push(Current {
6577        worker: None,
6578        task: task.id.clone(),
6579        run,
6580    });
6581
6582    // `RunState::quota` is the run's whole history across every resume, so
6583    // only what this execution added may arm the cooldown or earn a refund.
6584    let quota_before = runner.state.quota.clone();
6585    runner.state.carry_dispatched_resumes(task);
6586    runner.state.entry_resumption_generation =
6587        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
6588    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
6589        && runner.state.id == run
6590    {
6591        crate::head_e2e_stop::record_consumed_approval(
6592            &mut runner.state,
6593            &task.id,
6594            &stop_id,
6595            generation,
6596            approval_at,
6597        );
6598    }
6599    runner.state.next_pass_task_entry = true;
6600    let result = runner.execute().await;
6601    finish_attempt(
6602        opts.max_attempts,
6603        queue,
6604        task,
6605        &runner.state,
6606        &quota_before,
6607        result,
6608    )
6609}
6610
6611async fn attempt_sync_only(
6612    queue: &Queue,
6613    status: &Arc<Mutex<Status>>,
6614    stop: &Stop,
6615    interrupt: crate::graph::Pause,
6616    task: &mut Task,
6617    request: crate::base_sync_only::Request,
6618) {
6619    let result = async {
6620        anyhow::ensure!(
6621            task.status == TaskStatus::Queued
6622                && task.execution_runs().last() == Some(&request.run)
6623                && task.resume_override.as_ref().is_some_and(
6624                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
6625                ),
6626            "sync-base-only request no longer owns the exact queued run"
6627        );
6628        let mut runner = Runner::resume(&request.run)?;
6629        anyhow::ensure!(
6630            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
6631                .await?
6632                .is_none(),
6633            "the task still has a public execution owner"
6634        );
6635        anyhow::ensure!(
6636            !stop.parking() && !interrupt.parked(),
6637            "paused before base synchronization"
6638        );
6639        let original = task.clone();
6640        task.start(request.run.clone());
6641        task.attempts = original.attempts;
6642        if let Err(error) = queue.put(task) {
6643            *task = original;
6644            return Err(error);
6645        }
6646        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
6647            return Ok(());
6648        }
6649        lock(status).current.push(Current {
6650            worker: None,
6651            task: task.id.clone(),
6652            run: request.run.clone(),
6653        });
6654        runner.on_pause(stop.pause());
6655        runner.watch_interrupt(interrupt);
6656        runner.execute_sync_only(request.clone()).await
6657    }
6658    .await;
6659    if task.sync_only.as_ref() == Some(&request) {
6660        let saved = RunState::load(&request.run).ok();
6661        let detail = result.err().map(|error| {
6662            format!("Base synchronization only: {error:#}; verification was not allowed")
6663        });
6664        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
6665        record(queue, task);
6666    }
6667}
6668
6669/// Settle `task` after its run executed: the verdict, the diagnosis, the
6670/// supersession of earlier attempts and the save. Shared by the loop and by
6671/// `magi run --resume`, so an attempt is counted one way wherever it ran.
6672/// Returns the quota losses this execution added to the run.
6673pub fn finish_attempt(
6674    max_attempts: usize,
6675    queue: &Queue,
6676    task: &mut Task,
6677    state: &RunState,
6678    quota_before: &[QuotaLoss],
6679    result: Result<()>,
6680) -> Vec<QuotaLoss> {
6681    let detail = match result {
6682        Ok(()) => describe(state),
6683        Err(e) => format!("{e:#}"),
6684    };
6685    let fresh = losses_this_attempt(quota_before, &state.quota);
6686    let verdict = Verdict {
6687        status: state.status,
6688        // A run that opened a pull request handed its work over, whatever the
6689        // gate then decided about merging it.
6690        left_pr: state.pr.is_some(),
6691        // Only a rate limit earns the task its attempt back - and only one
6692        // suffered now: a refund justified by a previous session's loss is
6693        // the same mistake as re-arming the cooldown from it. A stalled run
6694        // resumed without hitting quota again therefore spends its attempt,
6695        // like any other failure of the task's own.
6696        quota_hit: !fresh.is_empty(),
6697        // A run that parked was asked to stop; that is not a failure and must
6698        // not spend an attempt, or replacing the binary a few times would
6699        // exhaust a task's budget without an agent ever misbehaving.
6700        parked: state.parked,
6701        // A quota loss that left nothing viable is the same machine fact as a
6702        // `Stalled` quota loss; see `settle`'s doc table.
6703        no_viable_candidates: state.viable().is_empty(),
6704    };
6705    if let Some(replacement) = &state.replaces
6706        && let Some(pr) = &state.pr
6707        && let Ok(mut old) = RunState::load(&replacement.run)
6708        && let Some(d) = &mut old.merge_decision
6709    {
6710        d.replacement_pr = Some(pr.url.clone());
6711        let _ = old.save();
6712    }
6713    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
6714    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
6715        task.hold_unrequested_retry(Some(format!(
6716            "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.",
6717            task.short()
6718        )));
6719    }
6720    if task.status == TaskStatus::Done {
6721        supersede_prior_runs(task, &crate::run::home());
6722    }
6723    record(queue, task);
6724    tracing::info!(
6725        "task {} is {} after run {} ({})",
6726        task.short(),
6727        task.status.as_str(),
6728        state.short(),
6729        label(state.status)
6730    );
6731    fresh
6732}
6733
6734/// A task a hand-started run leaves runnable (failed with attempts to spare,
6735/// or requeued) is **held**: nobody asked for a retry, and a loop starting
6736/// later must not spend agent calls on it. `magi task release` retries.
6737pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
6738    // Parked work (including legacy Failed records with a parked run) is a
6739    // checkpoint or owner handoff, not an unrequested retry.
6740    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
6741        && !awaiting_resume_with(task, RunState::load)
6742        // A run parked on the owner's word about a withheld PR title/body
6743        // resumes via `land_resume_state`, including review-only tasks that
6744        // `awaiting_resume_with` does not consider.
6745        && withheld_text_wait(task).is_none()
6746        && !(task.fresh_start && task.replacement.is_some())
6747    {
6748        let why = task.last_error.clone().map_or_else(
6749            || "the run did not finish".to_owned(),
6750            |e| format!("the run did not finish: {e}"),
6751        );
6752        task.hold_unrequested_retry(Some(format!(
6753            "{why}. It was started by hand, so it is not retried \
6754             automatically; `magi task release` retries it."
6755        )));
6756        record(queue, task);
6757    }
6758}
6759
6760/// Whether an attempt at a task whose newest run is `run` would resume that
6761/// run rather than start a fresh competition. `magi run --resume` hands a run
6762/// to a live loop only when this holds.
6763#[must_use]
6764pub fn loop_would_resume(run: &str) -> bool {
6765    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
6766}
6767
6768/// A loop in another process that is alive right now: a fresh heartbeat in
6769/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
6770/// carries the pid it published (`None` inside when it published none - a
6771/// fresh heartbeat is still evidence of a live loop).
6772///
6773/// The one judgement of "is somebody else serving this queue", shared by the
6774/// web UI's refusal to start a second loop and by `magi run` / `magi review`
6775/// deciding whether to hand a task to the loop. A claim file proves nothing
6776/// here: whether a claim succeeds says nothing about whether its owner lives.
6777#[must_use]
6778pub fn foreign_loop(
6779    reading: Option<&Reading>,
6780    now: Timestamp,
6781    own_pid: u32,
6782) -> Option<Option<u32>> {
6783    let reading = reading.filter(|r| r.running(now))?;
6784    match reading.pid {
6785        Some(pid) if pid == own_pid => None,
6786        pid => Some(pid),
6787    }
6788}
6789
6790fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
6791    reading.worker_protocol != Some(1)
6792        && (foreign_loop(Some(reading), now, own_pid).is_some()
6793            || reading
6794                .pid
6795                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
6796}
6797
6798/// Low-level claimed-task execution shared by the detached standalone worker
6799/// and focused lifecycle fixtures. The caller must retain the queue claim for
6800/// this entire call. CLI callers transfer ownership through
6801/// [`run_detached_claimed`] instead of executing inside their own runtime.
6802///
6803/// The one deliberate difference from the loop: a task the attempt leaves
6804/// runnable (failed with attempts to spare, or requeued) is **held** instead.
6805/// Nobody asked for a retry, and a daemon starting later must not spend agent
6806/// calls re-running a hand-started task behind the operator's back;
6807/// `magi task release` is the explicit retry.
6808pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
6809    run_claimed_until(opts, queue, task, &Stop::new()).await;
6810}
6811
6812async fn run_claimed_until(
6813    opts: &Opts,
6814    queue: &Queue,
6815    task: &mut Task,
6816    stop: &Stop,
6817) -> Vec<QuotaLoss> {
6818    let status = Arc::new(Mutex::new(Status::new()));
6819    // An attempt embeds startup and graph futures. Keep it off the standalone
6820    // caller's stack, on both the initial execution and withheld-text resume.
6821    let mut quota = Box::pin(attempt(
6822        opts,
6823        queue,
6824        &status,
6825        stop,
6826        crate::graph::Pause::new(),
6827        task,
6828    ))
6829    .await;
6830    // A run parked on the owner's word about a withheld PR title/body has no
6831    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
6832    // here with the claim still held, and resume once the question is settled
6833    // (answered, or abandoned at its deadline -> the neutral text).
6834    // A rejected reply files one more question (the gate asks at most twice),
6835    // so after a resume the run may be waiting again: keep going, with a fresh
6836    // limit for the new question. `resumes` bounds it even if a resume parks
6837    // without asking anything new.
6838    let mut resumes = 0;
6839    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
6840        let Some(timeout) = withheld_text_wait(task) else {
6841            break;
6842        };
6843        eprintln!(
6844            "waiting for the owner's answer on a withheld pull request text \
6845             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
6846        );
6847        // The deadline abandons the question itself; the extra margin only
6848        // covers an abandon that could not be saved.
6849        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
6850        let ready = loop {
6851            match land_resume_state(task) {
6852                LandResume::StillWaiting
6853                    if !stop.parking() && std::time::Instant::now() < limit =>
6854                {
6855                    tokio::time::sleep(WITHHELD_POLL).await;
6856                }
6857                LandResume::Ready => break true,
6858                _ => break false,
6859            }
6860        };
6861        if !ready || stop.parking() {
6862            break;
6863        }
6864        resumes += 1;
6865        quota.extend(
6866            Box::pin(attempt(
6867                opts,
6868                queue,
6869                &status,
6870                stop,
6871                crate::graph::Pause::new(),
6872                task,
6873            ))
6874            .await,
6875        );
6876    }
6877    hold_if_runnable(queue, task);
6878    quota
6879}
6880
6881/// Resumes an in-process run makes for withheld-text questions: the gate asks
6882/// at most twice, plus one for a resume that asks nothing new.
6883const MAX_WITHHELD_RESUMES: u32 = 3;
6884
6885/// How often an in-process run rechecks its withheld-text question.
6886const WITHHELD_POLL: Duration = Duration::from_secs(15);
6887
6888/// The `answer_timeout` (seconds) of the task's last run when that run is
6889/// parked on an unresolved withheld-text question; `None` otherwise.
6890fn withheld_text_wait(task: &Task) -> Option<u64> {
6891    let id = task.execution_runs().last()?;
6892    let s = RunState::load(id).ok()?;
6893    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
6894        .then_some(s.config.graph.answer_timeout)
6895}
6896
6897/// The quota losses `after` holds that `before` did not: what one execution
6898/// suffered, as opposed to the run's history.
6899///
6900/// Compared by value rather than by length or position because
6901/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
6902/// the vector can shrink and shift under a resume. A retried seat that hits
6903/// quota again is a `push` with a new `at`, so it shows up as new here.
6904/// Crash recovery uses the recorded pass start as its boundary when available;
6905/// legacy records without passes retain their original history-based policy.
6906fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
6907    after
6908        .iter()
6909        .filter(|q| !before.contains(q))
6910        .cloned()
6911        .collect()
6912}
6913
6914/// When the loop-wide quota cooldown should end, given this attempt's losses;
6915/// `None` when there were none. Reset-hint parsing and the cap live here.
6916fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
6917    let quota: Vec<_> = quota
6918        .iter()
6919        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
6920        .collect();
6921    if quota.is_empty() {
6922        return None;
6923    }
6924    let with_hint = quota.iter().find(|q| q.reset.is_some());
6925    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
6926    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
6927    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
6928    Some(
6929        now.checked_add(jiff::SignedDuration::from_secs(secs))
6930            .unwrap_or(Timestamp::MAX),
6931    )
6932}
6933
6934/// An explicit task count must agree with a run before any resume.
6935fn implementers_match(task: &Task, state: &RunState) -> bool {
6936    task.replacement.as_ref().map_or_else(
6937        || {
6938            task.implementers()
6939                .is_none_or(|n| n == state.config.graph.implementers)
6940        },
6941        |replacement| {
6942            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
6943                && state.config.graph.implementers == 1
6944        },
6945    )
6946}
6947
6948/// Never resume or take over candidate work built for a different seat count.
6949fn starter_with_implementers(
6950    task: &Task,
6951    previous: Option<&RunState>,
6952    proposed: Starter,
6953) -> Starter {
6954    if previous.is_some_and(|s| !implementers_match(task, s)) {
6955        task.review_of
6956            .as_ref()
6957            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
6958    } else {
6959        proposed
6960    }
6961}
6962
6963/// Apply this task's explicit count to the new attempt, without changing defaults.
6964fn apply_task_implementers(config: &mut Config, task: &Task) {
6965    if let Some(n) = task.implementers() {
6966        config.graph.implementers = n;
6967    }
6968}
6969
6970/// [`prepare`] for one task: its own `--config` and command-line overrides
6971/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
6972/// over the loop's, so handing a hand-started task to a daemon changes nothing
6973/// about what it does.
6974#[cfg(test)]
6975fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
6976    let explicit = match &task.overrides {
6977        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6978        _ => opts.config.as_deref(),
6979    };
6980    let (mut config, _) = Config::discover(repo, explicit)?;
6981    apply_options(&mut config, opts, task)?;
6982    Ok(config)
6983}
6984
6985fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
6986    if task
6987        .overrides
6988        .as_ref()
6989        .is_none_or(|o| o.inherit_daemon_options)
6990        && let Some(mode) = opts.merge.as_deref()
6991    {
6992        config.merge.mode = merge_mode(mode)?;
6993    }
6994    if let Some(o) = &task.overrides {
6995        o.apply(config);
6996    }
6997    if let Some((mode, _)) = task.build_cache_override(config) {
6998        config.verify.build_cache = mode;
6999    }
7000    Ok(())
7001}
7002
7003/// Load the config for a task's repository, with the merge override applied.
7004fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
7005    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
7006    if let Some(mode) = &opts.merge {
7007        config.merge.mode = merge_mode(mode)?;
7008    }
7009    Ok(config)
7010}
7011
7012/// Prune the shared build cache at a between-runs boundary. The detached cache
7013/// service checks authoritative task jobs first; dispatch waits for that finite
7014/// service, so scheduler replacement cannot turn a compile into idle cleanup.
7015/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
7016async fn maybe_prune_cache_between_runs(
7017    repo: &Path,
7018    opts: &Opts,
7019    home: &Path,
7020    stop: &Stop,
7021    last_checked: &mut Option<Timestamp>,
7022    now: Timestamp,
7023) {
7024    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
7025        return;
7026    }
7027    *last_checked = Some(now);
7028    let cfg = match prepare(repo, opts) {
7029        Ok(cfg) => cfg,
7030        Err(e) => {
7031            tracing::warn!("cache check: no config: {e:#}");
7032            return;
7033        }
7034    };
7035    match clean::prune_cache_if_over_limit(&cfg, home) {
7036        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
7037            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
7038            pruned.files,
7039            pruned.freed
7040        ),
7041        Ok(_) => {}
7042        Err(e) => {
7043            tracing::warn!("housekeep: prune cache: {e:#}");
7044            notices::raise_in(
7045                home,
7046                Notice::warn(
7047                    "housekeep:cache",
7048                    format!(
7049                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
7050                        e.to_string()
7051                            .lines()
7052                            .next()
7053                            .unwrap_or("unknown cleanup error")
7054                    ),
7055                ),
7056            );
7057        }
7058    }
7059}
7060
7061/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
7062/// now, given when it last did (if ever). Pure, so the cadence is asserted
7063/// directly rather than by waiting out real minutes in a test.
7064fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
7065    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
7066}
7067
7068/// The disk janitor, with its housekeeping logged rather than fatal.
7069///
7070/// Called only at the loop's idle points, for the reason the caller documents:
7071/// a prune racing a live compile would delete files mid-build. The config is
7072/// re-read on every call because the repository that just ran may not be the
7073/// daemon's own default, and the cache directory is a repository fact.
7074///
7075/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
7076/// and [`crate::run::default_worktree_root`] read here, for the same reason
7077/// [`drive`] takes its queue and status file rather than resolving them: a
7078/// test driving the loop must not reach through to the operator's real home
7079/// or worktree bay just because the janitor runs on every idle tick.
7080/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
7081/// to get wrong silently - a test's `home` was already isolated, but nothing
7082/// exercised the parameter next to it, so a real worktree bay stayed wired in
7083/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
7084/// it for real, every test in this file that drives the loop at all started
7085/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
7086async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
7087    let cfg = match prepare(repo, opts) {
7088        Ok(cfg) => cfg,
7089        Err(e) => {
7090            tracing::warn!("housekeep: no config: {e:#}");
7091            return;
7092        }
7093    };
7094    // A run's own worktree lives under `config.graph.worktree_root` when the
7095    // repository sets one - the same precedence `RunState::worktree_root`
7096    // uses - and `worktrees_root` only stands in for the *default* an
7097    // unconfigured repository resolves to (see this function's own
7098    // parameter, or the test fixture wiring one to a fake path). Housekeeping
7099    // that always swept the default regardless of this override would never
7100    // see, and so never reclaim, a single worktree for a repository that
7101    // relocated them elsewhere.
7102    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
7103    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
7104    // Reported whenever there is anything to say, not only when `folded > 0`:
7105    // the incident this exists to prevent was 90 of 93 runs skipped and 0
7106    // folded, on every single pass, for months - a report gated on `folded`
7107    // would have stayed silent through every one of them.
7108    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
7109        let mut extra = Vec::new();
7110        if out.unreadable > 0 {
7111            extra.push(format!("{} unreadable", out.unreadable));
7112        }
7113        if out.orphaned_worktrees > 0 {
7114            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
7115        }
7116        let detail = if extra.is_empty() {
7117            String::new()
7118        } else {
7119            format!(" ({})", extra.join(", "))
7120        };
7121        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
7122    }
7123    if out.external_merges_recorded > 0 {
7124        tracing::info!(
7125            "housekeep: recorded {} run(s) as merged externally",
7126            out.external_merges_recorded
7127        );
7128    }
7129    if out.stale_pr_states_repaired > 0 {
7130        tracing::info!(
7131            "housekeep: rewrote {} run record(s) whose pull request had already settled",
7132            out.stale_pr_states_repaired
7133        );
7134    }
7135    if out.cache_files > 0 {
7136        tracing::info!(
7137            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
7138            out.cache_files,
7139            out.cache_freed
7140        );
7141    }
7142    if out.questions_abandoned > 0 {
7143        tracing::info!(
7144            "housekeep: abandoned {} question(s) left open by a finished run",
7145            out.questions_abandoned
7146        );
7147    }
7148}
7149
7150/// Run [`triage::run_once`] and log whatever it did, the same "only when
7151/// there is something to say" rule [`janitor`] follows for its own report.
7152///
7153/// Called at the same idle points as [`janitor`] - once per full poll
7154/// interval, never mid-attempt - for the same reason: it is not liveness
7155/// critical, and a task's own `hold_reason` string is the one thing this
7156/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
7157/// tick for no benefit.
7158async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
7159    let questions = Questions::at(home.join("questions"));
7160    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
7161    if report.is_empty() {
7162        return;
7163    }
7164    if !report.quarantined.is_empty() {
7165        tracing::info!(
7166            "triage: held {} blocked task(s) whose blocked-on task or \
7167             question no longer exists: {}",
7168            report.quarantined.len(),
7169            report.quarantined.join(", ")
7170        );
7171    }
7172    if !report.resumed.is_empty() {
7173        tracing::info!(
7174            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
7175            report.resumed.len(),
7176            report.resumed.join(", ")
7177        );
7178    }
7179    if !report.asked.is_empty() {
7180        tracing::info!(
7181            "triage: asked about {} held task(s): {}",
7182            report.asked.len(),
7183            report.asked.join(", ")
7184        );
7185    }
7186    if !report.answered.is_empty() {
7187        tracing::info!(
7188            "triage: applied {} operator answer(s): {}",
7189            report.answered.len(),
7190            report.answered.join(", ")
7191        );
7192    }
7193}
7194
7195/// The free-space gate: what stands between this task and a new run, if
7196/// anything. `Some(reason)` holds the task; `None` lets it start.
7197///
7198/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
7199/// the operator opted out. A measurement failure is a gate, not a pass: both
7200/// sides of "cannot tell" are served by not starting.
7201pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
7202    disk_gate_at(repo, config, crate::run::home)
7203}
7204
7205pub(crate) fn disk_gate_at(
7206    repo: &Path,
7207    config: &Config,
7208    home: impl FnOnce() -> PathBuf,
7209) -> Option<String> {
7210    let measure = if crate::build_target::isolated(config) {
7211        crate::disk::managed_free_bytes
7212    } else {
7213        crate::disk::free_bytes
7214    };
7215    disk_gate_with(repo, config, home, measure)
7216}
7217
7218/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
7219/// test can assert the exact wiring `attempt` runs - config's threshold in,
7220/// task-holding reason out - without asking the real machine's disk anything.
7221fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
7222    repo: &Path,
7223    config: &Config,
7224    home: impl FnOnce() -> PathBuf,
7225    free_bytes: F,
7226) -> Option<String> {
7227    let min = config.disk.min_free_bytes;
7228    if min == 0 {
7229        return None;
7230    }
7231    let output = match config.verify.build_cache {
7232        BuildCache::Shared => config.cache_dir(),
7233        BuildCache::Isolated => Some(home()),
7234    };
7235    let default_worktree_root;
7236    let worktree_root = match config.graph.worktree_root.as_deref() {
7237        Some(root) => root,
7238        None => {
7239            default_worktree_root = crate::run::default_worktree_root();
7240            &default_worktree_root
7241        }
7242    };
7243    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
7244        .into_iter()
7245        .flatten()
7246    {
7247        let probe = if path == repo {
7248            path
7249        } else {
7250            path.ancestors().find(|p| p.exists()).unwrap_or(path)
7251        };
7252        let reason = match free_bytes(probe) {
7253            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
7254            Err(e) => Some(crate::disk::unmeasured_in(
7255                probe,
7256                &e,
7257                &config.graph.language,
7258            )),
7259        };
7260        if reason.is_some() {
7261            return reason;
7262        }
7263    }
7264    None
7265}
7266
7267/// How long to wait before offering another task when a run lost a seat to a
7268/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
7269/// could read, or carried nothing at all. Long enough that a quota outage
7270/// cannot burn through a whole backlog in the few seconds each doomed attempt
7271/// takes to fail; short enough that a quota which clears early is not left
7272/// idle for the fallback's sake.
7273const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
7274
7275/// Longest a parsed reset hint may push the wait out to. The hint comes from
7276/// the CLI's own words, not a contract, so a parsing slip that lands a day
7277/// away must not leave the loop asleep for a day.
7278const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
7279
7280/// How long [`poll`] should wait before offering the next task, after a run
7281/// lost at least one seat to a rate limit.
7282///
7283/// Pure and separate from the loop so the policy can be exercised without a
7284/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
7285/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
7286/// nothing to parse, or the parsed time has already passed; `cap` bounds how
7287/// far a parsed hint is trusted to push the wait out.
7288fn quota_wait(
7289    reset_at: Option<Timestamp>,
7290    now: Timestamp,
7291    fallback: Duration,
7292    cap: Duration,
7293) -> Duration {
7294    match reset_at {
7295        Some(at) if at > now => {
7296            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
7297            Duration::from_secs(secs).min(cap)
7298        }
7299        _ => fallback,
7300    }
7301}
7302
7303/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
7304///
7305/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
7306/// explains why parsing it exactly "would be a bug factory" — so this only
7307/// recognises the shapes actually observed in the wild, and returns `None`
7308/// for anything else rather than guess at a format nobody has seen.
7309///
7310/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
7311/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
7312/// said it, not from whenever this loop happens to read it: anchoring on `now`
7313/// would push the reset later on every read and would read an already-elapsed
7314/// reset as still in the future. (A long hint is still clamped by
7315/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
7316fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
7317    parse_reset_hint_zoned(text, now)
7318        .or_else(|| parse_reset_hint_dated(text))
7319        .or_else(|| parse_reset_hint_relative(text, recorded))
7320}
7321
7322/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
7323/// optional but at least one required, in that order. A bare number or any
7324/// unknown unit is refused.
7325fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
7326    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
7327    let mut rest = rest.trim();
7328    if rest.is_empty() {
7329        return None;
7330    }
7331    let mut total: i64 = 0;
7332    let mut matched = false;
7333    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
7334        if let Some((digits, tail)) = rest.split_once(unit)
7335            && !digits.is_empty()
7336            && digits.bytes().all(|b| b.is_ascii_digit())
7337        {
7338            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
7339            rest = tail;
7340            matched = true;
7341        }
7342    }
7343    if !rest.is_empty() || !matched {
7344        return None;
7345    }
7346    recorded
7347        .checked_add(jiff::SignedDuration::from_secs(total))
7348        .ok()
7349}
7350
7351/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
7352/// case-insensitive) into a 24-hour hour and minute. Shared by every
7353/// reset-hint shape below.
7354fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
7355    let clock = clock.trim().to_lowercase();
7356    let (digits, pm) = clock
7357        .strip_suffix("am")
7358        .map(|d| (d, false))
7359        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
7360    let (h, m) = digits.trim().split_once(':')?;
7361    let mut hour: i8 = h.trim().parse().ok()?;
7362    let minute: i8 = m.trim().parse().ok()?;
7363    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
7364        return None;
7365    }
7366    if pm && hour != 12 {
7367        hour += 12;
7368    } else if !pm && hour == 12 {
7369        hour = 0;
7370    }
7371    Some((hour, minute))
7372}
7373
7374/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
7375/// and a zone, never a date. A clock reading already past today is read as
7376/// tomorrow's: a CLI naming a same-day reset that has already gone by means
7377/// the window rolled over while nothing was watching.
7378fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
7379    let open = text.find('(')?;
7380    let close = text.rfind(')')?;
7381    if close <= open {
7382        return None;
7383    }
7384    let zone = text[open + 1..close].trim();
7385    let (hour, minute) = parse_12h_clock(&text[..open])?;
7386    let tz = jiff::tz::TimeZone::get(zone).ok()?;
7387    let candidate = now
7388        .to_zoned(tz)
7389        .with()
7390        .hour(hour)
7391        .minute(minute)
7392        .second(0)
7393        .millisecond(0)
7394        .microsecond(0)
7395        .nanosecond(0)
7396        .build()
7397        .ok()?;
7398    let mut at = candidate.timestamp();
7399    if at <= now {
7400        at += jiff::SignedDuration::from_hours(24);
7401    }
7402    Some(at)
7403}
7404
7405/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
7406/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
7407/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
7408/// "already past today" correction to make: the year already disambiguates
7409/// it. Scanned as a five-word window so it can be pulled out of the middle
7410/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
7411/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
7412/// any other timestamp with no zone attached.
7413fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
7414    let words: Vec<&str> = text.split_whitespace().collect();
7415    if words.len() < 5 {
7416        return None;
7417    }
7418    (0..=words.len() - 5)
7419        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
7420}
7421
7422/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
7423/// parenthesis right after the window is refused rather than ignored — it
7424/// reads as an explicit zone annotation on a shape that otherwise carries
7425/// none, and guessing UTC anyway would be exactly the silent misread this
7426/// module's parsing otherwise avoids.
7427fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
7428    if trailing.is_some_and(|next| next.starts_with('(')) {
7429        return None;
7430    }
7431    let month = month_number(window[0])?;
7432    let day_token = window[1].strip_suffix(',')?.to_lowercase();
7433    let day_digits = ["st", "nd", "rd", "th"]
7434        .iter()
7435        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
7436    let day: i8 = day_digits.parse().ok()?;
7437    let year_token = window[2];
7438    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
7439        return None;
7440    }
7441    let year: i16 = year_token.parse().ok()?;
7442    // The am/pm word carries the sentence's own trailing punctuation, e.g.
7443    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
7444    // reusing the same 12-hour clock reader the bracketed shape uses.
7445    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
7446    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
7447    let date = jiff::civil::Date::new(year, month, day).ok()?;
7448    let candidate = date
7449        .at(hour, minute, 0, 0)
7450        .to_zoned(jiff::tz::TimeZone::UTC)
7451        .ok()?;
7452    Some(candidate.timestamp())
7453}
7454
7455/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
7456/// case-insensitively, into a 1-based month number.
7457fn month_number(name: &str) -> Option<i8> {
7458    const NAMES: [&str; 12] = [
7459        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
7460    ];
7461    let lower = name.to_lowercase();
7462    NAMES
7463        .iter()
7464        .position(|n| *n == lower.as_str())
7465        .map(|i| i as i8 + 1)
7466}
7467
7468/// Test probe for the shared resume policy's review-budget exclusion.
7469#[cfg(test)]
7470fn exhausted_review_budget(state: &RunState) -> bool {
7471    // A run whose task-head publication failed has nothing left to review:
7472    // resuming it only retries the publication, so it is never "exhausted".
7473    !crate::handover::can_resume(state)
7474        && state.status == RunStatus::Blocked
7475        && !state.released()
7476        && state.retired_to.is_none()
7477}
7478
7479/// This task's *most recent* run, if resuming it would actually make
7480/// progress. `short` is only for the warning's own message.
7481///
7482/// Only ever `runs.last()` — never a search back through older history.
7483/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
7484/// mint, oldest first, and every entry before the last one was already
7485/// superseded at the moment it was minted: the daemon only ever starts a new
7486/// run when the previous one was not worth resuming (unresumable, exhausted,
7487/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
7488/// opens a fresh review-only run alongside an older, already-failed
7489/// competition. Searching further back would let an old run that merely
7490/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
7491/// behind, say — get resumed instead of the fresh competition
7492/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
7493/// nothing asked to revisit.
7494///
7495/// Two runs paid for the "prefer resuming over restarting" half of this
7496/// lesson, which is why this still checks `runs.last()` rather than always
7497/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
7498/// task a moment later, duplicating two and a half hours of agent work. Then
7499/// b25f stalled on a judge that timed out and one that answered with no JSON
7500/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
7501/// **one second** later, buying three fresh implementations to reach the
7502/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
7503/// the second case: a stall is terminal, and its cheap recovery re-asks only
7504/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
7505/// that is technically `resumable()` but provably cannot progress must not
7506/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
7507/// no-op instead of the fresh competition it promises.
7508///
7509/// A load failure is warned about rather than silently read as "not
7510/// resumable": the alternative is exactly what let a schema mismatch on run
7511/// `eba2` fall through to a full re-competition with nobody told why.
7512/// `crate::conduct` is what actually offers a better answer than
7513/// `Runner::start` here (see `Recovery::Review`), once this task's next
7514/// failure shows it up as `held`/`failed` with the run state unreadable.
7515fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
7516    unfinished_run_with(runs, short, RunState::load)
7517}
7518
7519/// [`unfinished_run`] with an injected state reader. Tests provide their
7520/// fixtures directly rather than touching the process-global run home.
7521pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
7522where
7523    F: FnMut(&str) -> Result<RunState>,
7524{
7525    let mut id = runs.last()?.clone();
7526    let mut visited = std::collections::BTreeSet::new();
7527    let mut repo = None;
7528    loop {
7529        if !runs.contains(&id) || !visited.insert(id.clone()) {
7530            tracing::warn!("invalid or cyclic recovery authority for task {short}");
7531            return None;
7532        }
7533        let state = match load(&id) {
7534            Ok(state) if state.id == id => state,
7535            Ok(_) => return None,
7536            Err(e) => {
7537                tracing::warn!("could not read run {id} for task {short}: {e:#}");
7538                return None;
7539            }
7540        };
7541        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
7542            return None;
7543        }
7544        repo = Some(state.repo.clone());
7545        if let Some(authority) = state.retired_to {
7546            id = authority;
7547            continue;
7548        }
7549        return (crate::handover::can_resume(&state)
7550            && state.liveness(false) != crate::run::Liveness::Live)
7551            .then_some(id);
7552    }
7553}
7554
7555/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
7556/// that [`attempt`] will resume it on its own?
7557///
7558/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
7559/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
7560/// injected reader like its sibling. An unreadable run is not awaiting
7561/// anything: it keeps going to the conductor as before.
7562fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
7563where
7564    F: FnOnce(&str) -> Result<RunState>,
7565{
7566    // `Failed` stays: a record an older build wrote for a parked run.
7567    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
7568        || task.fresh_start
7569        || task.review_branch.is_some()
7570    {
7571        return false;
7572    }
7573    let Some(id) = task.execution_runs().last() else {
7574        return false;
7575    };
7576    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
7577}
7578
7579/// Which of the three ways [`attempt`] can mint or continue a run this task
7580/// should use.
7581#[derive(Debug, Clone, PartialEq, Eq)]
7582enum Starter {
7583    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
7584    /// and that still exists.
7585    Review(String),
7586    /// `crate::graph::Runner::resume` on an unfinished run of this task.
7587    Resume(String),
7588    /// `crate::graph::Runner::start`: a fresh competition.
7589    Start,
7590}
7591
7592/// A second bound independent of inputs and the resettable failure counter.
7593/// Count execution and failed-startup recovery records once per run. Startup
7594/// failures can retain unrecorded preparation assets without an execution pass.
7595/// Unknown history is not evidence that a new set of worktrees is affordable.
7596fn retained_attempt_hold(
7597    task: &Task,
7598    starter: &Starter,
7599    limit: usize,
7600    mut load: impl FnMut(&str) -> Result<RunState>,
7601) -> Option<String> {
7602    if limit == 0 || matches!(starter, Starter::Resume(_)) {
7603        return None;
7604    }
7605    let mut retained = 0;
7606    for id in task
7607        .runs
7608        .iter()
7609        .chain(task.startup_failures.iter().map(|failure| &failure.run))
7610        .collect::<std::collections::BTreeSet<_>>()
7611    {
7612        let state = match load(id) {
7613            Ok(state) if state.id == *id => state,
7614            _ => {
7615                return Some(format!(
7616                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
7617                ));
7618            }
7619        };
7620        if state.retired_to.is_some() || state.released() {
7621            continue;
7622        }
7623        // Neither a completed status nor an empty candidate array proves that
7624        // all recovery sources (including unrecorded preparation) were retired.
7625        retained += 1;
7626    }
7627    (retained >= limit).then(|| format!(
7628        "[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."
7629    ))
7630}
7631
7632/// A selected public implementation overrides every historical candidate and pin.
7633fn selected_starter(
7634    selected: &crate::pr_recovery::Selection,
7635    previous: Option<&RunState>,
7636    unfinished: Option<&str>,
7637) -> Starter {
7638    if let Some(id) = unfinished
7639        && previous.is_some_and(|r| {
7640            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
7641        })
7642    {
7643        Starter::Resume(id.to_owned())
7644    } else {
7645        Starter::Review(selected.branch.clone())
7646    }
7647}
7648
7649/// The owner's answer to this branch's divergence question, consumed from the
7650/// task so a later, different divergence asks again. The runner applies it
7651/// (see `Runner::review_taking_over`), after the earlier worktree is released.
7652fn take_divergence_answer(
7653    branch: &str,
7654    remote: &str,
7655    task: &mut Task,
7656) -> Option<crate::reconcile::Choice> {
7657    let summary = crate::reconcile::summary_for(branch, remote);
7658    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
7659        (a.question == summary)
7660            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
7661            .flatten()
7662            .map(|c| (i, c))
7663    })?;
7664    task.answers.remove(idx);
7665    Some(choice)
7666}
7667
7668/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
7669/// this attempt should use. Pure, and separate from [`attempt`], so the
7670/// routing itself is assertable without spawning a real graph or a git
7671/// process: `attempt`'s own `crate::git::branch_exists` call has already
7672/// happened by the time this is called.
7673///
7674/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
7675/// whose branch is gone falls all the way through to [`Starter::Start`], not
7676/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
7677/// old (likely `Blocked`) run in the first place, and a branch that vanished
7678/// out from under that choice is not evidence resuming it would fare better.
7679fn choose_starter(
7680    review_branch: Option<&str>,
7681    branch_exists: bool,
7682    unfinished: Option<&str>,
7683) -> Starter {
7684    match review_branch {
7685        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
7686        Some(_) => Starter::Start,
7687        None => match unfinished {
7688            Some(id) => Starter::Resume(id.to_owned()),
7689            None => Starter::Start,
7690        },
7691    }
7692}
7693
7694/// Reuse a compatible latest review owner instead of taking its checked-out
7695/// branch into a new run. Different branches and changed criteria still use
7696/// the ordinary review/takeover policy.
7697fn review_retry_starter(
7698    task: &Task,
7699    previous: Option<&RunState>,
7700    branch: Option<&str>,
7701    exists: bool,
7702    unfinished: Option<&str>,
7703) -> Starter {
7704    if let Some(run) = previous
7705        && unfinished == Some(run.id.as_str())
7706        && run.reviewed_commits.is_some()
7707        && branch.is_some_and(|branch| {
7708            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
7709        })
7710        && may_resume_run(run, task)
7711    {
7712        return Starter::Resume(run.id.clone());
7713    }
7714    match (branch, unfinished, &task.review_of) {
7715        (None, None, Some(branch)) => Starter::Review(branch.clone()),
7716        _ => choose_starter(branch, exists, unfinished),
7717    }
7718}
7719
7720/// A retained review is valid only while its authored criteria still match.
7721fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
7722    task.review_branch
7723        .as_deref()
7724        .filter(|&branch| match &task.review_instruction {
7725            Some(authored) => *authored == task.instruction,
7726            // Legacy retained branches must agree with their prior run; only an
7727            // explicitly pinned review can proceed without recoverable provenance.
7728            None => previous.map_or_else(
7729                || task.review_of.as_deref() == Some(branch),
7730                |run| compatible_run_instruction(run, task),
7731            ),
7732        })
7733}
7734
7735/// A current explicit pin can select an otherwise incompatible run. Edits
7736/// and subsequent approvals invalidate pins selected for earlier criteria.
7737fn may_resume_run(run: &RunState, task: &Task) -> bool {
7738    if !task.assignment_accepts(run) {
7739        return false;
7740    }
7741    task.resume_override
7742        .as_ref()
7743        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
7744        || compatible_run_instruction(run, task)
7745}
7746
7747/// Review scaffolding is execution context, not evidence of an operator edit.
7748pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
7749    if let Some(authored) = &run.task_instruction {
7750        return compatible_instruction(authored, task);
7751    }
7752    if compatible_instruction(&run.instruction, task) {
7753        return true;
7754    }
7755    // Recognize only the existing generated review shapes on legacy runs.
7756    // Ordinary authored text with a similar heading is left intact.
7757    if run.reviewed_commits.is_some() {
7758        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
7759            return strip_answers_block(authored, task).trim() == task.instruction.trim();
7760        }
7761        if let Some(branch) = &task.review_of {
7762            let canonical = format!(
7763                "Review the branch `{branch}` (review-only: no implementation, no judging)."
7764            );
7765            let generated = format!(
7766                "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"
7767            );
7768            return task.instruction == canonical && run.instruction.starts_with(&generated);
7769        }
7770    }
7771    false
7772}
7773
7774/// Compare authored instructions, excluding answer blocks appended by the daemon.
7775pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
7776    strip_answers_block(old, task) == task.instruction
7777}
7778
7779/// Which repository a task runs in. A task that names none — the normal case
7780/// for one filed from a phone — runs in the daemon's own default.
7781fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
7782    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
7783        return fallback.to_path_buf();
7784    }
7785    task.repo.clone()
7786}
7787
7788/// The header [`append_answers`] appends operator answers under. Shared with
7789/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
7790/// rather than grown a new block on every resume.
7791const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
7792
7793/// Render the first `count` answers in the block appended to an instruction.
7794fn answers_block(task: &Task, count: usize) -> String {
7795    let mut s = ANSWERS_HEADER.to_owned();
7796    for a in &task.answers[..count] {
7797        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
7798    }
7799    s
7800}
7801
7802/// Render the approval independently of transient task state, so historical
7803/// suffixes remain recognizable after another explicit release.
7804fn resumption_block(r: &crate::queue::Resumption) -> String {
7805    format!(
7806        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
7807         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
7808        r.generation, r.at, r.instruction, r.answers_through,
7809    )
7810}
7811
7812/// Append audit answers and the latest explicit approval to the instruction.
7813fn append_answers(base: &str, task: &Task) -> String {
7814    let mut s = base.to_owned();
7815    if !task.answers.is_empty() {
7816        s.push_str(&answers_block(task, task.answers.len()));
7817    }
7818    if let Some(r) = &task.resumption {
7819        s.push_str(&resumption_block(r));
7820    }
7821    s
7822}
7823
7824/// Drop the prior answer block only when it is exactly the suffix this task
7825/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
7826/// the task author is ordinary instruction text, not a block to remove.
7827fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
7828    let mut instruction = instruction;
7829    for approval in task
7830        .resumption
7831        .iter()
7832        .chain(task.resumption_history.iter().rev())
7833    {
7834        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
7835            instruction = base;
7836            break;
7837        }
7838    }
7839    for count in (1..=task.answers.len()).rev() {
7840        let block = answers_block(task, count);
7841        if let Some(base) = instruction.strip_suffix(&block) {
7842            return base;
7843        }
7844    }
7845    instruction
7846}
7847
7848/// The instruction handed to `Runner::start`: the task's own text, plus any
7849/// operator answers `crate::conduct` collected for it (see
7850/// [`Task::answers`]), so a decision the operator actually made reaches the
7851/// implementers rather than only clearing the block that was waiting on it.
7852///
7853/// Appended rather than merged into [`Task::instruction`] itself, so the
7854/// task's own record stays exactly what its author wrote.
7855fn instruction_for(task: &Task) -> String {
7856    append_answers(&task.instruction, task)
7857}
7858
7859/// The instruction a resumed run should carry on with: whatever it already
7860/// had, refreshed with the task's *current* operator answers.
7861///
7862/// A resumable run's own `RunState::instruction` predates any answer
7863/// `crate::conduct` collects after the run parks, so resuming it unchanged —
7864/// the behaviour before this function existed — silently drops the very
7865/// decision the operator made to unblock it. Re-stripping any block this
7866/// function appended on an earlier resume before re-appending the current
7867/// list (rather than blindly appending again) is what keeps a task resumed
7868/// three times over three answered questions from carrying the same answer
7869/// three times.
7870fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
7871    append_answers(strip_answers_block(old_instruction, task), task)
7872}
7873
7874/// Preserve the producer's verified boundary and target, independent of prose.
7875fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
7876    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
7877    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
7878    if let Some(cause) = task.hold_notice_cause.as_mut() {
7879        cause.target = failure.map(|f| f.target.clone());
7880    }
7881}
7882
7883#[derive(Debug, thiserror::Error)]
7884#[error("attachment `{name}` is recorded on the task but {path} is missing")]
7885struct MissingAttachment {
7886    name: String,
7887    path: PathBuf,
7888}
7889
7890/// The task's attachments as absolute paths, each checked to still exist.
7891fn task_attachments(
7892    queue: &Queue,
7893    task: &Task,
7894) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
7895    let paths = queue.attachment_paths(task);
7896    for (name, path) in task.attachments.iter().zip(&paths) {
7897        if !path.is_file() {
7898            return Err(MissingAttachment {
7899                name: name.clone(),
7900                path: path.clone(),
7901            });
7902        }
7903    }
7904    Ok(paths)
7905}
7906
7907/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
7908/// answers before handing it to `Runner` — the actual boundary between
7909/// [`choose_starter`]'s routing and the graph, factored out so it is
7910/// assertable without a real repository, git branch, or agent CLI.
7911///
7912/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
7913/// instruction from the reviewed branch's own commit log because there is no
7914/// task statement to speak of for hand-written work, and splicing operator
7915/// answers into that text would contradict the very message it sends
7916/// reviewers ("there is no task statement").
7917fn prepare_instruction(
7918    starter: &Starter,
7919    old_instruction: Option<&str>,
7920    task: &Task,
7921) -> Option<String> {
7922    match starter {
7923        Starter::Start => Some(instruction_for(task)),
7924        Starter::Resume(_) => Some(resumed_instruction(
7925            old_instruction.expect("a resumed run always has a prior instruction"),
7926            task,
7927        )),
7928        Starter::Review(_) => None,
7929    }
7930}
7931
7932/// Persist a transition. A queue write failure is logged rather than fatal: the
7933/// run already happened, and taking the daemon down would only add a lost
7934/// backlog to a full disk.
7935fn record(queue: &Queue, task: &mut Task) {
7936    if let Err(e) = queue.put(task) {
7937        tracing::error!("could not record task {}: {e:#}", task.short());
7938        let notice = Notice::error(
7939            "loop:record",
7940            format!(
7941                "Task {} state could not be saved: {}. Check the disk.",
7942                task.id,
7943                e.to_string().lines().next().unwrap_or("unknown save error")
7944            ),
7945        )
7946        .link(Link::Task {
7947            id: task.id.clone(),
7948        });
7949        // The queue lives at `<home>/queue`, so its parent is the home.
7950        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
7951            Some(home) => notices::raise_in(home, notice),
7952            None => notices::raise(notice),
7953        }
7954    }
7955}
7956
7957/// Every runnable task, in the order the loop should try them.
7958///
7959/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
7960/// tail exists so that a claim somebody else holds costs the loop the next
7961/// candidate rather than a whole poll interval of idleness.
7962fn runnable(queue: &Queue) -> Vec<Task> {
7963    let mut tasks: Vec<Task> = queue
7964        .list()
7965        .into_iter()
7966        .filter(|t| t.status.runnable())
7967        .collect();
7968    tasks.sort_unstable_by(crate::queue::dispatch_order);
7969    tasks
7970}
7971
7972/// Why a run ended where it did, in one line, for [`Task::last_error`].
7973///
7974/// A stalled run names the seats the quota took out: "out of quota" is not
7975/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
7976/// agent to replace or which plan to top up.
7977///
7978/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
7979/// purpose: unlike `label`'s other callers (an internal log line, an
7980/// already-a-bug fallback message), this string becomes `Task::last_error`
7981/// verbatim, which the phone renders in the same alarm-styled box an
7982/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
7983/// `.err` styling. A bare `verified_noop` there would read exactly like the
7984/// failure this whole feature exists to tell apart from one.
7985fn describe(state: &RunState) -> String {
7986    let p = phrases(&state.config.graph.language);
7987    let mut detail = if state.status == RunStatus::Stalled {
7988        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
7989        seats.sort_unstable();
7990        seats.dedup();
7991        if seats.is_empty() {
7992            p.quorum_lost.to_owned()
7993        } else {
7994            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
7995        }
7996    } else {
7997        format!("{}{}", p.run_ended, state.status.display_label())
7998    };
7999    if let Some(cause) = state.verification_blocking_cause() {
8000        detail.push_str(&format!(" ({cause})"));
8001    } else if let Some(last) = state.events.last() {
8002        // The review loop's "never answered" stop is the one event worth
8003        // translating; it is recognised from structured state, not by
8004        // matching the English event text (which stays as recorded).
8005        let unanswered = state
8006            .reviews
8007            .last()
8008            .filter(|r| {
8009                state.status == RunStatus::Blocked
8010                    && last.node == "review"
8011                    && r.incomplete()
8012                    && r.blocking == 0
8013                    && r.round == state.config.graph.review_rounds
8014                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
8015            })
8016            .map(|r| (r.expected - r.answered, r.round));
8017        match unanswered {
8018            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
8019                detail.push_str(&format!(
8020                    " ({}: {})",
8021                    last.node,
8022                    (p.reviewers_never_answered)(missing, rounds)
8023                ));
8024            }
8025            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
8026        }
8027    }
8028    detail.push_str(&format!(" [run {}]", state.id));
8029    detail
8030}
8031
8032/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
8033///
8034/// The task file lives in the backlog indefinitely; a diagnostic is an
8035/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
8036/// stay small regardless of how much a gate command or a candidate printed.
8037const DIAGNOSTIC_MAX: usize = 4_000;
8038
8039/// Tail kept from a single failing command's output inside a diagnostic.
8040/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
8041/// pointer for a human deciding whether to go read the full artifact by hand,
8042/// not a replacement for reading it.
8043const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
8044
8045/// Assemble a bounded diagnostic excerpt from a held task's own run, so
8046/// `magi task show` says more than the one-line reason in [`describe`].
8047///
8048/// The one-liner answers "where did the run stop"; this answers "what would a
8049/// human have found opening `artifacts/` by hand" — the point of the whole
8050/// feature is the case that one-liner actively misleads on: a run held as "no
8051/// candidate produced a change" can mean the implementer actually finished
8052/// the task (opened a PR, merged it, tagged a release) and only left a clean
8053/// local worktree behind, which reads as "nothing happened" unless someone
8054/// goes and reads what the agent actually said. `None` when the run carries
8055/// none of the three shapes this recognises — an ordinary run held for
8056/// something not diagnosable from `RunState` alone still explains itself
8057/// through `Task::last_error`.
8058pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
8059    diagnostic(state)
8060}
8061
8062fn diagnostic(state: &RunState) -> Option<String> {
8063    let mut parts: Vec<String> = Vec::new();
8064
8065    if let Some(e2e) = &state.head_e2e
8066        && !e2e.passed
8067    {
8068        for o in e2e
8069            .outcomes
8070            .iter()
8071            .filter(|o| !o.ok() && !o.resource_blocked)
8072        {
8073            parts.push(format!(
8074                "head_e2e `{}` failed on {} ({}):\n{}",
8075                o.command,
8076                e2e.head.chars().take(7).collect::<String>(),
8077                notices::exit_status(o.code),
8078                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8079            ));
8080        }
8081    }
8082
8083    // Gate failure: which check(s), and the tail of what each printed.
8084    for o in state.gate.iter().filter(|o| !o.ok()) {
8085        parts.push(format!(
8086            "gate `{}` failed ({}):\n{}",
8087            o.command,
8088            notices::exit_status(o.code),
8089            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8090        ));
8091    }
8092
8093    // The land loop gave up because the fixer declined while checks were
8094    // still red: the message already names them (see `land::run`).
8095    if let Some(last) = state
8096        .events
8097        .iter()
8098        .rev()
8099        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
8100    {
8101        parts.push(last.message.clone());
8102    }
8103
8104    // No viable candidate: every implementer's own final word, sanitized the
8105    // same way a judge would have read it, so a run that actually finished
8106    // the job does not read as an unexplained failure. A verified no-op is
8107    // called out ahead of its own summary and apart from an ordinary
8108    // failure's `why` — this is the one candidate shape whose diagnostic a
8109    // human is expected to actually judge, not just skim.
8110    if state.viable().is_empty() {
8111        for c in &state.candidates {
8112            if c.has_valid_verified_noop()
8113                && let Some(evidence) = c.verified_noop_display()
8114            {
8115                parts.push(format!(
8116                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
8117                    c.label
8118                ));
8119            } else if !c.summary.trim().is_empty() {
8120                if let Some(why) = &c.failed {
8121                    parts.push(format!(
8122                        "candidate {} ({why}): {}",
8123                        c.label,
8124                        c.summary.trim()
8125                    ));
8126                } else {
8127                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
8128                }
8129            } else if let Some(why) = &c.failed {
8130                parts.push(format!("candidate {}: {why}", c.label));
8131            }
8132        }
8133    }
8134
8135    if parts.is_empty() {
8136        return None;
8137    }
8138    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
8139    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
8140    // back slightly over. Leave it enough room to always land under the
8141    // limit.
8142    Some(crate::run::tail(
8143        &parts.join("\n\n"),
8144        DIAGNOSTIC_MAX.saturating_sub(100),
8145    ))
8146}
8147
8148/// Stable lower-case name for a run status, for an internal log line and the
8149/// "graph stopped without reaching a terminal status" bug message in
8150/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
8151/// doc for why that one reads [`RunStatus::display_label`] instead. One
8152/// definition of a status's name, on the type that owns it: this table used
8153/// to live here as a second copy, and a status renamed in one place would
8154/// have gone on reading correctly in the other.
8155fn label(status: RunStatus) -> &'static str {
8156    status.as_str()
8157}
8158
8159/// Parse a merge mode override.
8160pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
8161    match mode {
8162        "none" => Ok(MergeMode::None),
8163        "local" => Ok(MergeMode::Local),
8164        "pr" => Ok(MergeMode::Pr),
8165        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
8166    }
8167}
8168
8169/// Take the status lock, recovering from a poisoned one.
8170///
8171/// A panic elsewhere must not silently stop the heartbeat: the status is plain
8172/// data, and the worst a poisoned lock can hold is a stale timestamp.
8173fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
8174    mutex
8175        .lock()
8176        .unwrap_or_else(std::sync::PoisonError::into_inner)
8177}
8178
8179#[cfg(test)]
8180mod tests {
8181    use super::*;
8182    use crate::queue::{Source, TaskStatus};
8183    use crate::run::{Candidate, CommandOutcome};
8184    use pretty_assertions::assert_eq;
8185
8186    fn task() -> Task {
8187        Task::new(
8188            "add retries".to_owned(),
8189            "add retries".to_owned(),
8190            PathBuf::from("/repo"),
8191            Source::Human,
8192        )
8193    }
8194
8195    #[test]
8196    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
8197        let skips = DispatchSkips::from([
8198            ("a".into(), SkipReason::CoolingDown),
8199            ("b".into(), SkipReason::WaitingOnLanding),
8200            ("c".into(), SkipReason::WaitingOnLanding),
8201            ("d".into(), SkipReason::OrdinaryCapacity),
8202        ]);
8203        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
8204        assert_eq!(wait.runnable, 4);
8205        assert_eq!(
8206            wait.reasons
8207                .iter()
8208                .map(|r| (r.reason.as_str(), r.count))
8209                .collect::<Vec<_>>(),
8210            [
8211                ("waiting_on_landing", 2),
8212                ("cooling_down", 1),
8213                ("ordinary_capacity", 1)
8214            ]
8215        );
8216        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
8217        assert!(
8218            aggregate_dispatch_wait(2, &DispatchSkips::new())
8219                .unwrap()
8220                .reasons
8221                .is_empty()
8222        );
8223    }
8224
8225    #[test]
8226    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
8227        let before = vec!["a".into(), "b".into(), "c".into()];
8228        let allowed = vec![task_with_id("b")];
8229        let skips = interrupt_skips(&before, &allowed);
8230        assert_eq!(
8231            skips,
8232            DispatchSkips::from([
8233                ("a".into(), SkipReason::InterruptGate),
8234                ("c".into(), SkipReason::InterruptGate),
8235            ])
8236        );
8237        let mut previous = DispatchSkips::new();
8238        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8239        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
8240        assert!(!changed_dispatch_skips(&mut previous, skips));
8241        assert!(changed_dispatch_skips(
8242            &mut previous,
8243            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
8244        ));
8245        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8246    }
8247
8248    #[test]
8249    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
8250        let mut value = serde_json::to_value(Status::new()).unwrap();
8251        value.as_object_mut().unwrap().remove("dispatch_wait");
8252        assert!(
8253            serde_json::from_value::<Status>(value.clone())
8254                .unwrap()
8255                .dispatch_wait
8256                .is_none()
8257        );
8258        assert!(
8259            serde_json::from_value::<Reading>(value.clone())
8260                .unwrap()
8261                .dispatch_wait
8262                .is_none()
8263        );
8264        value["dispatch_wait"] = serde_json::json!({
8265            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
8266        });
8267        let reading = serde_json::from_value::<Reading>(value).unwrap();
8268        assert_eq!(
8269            reading.dispatch_wait.unwrap().reasons[0].reason,
8270            "future_reason"
8271        );
8272    }
8273
8274    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
8275        let job = crate::worker::Job {
8276            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
8277            sequence: 1,
8278            kind: "task".into(),
8279            key: format!("task:{}", request.task),
8280            payload: serde_json::to_value(request).unwrap(),
8281            generation: "a".repeat(64),
8282            version: None,
8283            status: crate::worker::Status::Starting,
8284            result: None,
8285            pid: None,
8286            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
8287            finished_at: None,
8288        };
8289        let dir = home.join("workers/jobs").join(&job.id);
8290        std::fs::create_dir_all(&dir).unwrap();
8291        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
8292        job
8293    }
8294
8295    #[test]
8296    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
8297        let home = tempfile::tempdir().unwrap();
8298        let request = TaskWorker {
8299            opts: Opts::default(),
8300            queue: home.path().join("queue"),
8301            task: "startup".into(),
8302            lane: PermitKind::Ordinary,
8303            standalone: false,
8304        };
8305        let job = starting_task_reservation(home.path(), &request);
8306        let error = task_worker_spawn_error(
8307            home.path(),
8308            &request,
8309            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
8310        )
8311        .expect_err("our own reservation must not turn a failed spawn into a resync");
8312        let active = crate::worker::active(home.path()).unwrap();
8313        assert_eq!(active.len(), 1);
8314        assert_eq!(active[0].id, job.id);
8315        assert_eq!(active[0].status, crate::worker::Status::Starting);
8316        assert!(
8317            crate::worker::control(home.path(), &job.key)
8318                .unwrap()
8319                .is_none()
8320        );
8321        let notices = notices::Notices::at(home.path().join("notifications")).list();
8322        assert_eq!(notices.len(), 1);
8323        assert_eq!(notices[0].key, "loop:worker-startup");
8324        assert!(!notices[0].message.contains("private-error-detail"));
8325        assert!(notices[0].message.contains(&request.task));
8326        assert!(
8327            notices[0]
8328                .message
8329                .contains("could not be started or acknowledged")
8330        );
8331        assert!(notices[0].message.contains("worker.log"));
8332        assert_eq!(
8333            notices[0].link,
8334            Some(Link::Task {
8335                id: request.task.clone()
8336            })
8337        );
8338        assert!(format!("{error:#}").contains("private-error-detail"));
8339    }
8340
8341    #[test]
8342    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
8343        let home = tempfile::tempdir().unwrap();
8344        let mut request = TaskWorker {
8345            opts: Opts::default(),
8346            queue: home.path().join("queue"),
8347            task: "handoff".into(),
8348            lane: PermitKind::Ordinary,
8349            standalone: true,
8350        };
8351        let job = starting_task_reservation(home.path(), &request);
8352        request.standalone = false;
8353        task_worker_spawn_error(
8354            home.path(),
8355            &request,
8356            anyhow::anyhow!("operation key is already reserved for a different request"),
8357        )
8358        .expect("a different standalone request is the handoff race, not our startup failure");
8359        let active = crate::worker::active(home.path()).unwrap();
8360        assert_eq!(active.len(), 1);
8361        assert_eq!(active[0].id, job.id);
8362        assert_eq!(active[0].payload, job.payload);
8363        assert!(
8364            notices::Notices::at(home.path().join("notifications"))
8365                .list()
8366                .is_empty()
8367        );
8368    }
8369
8370    #[test]
8371    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
8372        let home = tempfile::tempdir().unwrap();
8373        let queue = Queue::at(home.path().join("queue"));
8374        let mut task = task();
8375        task.runs = vec!["previous".into()];
8376        queue.put(&mut task).unwrap();
8377        let request = TaskWorker {
8378            opts: Opts::default(),
8379            queue: home.path().join("queue"),
8380            task: task.id.clone(),
8381            lane: PermitKind::Ordinary,
8382            standalone: false,
8383        };
8384        let job = starting_task_reservation(home.path(), &request);
8385        let claims = current_work(home.path(), Timestamp::now());
8386        assert_eq!(claims.len(), 1);
8387        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
8388        assert_eq!(claims[0].run, "previous");
8389        assert!(other_claims_run(&claims, "previous", None));
8390        // Only after confirming the executing caller may admission ignore
8391        // this exact projection. Cleanup continues to observe it as live.
8392        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
8393        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
8394    }
8395
8396    #[test]
8397    fn admission_excludes_only_the_callers_exact_reservation() {
8398        let own = Current {
8399            worker: Some("own".into()),
8400            task: "same-task".into(),
8401            run: "previous".into(),
8402        };
8403        assert!(!other_claims_run(
8404            std::slice::from_ref(&own),
8405            "previous",
8406            Some("own")
8407        ));
8408        assert!(other_claims_run(
8409            std::slice::from_ref(&own),
8410            "previous",
8411            None
8412        ));
8413        for worker in [None, Some("other".into())] {
8414            let other = Current {
8415                worker,
8416                ..own.clone()
8417            };
8418            assert!(other_claims_run(
8419                &[own.clone(), other],
8420                "previous",
8421                Some("own")
8422            ));
8423        }
8424        let legacy: Current =
8425            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
8426        assert!(other_claims_run(&[legacy], "previous", Some("own")));
8427    }
8428
8429    #[test]
8430    fn os_leased_task_worker_survives_wall_clock_advance() {
8431        let home = tempfile::tempdir().unwrap();
8432        let queue = Queue::at(home.path().join("queue"));
8433        let mut task = task();
8434        let run = "20260903-100000-abcd";
8435        task.start(run.into());
8436        queue.put(&mut task).unwrap();
8437        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
8438        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
8439        assert!(
8440            current_work(home.path(), future)
8441                .iter()
8442                .any(
8443                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
8444                        && claim.run == run
8445                )
8446        );
8447        worker.release_lease();
8448        assert!(worker.dir.join("job.json").is_file());
8449        assert!(!is_working_on(home.path(), run, future));
8450        let dir = worker.dir.clone();
8451        drop(worker);
8452        assert!(!dir.exists());
8453    }
8454
8455    #[test]
8456    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
8457        let mut task = task();
8458        let mut run = run_state(RunStatus::Reviewing);
8459        run.task_instruction = Some(task.instruction.clone());
8460        run.reviewed_commits = Some(vec!["committed-fix".into()]);
8461        let branch = "magi/test/B";
8462        run.candidates.push(crate::run::Candidate {
8463            branch: branch.into(),
8464            ..candidate('B', "preserved work", false, None)
8465        });
8466        task.runs = vec![run.id.clone()];
8467        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
8468        assert_eq!(
8469            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8470            Starter::Resume(run.id.clone())
8471        );
8472        assert!(matches!(
8473            review_retry_starter(
8474                &task,
8475                Some(&run),
8476                Some("different"),
8477                true,
8478                unfinished.as_deref()
8479            ),
8480            Starter::Review(_)
8481        ));
8482        assert_eq!(
8483            review_retry_starter(
8484                &task,
8485                Some(&run),
8486                Some(branch),
8487                false,
8488                unfinished.as_deref()
8489            ),
8490            Starter::Start
8491        );
8492        task.instruction.push_str(" changed criteria");
8493        assert!(matches!(
8494            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8495            Starter::Review(_)
8496        ));
8497        assert!(matches!(
8498            review_retry_starter(&task, Some(&run), Some(branch), true, None),
8499            Starter::Review(_)
8500        ));
8501    }
8502
8503    #[test]
8504    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
8505        let dir = tempfile::tempdir().unwrap();
8506        let queue = Queue::at(dir.path().join("queue"));
8507        let mut task = task();
8508        task.status = TaskStatus::Running;
8509        task.attempts = 1;
8510        queue.put(&mut task).unwrap();
8511        let live = std::collections::BTreeSet::from([task.id.clone()]);
8512        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
8513        drop(queue.claim(&task.id).unwrap());
8514        let saved = queue.get(&task.id).unwrap();
8515        assert_eq!(saved.status, TaskStatus::Running);
8516        assert_eq!(saved.attempts, 1);
8517        assert!(saved.last_error.is_none());
8518    }
8519
8520    #[test]
8521    fn standalone_workers_do_not_consume_scheduler_lanes() {
8522        let request = |task: &str, lane, standalone| TaskWorker {
8523            opts: Opts::default(),
8524            queue: PathBuf::from("/queue"),
8525            task: task.to_owned(),
8526            lane,
8527            standalone,
8528        };
8529        let mut jobs = vec![
8530            request("ordinary", PermitKind::Ordinary, false),
8531            request("standalone-urgent", PermitKind::Urgent, true),
8532            request("standalone-ordinary", PermitKind::Ordinary, true),
8533            request("decision", PermitKind::None, false),
8534        ];
8535        assert_eq!(available_slots(&jobs, 2), (1, 1));
8536        jobs.push(request("urgent", PermitKind::Urgent, false));
8537        assert_eq!(available_slots(&jobs, 2), (1, 0));
8538        assert_eq!(available_slots(&jobs, 0), (0, 0));
8539    }
8540
8541    #[test]
8542    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
8543        let now = Timestamp::now();
8544        let mut reading = Reading {
8545            pid: Some(std::process::id()),
8546            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
8547            ..Reading::default()
8548        };
8549        assert!(!reading.running(now));
8550        assert!(legacy_scheduler_running(&reading, now, 0));
8551        reading.worker_protocol = Some(1);
8552        assert!(!legacy_scheduler_running(&reading, now, 0));
8553    }
8554
8555    #[test]
8556    fn selected_public_head_overrides_historical_resume_and_pin() {
8557        let mut t = task();
8558        let mut old = run_state(RunStatus::Blocked);
8559        let selection = crate::pr_recovery::Selection {
8560            url: "url".into(),
8561            branch: format!("magi/task-{}", t.id),
8562            head: "a".repeat(40),
8563            source_head: None,
8564            source_run: None,
8565            source_proof: None,
8566            disposition: Some(crate::pr_recovery::Disposition::Review),
8567            instruction: t.instruction.clone(),
8568            approved_at: Timestamp::now(),
8569        };
8570        t.resume_override = Some(crate::queue::OperatorResume {
8571            pinned_run: Some(old.id.clone()),
8572            question_id: "choice".into(),
8573            at: Timestamp::now(),
8574            conductor_rehold: None,
8575            forced: false,
8576        });
8577        assert_eq!(
8578            selected_starter(&selection, Some(&old), Some(&old.id)),
8579            Starter::Review(selection.branch.clone())
8580        );
8581        old.pr_recovery = Some(selection.clone());
8582        assert_eq!(
8583            selected_starter(&selection, Some(&old), Some(&old.id)),
8584            Starter::Review(selection.branch.clone())
8585        );
8586        old.reviewed_commits = Some(vec!["implementation".into()]);
8587        assert_eq!(
8588            selected_starter(&selection, Some(&old), Some(&old.id)),
8589            Starter::Resume(old.id.clone())
8590        );
8591        let mut changed = selection.clone();
8592        changed.head = "b".repeat(40);
8593        assert_eq!(
8594            selected_starter(&changed, Some(&old), Some(&old.id)),
8595            Starter::Review(changed.branch)
8596        );
8597    }
8598
8599    #[test]
8600    fn candidate_transplant_failure_is_one_actionable_hold() {
8601        let dir = tempfile::tempdir().unwrap();
8602        let q = Queue::at(dir.path().join("queue"));
8603        let mut t = task();
8604        let mut state = run_state(RunStatus::Blocked);
8605        state.event("prep", "cannot apply referenced commit: conflict");
8606        state.prep_failure = Some("conflict".into());
8607        t.start(state.id.clone());
8608        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
8609        assert_eq!(t.attempts, 1);
8610        assert_eq!(t.status, TaskStatus::Held);
8611        assert!(t.operator_held());
8612        assert!(!t.status.runnable());
8613        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
8614        let first = t.chat_notice_key().unwrap();
8615        t.chat_notices.push(first.clone());
8616        t.release_operator("test", None);
8617        state.id = "another-unprepared-run".into();
8618        t.start(state.id.clone());
8619        finish_attempt(
8620            3,
8621            &q,
8622            &mut t,
8623            &state,
8624            &[],
8625            Err(anyhow::anyhow!("still conflicts")),
8626        );
8627        assert_eq!(
8628            t.chat_notice_key().as_ref(),
8629            Some(&first),
8630            "no work happened"
8631        );
8632        t.release_operator("test", None);
8633        state.prep_failure = None;
8634        state.status = RunStatus::Failed;
8635        state.begin_pass();
8636        t.start(state.id.clone());
8637        finish_attempt(
8638            1,
8639            &q,
8640            &mut t,
8641            &state,
8642            &[],
8643            Err(anyhow::anyhow!("new gate failure")),
8644        );
8645        let failure = t.chat_notice_key().unwrap();
8646        assert_ne!(failure, first, "approved recovery reached a real failure");
8647        t.release_operator("test", None);
8648        state.begin_pass();
8649        t.start(state.id.clone());
8650        finish_attempt(
8651            1,
8652            &q,
8653            &mut t,
8654            &state,
8655            &[],
8656            Err(anyhow::anyhow!("new failure on resume")),
8657        );
8658        assert_ne!(
8659            t.chat_notice_key().as_ref(),
8660            Some(&failure),
8661            "a new settled pass"
8662        );
8663    }
8664
8665    #[test]
8666    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
8667        for source in ["cli", "web"] {
8668            let mut t = task();
8669            let mut run = run_state(RunStatus::Blocked);
8670            run.instruction = "Run A original criteria".into();
8671            run.task_instruction = Some(run.instruction.clone());
8672            t.start(run.id.clone());
8673            t.release_operator("choice", Some("resume-question"));
8674            t.resume_override = Some(crate::queue::OperatorResume {
8675                question_id: "resume-question".into(),
8676                at: Timestamp::now(),
8677                conductor_rehold: None,
8678                forced: true,
8679                pinned_run: Some(run.id.clone()),
8680            });
8681            t.hold_machine(Some("not enough free space to start a run".into()));
8682            let mut unchanged = t.clone();
8683            unchanged
8684                .edit("title changed".into(), unchanged.instruction.clone())
8685                .unwrap();
8686            unchanged.release_operator(source, None);
8687            assert_eq!(
8688                unchanged
8689                    .resume_override
8690                    .as_ref()
8691                    .unwrap()
8692                    .pinned_run
8693                    .as_deref(),
8694                Some(run.id.as_str())
8695            );
8696            assert!(!compatible_run_instruction(&run, &unchanged));
8697            assert!(may_resume_run(&run, &unchanged));
8698
8699            t.edit(
8700                "approved recovery".into(),
8701                "Reuse measured PR head B; fix Clippy; review".into(),
8702            )
8703            .unwrap();
8704            assert!(t.resume_override.is_none());
8705            t.release_operator(source, None);
8706            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
8707            assert!(reloaded.resume_override.is_none());
8708            assert!(!may_resume_run(&run, &reloaded));
8709            let unfinished =
8710                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
8711                    .filter(|_| may_resume_run(&run, &reloaded));
8712            assert_eq!(
8713                choose_starter(None, false, unfinished.as_deref()),
8714                Starter::Start
8715            );
8716            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
8717            assert_eq!(
8718                reloaded.resumption_history[0].question_id.as_deref(),
8719                Some("resume-question")
8720            );
8721
8722            // A revision already persisted with the old approval/pin is also
8723            // invalidated when the new operator release is recorded.
8724            unchanged.instruction = "Reuse measured PR head B".into();
8725            unchanged.hold_machine(Some("disk hold".into()));
8726            unchanged.release_operator(source, None);
8727            assert!(unchanged.resume_override.is_none());
8728            assert!(!may_resume_run(&run, &unchanged));
8729        }
8730    }
8731
8732    #[test]
8733    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
8734        let mut t = task();
8735        let mut run = run_state(RunStatus::Blocked);
8736        t.review_of = Some("approved-head".into());
8737        t.instruction =
8738            "Review the branch `approved-head` (review-only: no implementation, no judging)."
8739                .into();
8740        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();
8741        run.reviewed_commits = Some(vec!["Commit log".into()]);
8742        t.start(run.id.clone());
8743        t.hold_machine(Some("interrupted review".into()));
8744        t.release_operator("cli", None);
8745        assert!(
8746            compatible_run_instruction(&run, &t),
8747            "legacy explicit review remains resumable"
8748        );
8749        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
8750            .filter(|_| compatible_run_instruction(&run, &t));
8751        assert_eq!(
8752            choose_starter(None, false, unfinished.as_deref()),
8753            Starter::Resume(run.id.clone())
8754        );
8755        run.task_instruction = Some(t.instruction.clone());
8756        assert!(compatible_run_instruction(&run, &t));
8757        let reloaded: RunState =
8758            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
8759        assert!(compatible_run_instruction(&reloaded, &t));
8760        t.edit(
8761            "new approved head".into(),
8762            "Reuse measured PR head B".into(),
8763        )
8764        .unwrap();
8765        assert!(!compatible_run_instruction(&run, &t));
8766
8767        // Legacy recovery reviews retain the task criteria ahead of the log.
8768        t.review_of = None;
8769        t.instruction = "Fix Clippy on approved head".into();
8770        run.task_instruction = None;
8771        run.instruction = format!(
8772            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
8773            t.instruction
8774        );
8775        assert!(compatible_run_instruction(&run, &t));
8776        t.instruction.push('\n');
8777        assert!(
8778            compatible_run_instruction(&run, &t),
8779            "legacy generated review trimmed the original criteria"
8780        );
8781        t.hold_for_handover(Some("approved-head".into()), "refused".into());
8782        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
8783        t.edit("new plan".into(), "Reuse measured PR head B".into())
8784            .unwrap();
8785        assert!(review_branch_for(&t, Some(&run)).is_none());
8786        assert!(!compatible_run_instruction(&run, &t));
8787        t.review_branch = Some("approved-head".into());
8788        t.review_instruction = None;
8789        assert!(
8790            review_branch_for(&t, Some(&run)).is_none(),
8791            "legacy retained candidate cannot replace a revised approved head"
8792        );
8793    }
8794
8795    #[test]
8796    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
8797        let home = crate::run::test_home();
8798        crate::run::pin_test_home();
8799        let dir = tempfile::tempdir().unwrap();
8800        let queue = Queue::at(dir.path().join("queue"));
8801        for resume in [true, false] {
8802            let state = run_state(RunStatus::Blocked);
8803            let mut t = task();
8804            t.start(state.id.clone());
8805            let action = if resume {
8806                ask::ChoiceAction::Resume {
8807                    run: state.id.clone(),
8808                }
8809            } else {
8810                ask::ChoiceAction::Requeue
8811            };
8812            let mut q = action_question(&state.id, action);
8813            q.status = ask::QuestionStatus::Open;
8814            q.answer = None;
8815            q.answered_at = None;
8816            t.fail("run stopped with a question", 3);
8817            hold_if_runnable(&queue, &mut t);
8818            assert!(t.operator_decided_at.is_none());
8819            assert!(t.operator_held());
8820            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
8821            let expected = if resume {
8822                ActionDecision::Resume(state.id.clone())
8823            } else {
8824                ActionDecision::Requeue
8825            };
8826            assert_eq!(
8827                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8828                expected
8829            );
8830            t.hold_manual(Some("later explicit hold".into()));
8831            assert_eq!(
8832                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8833                ActionDecision::Stale
8834            );
8835        }
8836    }
8837
8838    #[test]
8839    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
8840        let mut t = task();
8841        t.answers.push(crate::queue::AnsweredQuestion {
8842            question: "Inspect the remote?".into(),
8843            answer: "Inspect then wait".into(),
8844        });
8845        let old = instruction_for(&t);
8846        assert!(compatible_instruction(&old, &t));
8847        t.instruction = "Reuse approved PR head and review".into();
8848        t.release_operator("cli", None);
8849        assert!(!compatible_instruction(&old, &t));
8850        let approved = instruction_for(&t);
8851        assert!(approved.contains("waiting premises are superseded"));
8852        assert!(compatible_instruction(&approved, &t));
8853        assert_eq!(resumed_instruction(&approved, &t), approved);
8854        t.release_operator("web", None);
8855        assert!(compatible_instruction(&approved, &t));
8856        assert_eq!(t.resumption_history.len(), 1);
8857        t.start("run".into());
8858        assert!(instruction_for(&t).contains("Explicit operator resumption"));
8859    }
8860
8861    /// A run that stopped on an infrastructure wait asked no agent anything:
8862    /// the task is held by the machine under a `[resource]` reason (resumable,
8863    /// re-checked by triage), and the attempt it started is given back.
8864    #[test]
8865    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
8866        let mut state = RunState::new(
8867            PathBuf::from("/repo"),
8868            "main".into(),
8869            "base".into(),
8870            "task".into(),
8871            Config::default(),
8872        );
8873        state.status = RunStatus::Landing;
8874        state.parked = true;
8875        state.pr_pushed_head = Some("head".into());
8876        state.land_unrelated = Some(
8877            serde_json::from_value(serde_json::json!({
8878                "head": "head", "question": "ci-question",
8879                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
8880            }))
8881            .unwrap(),
8882        );
8883        let mut t = task();
8884        t.start(state.id.clone());
8885        let verdict = Verdict {
8886            status: RunStatus::Landing,
8887            left_pr: true,
8888            quota_hit: false,
8889            parked: true,
8890            no_viable_candidates: false,
8891        };
8892        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8893        assert_eq!(t.attempts, 0);
8894        assert_eq!(t.status, TaskStatus::Held);
8895        assert!(!t.operator_held());
8896        assert!(
8897            t.hold_reason
8898                .as_deref()
8899                .unwrap()
8900                .starts_with("[ci-unrelated]")
8901        );
8902        // A second settlement must not refund an earlier task attempt.
8903        t.attempts = 1;
8904        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8905        assert_eq!(t.attempts, 1);
8906        assert_eq!(t.passes.len(), 1);
8907        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8908        state.pr_pushed_head = Some("new-head".into());
8909        state.parked = false;
8910        state.status = RunStatus::Blocked;
8911        let stale = Verdict {
8912            status: RunStatus::Blocked,
8913            parked: false,
8914            ..verdict
8915        };
8916        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
8917        assert_eq!(t.attempts, 1);
8918        // A new execution pass can refund its own newly charged attempt.
8919        state.begin_pass();
8920        state.begin_pass();
8921        state.status = RunStatus::Landing;
8922        state.parked = true;
8923        state.pr_pushed_head = Some("head".into());
8924        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
8925        assert_eq!(t.attempts, 0);
8926        assert_eq!(t.passes.len(), 2);
8927    }
8928
8929    #[test]
8930    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
8931        let mut state = run_state(RunStatus::Failed);
8932        state
8933            .quota
8934            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
8935        state.begin_pass();
8936        let mut t = task();
8937        t.start(state.id.clone());
8938        reclaim(&mut t, Some(state), 2, "en");
8939        assert_eq!(t.attempts, 1);
8940    }
8941
8942    #[test]
8943    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
8944        let mut state = run_state(RunStatus::Blocked);
8945        let losses: Vec<_> = ["alpha", "beta"]
8946            .into_iter()
8947            .enumerate()
8948            .map(|(i, agent)| {
8949                QuotaLoss::from_report(
8950                    format!("advisor-{i}"),
8951                    "advise",
8952                    Some(&crate::agent::Quota {
8953                        cause: crate::agent::QuotaCause::Authentication,
8954                        agent: agent.to_owned(),
8955                        reset: None,
8956                    }),
8957                )
8958            })
8959            .collect();
8960        crate::graph::block_machine_outage(&mut state, "advise", &losses);
8961        state.quota = losses;
8962        let mut t = task();
8963        t.start(state.id.clone());
8964        let verdict = Verdict {
8965            status: state.status,
8966            left_pr: false,
8967            quota_hit: true,
8968            parked: false,
8969            no_viable_candidates: true,
8970        };
8971        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
8972        assert_eq!(t.attempts, 0);
8973        assert_eq!(t.status, TaskStatus::Held);
8974        assert!(!t.operator_held());
8975        let reason = t.hold_reason.as_deref().unwrap();
8976        assert!(reason.starts_with("[authentication]"));
8977        assert!(
8978            reason.contains("alpha")
8979                && reason.contains("beta")
8980                && reason.contains("re-authenticate")
8981        );
8982        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
8983        // Orphan recovery uses the same settlement and cannot spend an attempt.
8984        let mut orphan = task();
8985        orphan.start(state.id.clone());
8986        reclaim(&mut orphan, Some(state), 2, "en");
8987        assert_eq!(orphan.attempts, 0);
8988        assert_eq!(orphan.status, TaskStatus::Held);
8989    }
8990
8991    #[test]
8992    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
8993        let mut state = RunState::new(
8994            PathBuf::from("/repo"),
8995            "main".to_owned(),
8996            "abc1234".to_owned(),
8997            "task".to_owned(),
8998            Config::default(),
8999        );
9000        state.status = RunStatus::Blocked;
9001        state.resource_block = Some(crate::run::ResourceBlock {
9002            cause: crate::run::ResourceBlockCause::Other,
9003            node: "graft".to_owned(),
9004            kind: "shared build cache".to_owned(),
9005            detail: "timed out".to_owned(),
9006            at: jiff::Timestamp::now(),
9007        });
9008        let mut t = task();
9009        t.start("20260902-000000-aaaa".to_owned());
9010        assert_eq!(t.attempts, 1);
9011        let verdict = Verdict {
9012            status: RunStatus::Blocked,
9013            left_pr: false,
9014            quota_hit: false,
9015            parked: false,
9016            no_viable_candidates: false,
9017        };
9018        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
9019        assert_eq!(t.status, TaskStatus::Held);
9020        assert_eq!(t.attempts, 0, "the attempt is refunded");
9021        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
9022        assert!(
9023            !t.operator_held(),
9024            "a machine hold, released without a human"
9025        );
9026
9027        let mut selected = task();
9028        selected.start("20260902-000000-cccc".into());
9029        selected.replacement = Some(crate::merge_decision::Replacement {
9030            question: "fixture".into(),
9031            run: "earlier".into(),
9032            pr: "https://example.invalid/pr/1".into(),
9033            agent: "selected".into(),
9034            context: "fixture".into(),
9035        });
9036        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
9037        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
9038        assert_eq!(selected.attempts, 0);
9039        assert!(
9040            !selected.operator_held(),
9041            "a selected agent also retains a machine resource hold"
9042        );
9043        assert!(
9044            selected
9045                .hold_reason
9046                .as_deref()
9047                .unwrap()
9048                .starts_with("[resource] ")
9049        );
9050
9051        // A park request outranks it: still the operator's doing.
9052        let mut p = task();
9053        p.start("20260902-000000-bbbb".to_owned());
9054        settle_and_diagnose(
9055            &mut p,
9056            Verdict {
9057                parked: true,
9058                ..verdict
9059            },
9060            "parked",
9061            2,
9062            &state,
9063        );
9064        assert_eq!(p.status, TaskStatus::Parked);
9065        assert_eq!(
9066            p.attempts, 0,
9067            "parking refunds once rather than also settling the resource hold"
9068        );
9069    }
9070
9071    #[test]
9072    fn record_failure_notice_links_the_task() {
9073        let dir = tempfile::tempdir().unwrap();
9074        // A regular file where the queue directory should be makes every
9075        // `put` fail, on every platform and whoever runs the test.
9076        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
9077        let queue = Queue::at(dir.path().join("queue"));
9078        let mut t = interrupt_task("rec-fail-1");
9079        record(&queue, &mut t);
9080
9081        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
9082        assert_eq!(found.len(), 1);
9083        assert_eq!(found[0].key, "loop:record");
9084        assert_eq!(
9085            found[0].link,
9086            Some(Link::Task {
9087                id: "rec-fail-1".to_owned()
9088            })
9089        );
9090    }
9091
9092    /// A runnable task marked to interrupt, with an id fixed for assertions
9093    /// rather than the random one [`Task::new`] mints.
9094    fn interrupt_task(id: &str) -> Task {
9095        let mut t = task();
9096        t.id = id.to_owned();
9097        t.interrupt = true;
9098        t
9099    }
9100
9101    /// An ordinary runnable task with an id fixed for assertions.
9102    fn task_with_id(id: &str) -> Task {
9103        let mut t = task();
9104        t.id = id.to_owned();
9105        t
9106    }
9107
9108    /// A runnable task marked `--urgent`, with an id fixed for assertions.
9109    fn urgent_task(id: &str) -> Task {
9110        let mut t = task();
9111        t.id = id.to_owned();
9112        t.urgent = true;
9113        t
9114    }
9115
9116    #[test]
9117    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
9118        let dir = tempfile::tempdir().unwrap();
9119        let queue = Queue::at(dir.path().join("queue"));
9120        let mut parked = task_with_id("parked");
9121        parked.start("run".into());
9122        parked.park("upgrade");
9123        parked.record_pass_at(
9124            "run",
9125            0,
9126            Some(Timestamp::now()),
9127            1,
9128            Some(crate::run::ParkCause::Upgrade {
9129                from: "old".into(),
9130                to: None,
9131            }),
9132        );
9133        let mut fresh = task_with_id("fresh");
9134        fresh.priority = 100;
9135        let mut urgent_task = urgent_task("urgent");
9136        for t in [&mut parked, &mut fresh, &mut urgent_task] {
9137            queue.put(t).unwrap();
9138        }
9139        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9140        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9141        let candidates = runnable(&queue);
9142        assert_eq!(candidates[0].id, parked.id);
9143        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
9144        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
9145        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
9146        drop(first);
9147        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
9148        let next = runnable(&queue)
9149            .into_iter()
9150            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
9151            .unwrap();
9152        assert_eq!(next.task.id, fresh.id);
9153        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
9154        drop(claimed_elsewhere);
9155        drop(next);
9156        assert!(matches!(
9157            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
9158            Err(SkipReason::CoolingDown)
9159        ));
9160    }
9161
9162    #[test]
9163    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
9164        let dir = tempfile::tempdir().unwrap();
9165        let queue = Queue::at(dir.path().join("queue"));
9166        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9167        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9168        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9169        let mut first = task();
9170        queue.put(&mut first).unwrap();
9171        let stale_plain = queue.get(&first.id).unwrap();
9172        first.set_urgent(true).unwrap();
9173        queue.put(&mut first).unwrap();
9174        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
9175        let mut second = urgent_task("second");
9176        queue.put(&mut second).unwrap();
9177        assert!(matches!(
9178            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
9179            Err(SkipReason::UrgentCapacity)
9180        ));
9181        drop(queue.claim(&second.id).unwrap());
9182        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
9183        drop(dispatched);
9184        let stale_urgent = queue.get(&first.id).unwrap();
9185        first.set_urgent(false).unwrap();
9186        queue.put(&mut first).unwrap();
9187        assert!(matches!(
9188            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
9189            Err(SkipReason::OrdinaryCapacity)
9190        ));
9191        assert_eq!(urgent.available_permits(), 1);
9192        drop(queue.claim(&first.id).unwrap());
9193        drop(occupied);
9194    }
9195
9196    #[test]
9197    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
9198        let dir = tempfile::tempdir().unwrap();
9199        let queue = Queue::at(dir.path().join("queue"));
9200        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9201        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9202        let mut t = task();
9203        queue.put(&mut t).unwrap();
9204        for enabled in [true, false] {
9205            let stale = queue.get(&t.id).unwrap();
9206            t.set_urgent(enabled).unwrap();
9207            queue.put(&mut t).unwrap();
9208            assert_ne!(stale.urgent, enabled);
9209            let DispatchClaim {
9210                task: fresh,
9211                claim,
9212                lane,
9213                permit,
9214            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9215            assert_eq!(fresh.urgent, enabled);
9216            assert_eq!(
9217                lane,
9218                if enabled {
9219                    PermitKind::Urgent
9220                } else {
9221                    PermitKind::Ordinary
9222                }
9223            );
9224            assert_eq!(ordinary.available_permits(), usize::from(enabled));
9225            assert_eq!(urgent.available_permits(), usize::from(!enabled));
9226            assert!(queue.claim(&t.id).is_err());
9227            assert_eq!(fresh.attempts, stale.attempts);
9228            drop((claim, permit));
9229            assert_eq!(ordinary.available_permits(), 1);
9230            assert_eq!(urgent.available_permits(), 1);
9231        }
9232        t.set_urgent(true).unwrap();
9233        queue.put(&mut t).unwrap();
9234        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
9235        assert!(matches!(
9236            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9237            Err(SkipReason::UrgentCapacity)
9238        ));
9239        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
9240        drop(queue.claim(&t.id).unwrap());
9241        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
9242        drop(occupied);
9243        assert!(matches!(
9244            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
9245            Err(SkipReason::CoolingDown)
9246        ));
9247        drop(queue.claim(&t.id).unwrap());
9248        let held = queue.claim(&t.id).unwrap();
9249        assert!(matches!(
9250            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9251            Err(SkipReason::ClaimUnavailable)
9252        ));
9253        drop(held);
9254        t.status = TaskStatus::Held;
9255        queue.put(&mut t).unwrap();
9256        assert!(matches!(
9257            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9258            Err(SkipReason::NoLongerRunnable)
9259        ));
9260        drop(queue.claim(&t.id).unwrap());
9261        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
9262        assert!(matches!(
9263            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9264            Err(SkipReason::RereadFailed)
9265        ));
9266        drop(queue.claim(&t.id).unwrap());
9267        assert_eq!(urgent.available_permits(), 1);
9268    }
9269
9270    /// The land-resume exemption wins outright, whether or not the candidate
9271    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
9272    /// queue behind anything" guarantee cannot be weaker just because the
9273    /// same task was also filed with `--urgent`.
9274    #[test]
9275    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
9276        assert_eq!(permit_kind(true, false, false), PermitKind::None);
9277        assert_eq!(permit_kind(true, false, true), PermitKind::None);
9278        assert_eq!(permit_kind(true, true, false), PermitKind::None);
9279        assert_eq!(permit_kind(true, true, true), PermitKind::None);
9280    }
9281
9282    /// The one property this whole feature exists for: `--urgent` draws from
9283    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
9284    /// ordinary candidate draws from the ordinary pool exactly as before,
9285    /// untouched by the urgent slot's existence.
9286    #[test]
9287    fn permit_kind_separates_urgent_from_ordinary() {
9288        assert_eq!(permit_kind(false, false, true), PermitKind::Urgent);
9289        assert_eq!(permit_kind(false, false, false), PermitKind::Ordinary);
9290        assert_eq!(permit_kind(false, true, false), PermitKind::Immediate);
9291        assert_eq!(permit_kind(false, true, true), PermitKind::Immediate);
9292    }
9293
9294    #[test]
9295    fn immediate_lane_does_not_consume_ordinary_or_urgent_slots() {
9296        let request = |task: &str, lane, standalone| TaskWorker {
9297            opts: Opts::default(),
9298            queue: PathBuf::from("/queue"),
9299            task: task.to_owned(),
9300            lane,
9301            standalone,
9302        };
9303        let jobs = vec![
9304            request("ordinary", PermitKind::Ordinary, false),
9305            request("urgent", PermitKind::Urgent, false),
9306            request("immediate-1", PermitKind::Immediate, false),
9307            request("immediate-2", PermitKind::Immediate, false),
9308            request("decision", PermitKind::None, false),
9309        ];
9310        assert_eq!(available_slots(&jobs, 1), (0, 0));
9311        assert_eq!(available_slots(&jobs, 2), (1, 0));
9312        let immediate_only = vec![
9313            request("immediate-1", PermitKind::Immediate, false),
9314            request("immediate-2", PermitKind::Immediate, false),
9315        ];
9316        assert_eq!(available_slots(&immediate_only, 1), (1, 1));
9317    }
9318
9319    #[test]
9320    fn immediate_dispatch_bypasses_saturated_lanes_and_preserves_non_concurrency_gates() {
9321        let dir = tempfile::tempdir().unwrap();
9322        let queue = Queue::at(dir.path().join("queue"));
9323        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9324        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9325        let _ord_permit = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9326        let _urg_permit = Arc::clone(&urgent).try_acquire_owned().unwrap();
9327
9328        // Both ordinary and urgent lanes are saturated.
9329        let mut imm1 = task_with_id("imm-1");
9330        imm1.immediate = true;
9331        let mut imm2 = task_with_id("imm-2");
9332        imm2.immediate = true;
9333        imm2.urgent = true;
9334        queue.put(&mut imm1).unwrap();
9335        queue.put(&mut imm2).unwrap();
9336
9337        // Stale non-immediate listing still picks up saved immediate under claim.
9338        let mut stale = imm1.clone();
9339        stale.immediate = false;
9340        let claim1 = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9341        assert_eq!(claim1.lane, PermitKind::Immediate);
9342        assert!(claim1.permit.is_none());
9343
9344        // Multiple immediate tasks can claim simultaneously without touching semaphores.
9345        let claim2 = claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).unwrap();
9346        assert_eq!(claim2.lane, PermitKind::Immediate);
9347        assert!(claim2.permit.is_none());
9348        assert_eq!(ordinary.available_permits(), 0);
9349        assert_eq!(urgent.available_permits(), 0);
9350
9351        // Duplicate claim on an already-claimed immediate task is refused.
9352        assert_eq!(
9353            claim_dispatch(&queue, &imm1, false, &ordinary, &urgent).err(),
9354            Some(SkipReason::ClaimUnavailable)
9355        );
9356        drop((claim1, claim2));
9357
9358        // Cooldown still blocks immediate tasks.
9359        assert_eq!(
9360            claim_dispatch(&queue, &imm1, true, &ordinary, &urgent).err(),
9361            Some(SkipReason::CoolingDown)
9362        );
9363
9364        // Clearing immediate while urgent remains true reverts to urgent lane.
9365        imm2.set_immediate(false).unwrap();
9366        queue.put(&mut imm2).unwrap();
9367        assert_eq!(
9368            claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).err(),
9369            Some(SkipReason::UrgentCapacity)
9370        );
9371
9372        // Interrupt gate still withholds immediate candidates.
9373        let interrupt = Interrupt::Parking {
9374            parked: vec!["in-flight".into()],
9375            interrupt_task: "other".into(),
9376        };
9377        assert!(
9378            interrupt_gate(&interrupt, &["in-flight".into()], vec![imm1.clone()]).is_empty(),
9379            "an active interrupt sequence must withhold immediate tasks too"
9380        );
9381    }
9382
9383    #[test]
9384    fn admission_snapshot_distinguishes_mode_lane_blockers_and_unknown_state() {
9385        let dir = tempfile::tempdir().unwrap();
9386        let home = dir.path();
9387        let queue = Queue::at(home.join("queue"));
9388        let now = Timestamp::now();
9389
9390        let mut imm = task_with_id("imm-ready");
9391        imm.immediate = true;
9392        queue.put(&mut imm).unwrap();
9393
9394        // No scheduler running -> waiting, never "next poll".
9395        let snap = AdmissionSnapshot::capture(home, now);
9396        let adm = snap.evaluate(&imm, &queue, None, home);
9397        assert_eq!(adm.mode, "immediate");
9398        assert_eq!(adm.state, "waiting");
9399        assert_eq!(adm.label, "Immediate: waiting — scheduler not running");
9400
9401        // Live scheduler + saturated ordinary/urgent workers + stale capacity skip -> next poll!
9402        let mut status = Status::new();
9403        status.updated_at = now;
9404        status
9405            .dispatch_skips
9406            .insert(imm.id.clone(), SkipReason::UrgentCapacity.key().to_owned());
9407        write_status_to(&home.join("daemon.json"), &status).unwrap();
9408
9409        let mut ord = task_with_id("ord-running");
9410        ord.status = TaskStatus::Running;
9411        queue.put(&mut ord).unwrap();
9412        let ord_req = TaskWorker {
9413            opts: Opts::default(),
9414            queue: queue.root().to_path_buf(),
9415            task: ord.id.clone(),
9416            lane: PermitKind::Ordinary,
9417            standalone: false,
9418        };
9419        let (_ord_job, _ord_lease) = crate::worker::running_fixture(
9420            home,
9421            &format!("task:{}", ord.id),
9422            serde_json::to_value(&ord_req).unwrap(),
9423        )
9424        .unwrap();
9425
9426        let mut urg = task_with_id("urg-running");
9427        urg.urgent = true;
9428        urg.status = TaskStatus::Running;
9429        queue.put(&mut urg).unwrap();
9430        let urg_req = TaskWorker {
9431            opts: Opts::default(),
9432            queue: queue.root().to_path_buf(),
9433            task: urg.id.clone(),
9434            lane: PermitKind::Urgent,
9435            standalone: false,
9436        };
9437        let (_urg_job, _urg_lease) = crate::worker::running_fixture(
9438            home,
9439            &format!("task:{}", urg.id),
9440            serde_json::to_value(&urg_req).unwrap(),
9441        )
9442        .unwrap();
9443
9444        let snap = AdmissionSnapshot::capture(home, now);
9445        let adm = snap.evaluate(&imm, &queue, None, home);
9446        assert_eq!(adm.state, "next_poll");
9447        assert_eq!(adm.label, "Immediate: next poll");
9448        assert_eq!(adm.reservation_lane, None);
9449
9450        // Running worker reports its actual persisted reservation lane.
9451        let ord_adm = snap.evaluate(&ord, &queue, None, home);
9452        assert_eq!(ord_adm.state, "running");
9453        assert_eq!(ord_adm.reservation_lane, Some("ordinary"));
9454        assert_eq!(ord_adm.label, "Running (ordinary lane)");
9455
9456        // Held (manual + disk) and Blocked (dependency) report concrete blockers.
9457        let mut held = task_with_id("imm-held");
9458        held.immediate = true;
9459        held.hold_manual(Some("awaiting signoff".into()));
9460        queue.put(&mut held).unwrap();
9461        let held_adm = snap.evaluate(&held, &queue, None, home);
9462        assert_eq!(held_adm.state, "waiting");
9463        assert_eq!(
9464            held_adm.label,
9465            "Immediate: waiting — held (awaiting signoff)"
9466        );
9467
9468        let mut disk_held = task_with_id("imm-disk");
9469        disk_held.immediate = true;
9470        disk_held.hold_machine(Some("only 1 GiB free".into()));
9471        disk_held.mark_startup_disk_capacity();
9472        queue.put(&mut disk_held).unwrap();
9473        let disk_adm = snap.evaluate(&disk_held, &queue, None, home);
9474        assert_eq!(disk_adm.state, "waiting");
9475        assert!(disk_adm.label.contains("disk admission"), "{disk_adm:?}");
9476
9477        let mut blocked = task_with_id("imm-blocked");
9478        blocked.immediate = true;
9479        blocked.block(vec![held.id.clone()], Some("needs held task".into()));
9480        queue.put(&mut blocked).unwrap();
9481        let questions = Questions::at(home.join("questions"));
9482        let inv = crate::blockers::Inventory::load(&queue, &questions);
9483        let blocked_adm = snap.evaluate(&blocked, &queue, Some(&inv), home);
9484        assert_eq!(blocked_adm.state, "waiting");
9485        assert!(
9486            blocked_adm
9487                .label
9488                .starts_with("Immediate: waiting — waiting on dependencies"),
9489            "{blocked_adm:?}"
9490        );
9491
9492        // Existing claim blocks immediate.
9493        let _claim = queue.claim(&imm.id).unwrap();
9494        let claimed_adm = snap.evaluate(&imm, &queue, None, home);
9495        assert_eq!(claimed_adm.state, "waiting");
9496        assert_eq!(
9497            claimed_adm.label,
9498            "Immediate: waiting — claimed by another process"
9499        );
9500        drop(_claim);
9501
9502        // Quota cooldown blocks immediate.
9503        let until = now + jiff::SignedDuration::from_secs(120);
9504        std::fs::write(
9505            home.join("task-quota-cooldown.json"),
9506            serde_json::to_vec(&until).unwrap(),
9507        )
9508        .unwrap();
9509        let cool_snap = AdmissionSnapshot::capture(home, now);
9510        let cool_adm = cool_snap.evaluate(&imm, &queue, None, home);
9511        assert_eq!(cool_adm.state, "waiting");
9512        assert!(cool_adm.label.contains("quota cooldown"), "{cool_adm:?}");
9513        std::fs::remove_file(home.join("task-quota-cooldown.json")).unwrap();
9514
9515        // Corrupt interrupt file is reported as unknown, never "next poll".
9516        std::fs::write(home.join("scheduler-interrupt.json"), "{broken").unwrap();
9517        let bad_snap = AdmissionSnapshot::capture(home, now);
9518        let bad_adm = bad_snap.evaluate(&imm, &queue, None, home);
9519        assert_eq!(bad_adm.state, "unknown");
9520        assert_ne!(bad_adm.label, "Immediate: next poll");
9521    }
9522
9523    /// The exact wiring `attempt` runs before minting anything: a config's
9524    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
9525    /// Free space is injected rather than asked of the real disk - the point
9526    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
9527    /// is deterministic on every machine this test runs on, never dependent
9528    /// on how full the CI runner's own disk happens to be.
9529    #[test]
9530    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
9531        let cfg = Config::default();
9532        let repo = Path::new("/any/repo/path");
9533
9534        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
9535            .expect("must hold below the threshold");
9536        assert!(reason.contains("1024"), "{reason}");
9537        assert!(
9538            reason.contains(&cfg.disk.min_free_bytes.to_string()),
9539            "{reason}"
9540        );
9541
9542        assert_eq!(
9543            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
9544            None,
9545            "exactly at the floor is open"
9546        );
9547        assert_eq!(
9548            disk_gate_with(
9549                repo,
9550                &cfg,
9551                PathBuf::new,
9552                |_| Ok(cfg.disk.min_free_bytes + 1)
9553            ),
9554            None,
9555            "comfortably above the floor is open"
9556        );
9557    }
9558
9559    /// The collection threshold is not an admission floor: free space just
9560    /// above `min_free_bytes` but far below `reclaim_free_bytes` opens the gate
9561    /// with no hold, whatever the threshold is.
9562    #[test]
9563    fn disk_gate_ignores_the_collection_threshold() {
9564        let mut cfg = Config::default();
9565        cfg.disk.reclaim_free_bytes = Some(cfg.disk.min_free_bytes * 100);
9566        let repo = Path::new("/any/repo/path");
9567        assert_eq!(
9568            disk_gate_with(
9569                repo,
9570                &cfg,
9571                PathBuf::new,
9572                |_| Ok(cfg.disk.min_free_bytes + 1)
9573            ),
9574            None
9575        );
9576        assert!(
9577            disk_gate_with(
9578                repo,
9579                &cfg,
9580                PathBuf::new,
9581                |_| Ok(cfg.disk.min_free_bytes - 1)
9582            )
9583            .is_some(),
9584            "below the admission floor still holds"
9585        );
9586    }
9587
9588    #[test]
9589    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
9590        let dir = tempfile::tempdir().unwrap();
9591        let repo = dir.path().join("repo");
9592        let cache = dir.path().join("cache");
9593        let worktrees = dir.path().join("worktrees");
9594        for path in [&repo, &cache, &worktrees] {
9595            std::fs::create_dir(path).unwrap();
9596        }
9597        let mut cfg = Config::default();
9598        cfg.graph.worktree_root = Some(worktrees.clone());
9599        cfg.verify.gate = vec![format!(
9600            "CARGO_TARGET_DIR='{}' cargo build",
9601            cache.display()
9602        )];
9603        for blocked in [&cache, &worktrees] {
9604            for unmeasured in [false, true] {
9605                assert!(
9606                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
9607                        if path == blocked {
9608                            if unmeasured {
9609                                Err(anyhow::anyhow!("measurement failed"))
9610                            } else {
9611                                Ok(0)
9612                            }
9613                        } else {
9614                            Ok(u64::MAX)
9615                        }
9616                    })
9617                    .is_some(),
9618                    "a blocked secondary output volume must close admission"
9619                );
9620            }
9621        }
9622        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
9623    }
9624
9625    #[test]
9626    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
9627        let dir = tempfile::tempdir().unwrap();
9628        let repo = dir.path().join("repo");
9629        let cache = dir.path().join("cache");
9630        let home_parent = dir.path().join("run-volume");
9631        let home = home_parent.join("new-home");
9632        for path in [&repo, &cache, &home_parent] {
9633            std::fs::create_dir(path).unwrap();
9634        }
9635        let mut cfg = Config::default();
9636        cfg.graph.worktree_root = Some(repo.clone());
9637        cfg.verify.gate = vec![format!(
9638            "CARGO_TARGET_DIR='{}' cargo build",
9639            cache.display()
9640        )];
9641        cfg.verify.build_cache = BuildCache::Isolated;
9642        let denied = |blocked: &Path| {
9643            disk_gate_with(
9644                &repo,
9645                &cfg,
9646                || home.clone(),
9647                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
9648            )
9649            .is_some()
9650        };
9651        assert!(!denied(&cache));
9652        assert!(denied(&home_parent));
9653    }
9654
9655    #[test]
9656    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
9657        let mut cfg = Config::default();
9658        cfg.disk.min_free_bytes = 0;
9659        let repo = Path::new("/any/repo/path");
9660        assert_eq!(
9661            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
9662            None,
9663            "a zero floor never measures at all"
9664        );
9665    }
9666
9667    #[test]
9668    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
9669        let cfg = Config::default();
9670        let repo = Path::new("/any/repo/path");
9671        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
9672            Err(anyhow::anyhow!("no df on this box"))
9673        })
9674        .expect("a measurement failure must close the gate, not open it");
9675        assert!(reason.contains("could not measure"), "{reason}");
9676    }
9677
9678    #[test]
9679    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
9680        let ordinary = task();
9681        let next = advance_interrupt(
9682            Interrupt::Idle,
9683            std::slice::from_ref(&ordinary.id),
9684            std::slice::from_ref(&ordinary),
9685        );
9686        assert_eq!(next, Interrupt::Idle);
9687    }
9688
9689    #[test]
9690    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
9691        // Nothing to interrupt - this is just an ordinary candidate, and the
9692        // loop's normal dispatch will pick it up like any other.
9693        let marked = interrupt_task("marked");
9694        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9695        assert_eq!(next, Interrupt::Idle);
9696    }
9697
9698    #[test]
9699    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
9700        let marked = interrupt_task("marked");
9701        let next = advance_interrupt(
9702            Interrupt::Idle,
9703            &["running".to_owned()],
9704            std::slice::from_ref(&marked),
9705        );
9706        assert_eq!(
9707            next,
9708            Interrupt::Parking {
9709                parked: vec!["running".to_owned()],
9710                interrupt_task: "marked".to_owned(),
9711            }
9712        );
9713    }
9714
9715    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
9716    /// one run can be in flight when a task becomes runnable and marked.
9717    /// Parking all of them would mean `Resuming` later has more than one id
9718    /// to release back to ordinary dispatch, which cannot be made safe
9719    /// against that same setting's own extra concurrency slots letting two
9720    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
9721    /// The simplification the task's own constraints ask for: do not begin
9722    /// a sequence at all until the herd settles back to exactly one.
9723    #[test]
9724    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
9725        let marked = interrupt_task("marked");
9726
9727        let two = advance_interrupt(
9728            Interrupt::Idle,
9729            &["a".to_owned(), "b".to_owned()],
9730            std::slice::from_ref(&marked),
9731        );
9732        assert_eq!(two, Interrupt::Idle);
9733
9734        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9735        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
9736    }
9737
9738    #[test]
9739    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
9740        let state = Interrupt::Parking {
9741            parked: vec!["running".to_owned()],
9742            interrupt_task: "marked".to_owned(),
9743        };
9744        // Still in flight: no change.
9745        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
9746        assert_eq!(still_going, state);
9747
9748        // Left flight, but the interrupt task has not been dispatched yet on
9749        // this tick - stays `Parking` so `interrupt_gate` can let it through,
9750        // as long as it is still runnable.
9751        let stopped_but_not_yet_dispatched =
9752            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
9753        assert_eq!(stopped_but_not_yet_dispatched, state);
9754
9755        // Left flight, and the interrupt task is now in flight itself.
9756        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
9757        assert_eq!(
9758            dispatched,
9759            Interrupt::Running {
9760                parked: vec!["running".to_owned()],
9761                interrupt_task: "marked".to_owned(),
9762            }
9763        );
9764    }
9765
9766    #[test]
9767    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
9768        let state = Interrupt::Running {
9769            parked: vec!["running".to_owned()],
9770            interrupt_task: "marked".to_owned(),
9771        };
9772        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
9773        assert_eq!(still_running, state);
9774
9775        // Whatever it ended as - merged, failed, held - is not this
9776        // function's concern: leaving flight is the only trigger, driven
9777        // straight off the same in-flight list `poll` already reaps. It does
9778        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
9779        // why that would let an unrelated task start ahead of, or alongside,
9780        // the guaranteed resume.
9781        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
9782        assert_eq!(
9783            ended,
9784            Interrupt::Resuming {
9785                parked: vec!["running".to_owned()]
9786            }
9787        );
9788    }
9789
9790    #[test]
9791    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
9792        let state = Interrupt::Resuming {
9793            parked: vec!["running".to_owned()],
9794        };
9795        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
9796        assert_eq!(still_waiting, state);
9797
9798        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
9799        assert_eq!(dispatched, Interrupt::Idle);
9800    }
9801
9802    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
9803    /// or otherwise moved on by an operator with no claim standing in the
9804    /// way - must not wedge the sequence (and so the whole loop's dispatch,
9805    /// via `interrupt_gate`) waiting forever for a dispatch that can never
9806    /// come. The parked run still gets its resume.
9807    #[test]
9808    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
9809    {
9810        let state = Interrupt::Parking {
9811            parked: vec!["running".to_owned()],
9812            interrupt_task: "marked".to_owned(),
9813        };
9814        // `marked` has been held/blocked/deleted since the sequence began:
9815        // it no longer appears in `runnable` at all.
9816        let next = advance_interrupt(state, &[], &[]);
9817        assert_eq!(
9818            next,
9819            Interrupt::Resuming {
9820                parked: vec!["running".to_owned()]
9821            },
9822            "abandoning the interrupt must not abandon the resume it owes"
9823        );
9824    }
9825
9826    /// The same abandonment, one step later: `Resuming` itself must not wait
9827    /// forever for a parked task that has since become unrunnable.
9828    #[test]
9829    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
9830        let state = Interrupt::Resuming {
9831            parked: vec!["running".to_owned()],
9832        };
9833        let next = advance_interrupt(state, &[], &[]);
9834        assert_eq!(
9835            next,
9836            Interrupt::Idle,
9837            "nothing is left to wait for; the loop must not stay wedged"
9838        );
9839    }
9840
9841    #[test]
9842    fn disabled_by_config_the_sequence_can_never_leave_idle() {
9843        let marked = interrupt_task("marked");
9844        let next = advance_interrupt_tick(
9845            false,
9846            Interrupt::Idle,
9847            &["running".to_owned()],
9848            std::slice::from_ref(&marked),
9849        );
9850        assert_eq!(
9851            next,
9852            Interrupt::Idle,
9853            "an unmarked, unconfigured daemon must behave exactly as before"
9854        );
9855    }
9856
9857    #[test]
9858    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
9859        let state = Interrupt::Parking {
9860            parked: vec!["running".to_owned()],
9861            interrupt_task: "marked".to_owned(),
9862        };
9863        let candidates = vec![interrupt_task("marked"), task()];
9864        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9865        assert!(
9866            allowed.is_empty(),
9867            "nothing may dispatch - not even the interrupt task itself - \
9868             until the parked run has actually stopped"
9869        );
9870    }
9871
9872    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
9873    /// grow a special case for it: an urgent candidate that is not the
9874    /// interrupt task withholds exactly like an ordinary one for as long as
9875    /// the parked run it is racing has not actually left flight. A version
9876    /// of this feature once bypassed the gate for urgent candidates, on the
9877    /// theory that a genuinely separate concurrency lane could not collide
9878    /// with 75dd's own; it could, and did - the bypassed task dispatched
9879    /// alongside a run 75dd's own state machine had only *asked* to park,
9880    /// not yet confirmed gone, which is exactly the second run
9881    /// `Interrupt::Parking`'s own doc says must never happen. There is no
9882    /// tick during Parking/Running/Resuming where letting an extra
9883    /// candidate through is safe, urgent or not - the parked run may still
9884    /// be genuinely mid-call.
9885    #[test]
9886    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
9887        for state in [
9888            Interrupt::Parking {
9889                parked: vec!["running".to_owned()],
9890                interrupt_task: "marked".to_owned(),
9891            },
9892            Interrupt::Running {
9893                parked: vec!["running".to_owned()],
9894                interrupt_task: "marked".to_owned(),
9895            },
9896            Interrupt::Resuming {
9897                parked: vec!["running".to_owned()],
9898            },
9899        ] {
9900            let candidates = vec![
9901                interrupt_task("marked"),
9902                urgent_task("hot"),
9903                task_with_id("ordinary"),
9904            ];
9905            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
9906            assert!(
9907                !allowed.iter().any(|t| t.id == "hot"),
9908                "an urgent candidate must wait out the same gate as anything \
9909                 else while the run it would run alongside has not actually \
9910                 left flight, for state {state:?}: {allowed:?}"
9911            );
9912        }
9913    }
9914
9915    /// The one case where marking a task `--urgent` and `interrupt` at once
9916    /// is not redundant: once the interrupt sequence's own guaranteed
9917    /// resume/dispatch actually admits the task, it is unaffected by also
9918    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
9919    /// never on the urgent flag.
9920    #[test]
9921    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
9922        let state = Interrupt::Resuming {
9923            parked: vec!["hot".to_owned()],
9924        };
9925        let candidates = vec![urgent_task("hot"), task()];
9926        let allowed = interrupt_gate(&state, &[], candidates);
9927        assert_eq!(
9928            allowed.iter().filter(|t| t.id == "hot").count(),
9929            1,
9930            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
9931        );
9932    }
9933
9934    #[test]
9935    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
9936        let state = Interrupt::Parking {
9937            parked: vec!["running".to_owned()],
9938            interrupt_task: "marked".to_owned(),
9939        };
9940        let other = task();
9941        let candidates = vec![interrupt_task("marked"), other.clone()];
9942        let allowed = interrupt_gate(&state, &[], candidates);
9943        assert_eq!(allowed.len(), 1);
9944        assert_eq!(allowed[0].id, "marked");
9945    }
9946
9947    #[test]
9948    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
9949        let state = Interrupt::Running {
9950            parked: vec!["running".to_owned()],
9951            interrupt_task: "marked".to_owned(),
9952        };
9953        let candidates = vec![task(), task()];
9954        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
9955        assert!(allowed.is_empty());
9956    }
9957
9958    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
9959    /// sequence began (only reachable above the default
9960    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
9961    /// never both in the same tick, which is what "exactly one resume, no
9962    /// simultaneous run" actually requires structurally rather than by
9963    /// coincidence of how many ordinary slots happen to be free.
9964    #[test]
9965    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
9966        let state = Interrupt::Resuming {
9967            parked: vec!["a".to_owned(), "c".to_owned()],
9968        };
9969        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
9970        let allowed = interrupt_gate(&state, &[], candidates);
9971        assert_eq!(
9972            allowed.len(),
9973            1,
9974            "at most one candidate may be offered while resuming: {allowed:?}"
9975        );
9976        assert_eq!(allowed[0].id, "a");
9977    }
9978
9979    #[test]
9980    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
9981        let state = Interrupt::Resuming {
9982            parked: vec!["a".to_owned()],
9983        };
9984        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
9985        assert!(allowed.is_empty());
9986    }
9987
9988    /// The invariant the completion criteria ask for by name: across a whole
9989    /// simulated sequence, there is never a tick where the gate would let
9990    /// through both the parked run's resume and the interrupt task, and
9991    /// exactly one candidate resumes the instant the interrupt task's run
9992    /// ends - never zero, never more than one.
9993    #[test]
9994    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
9995        let running = task(); // id: whatever `Task::new` minted
9996        let marked = interrupt_task("marked");
9997
9998        let mut state = Interrupt::Idle;
9999        // Tick 1: `running` is in flight, `marked` becomes runnable.
10000        let in_flight = vec![running.id.clone()];
10001        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
10002        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
10003        assert!(gated.is_empty(), "still waiting on `running` to park");
10004
10005        // Tick 2: `running` parked and left flight; nothing dispatched yet.
10006        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
10007        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
10008        assert_eq!(
10009            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10010            vec!["marked"],
10011            "only the interrupt task may be offered to the dispatcher now"
10012        );
10013
10014        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
10015        state = advance_interrupt_tick(
10016            true,
10017            state,
10018            &["marked".to_owned()],
10019            std::slice::from_ref(&running),
10020        );
10021        let gated = interrupt_gate(
10022            &state,
10023            &["marked".to_owned()],
10024            vec![marked.clone(), running.clone()],
10025        );
10026        assert!(
10027            gated.is_empty(),
10028            "the parked run must not be offered back while the interrupt \
10029             task is still running"
10030        );
10031
10032        // Tick 4: `marked`'s run reached a terminal status and left flight.
10033        // A higher-priority ordinary task `other` is also runnable now - it
10034        // must not be let through instead of, or alongside, `running`.
10035        let other = task_with_id("other");
10036        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
10037        assert_eq!(
10038            state,
10039            Interrupt::Resuming {
10040                parked: vec![running.id.clone()]
10041            }
10042        );
10043        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
10044        assert_eq!(
10045            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10046            vec![running.id.as_str()],
10047            "exactly the parked run resumes - not the unrelated task, even \
10048             though it was offered first"
10049        );
10050
10051        // Tick 5: `running` is now in flight (dispatched from tick 4's
10052        // gate). Only now does the sequence end and ordinary dispatch fully
10053        // resume.
10054        state = advance_interrupt_tick(
10055            true,
10056            state,
10057            std::slice::from_ref(&running.id),
10058            std::slice::from_ref(&other),
10059        );
10060        assert_eq!(state, Interrupt::Idle);
10061        let gated = interrupt_gate(
10062            &state,
10063            std::slice::from_ref(&running.id),
10064            vec![other.clone()],
10065        );
10066        assert_eq!(
10067            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10068            vec![other.id.as_str()],
10069            "ordinary dispatch is unrestricted again"
10070        );
10071    }
10072
10073    #[test]
10074    fn every_run_status_settles_the_task_it_came_from() {
10075        // run status, resulting task status, attempts still standing after one
10076        let table = [
10077            (RunStatus::Merged, TaskStatus::Done, 1),
10078            (RunStatus::Ready, TaskStatus::Done, 1),
10079            (RunStatus::Stalled, TaskStatus::Failed, 0),
10080            (RunStatus::Blocked, TaskStatus::Failed, 1),
10081            (RunStatus::Failed, TaskStatus::Failed, 1),
10082            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
10083            (RunStatus::Prep, TaskStatus::Failed, 1),
10084            (RunStatus::Implementing, TaskStatus::Failed, 1),
10085            (RunStatus::Judging, TaskStatus::Failed, 1),
10086            (RunStatus::Deliberating, TaskStatus::Failed, 1),
10087            (RunStatus::Voting, TaskStatus::Failed, 1),
10088            (RunStatus::Reviewing, TaskStatus::Failed, 1),
10089            (RunStatus::Gating, TaskStatus::Failed, 1),
10090        ];
10091        for (run, want, attempts) in table {
10092            let mut t = task();
10093            t.start("20260902-000000-aaaa".to_owned());
10094            settle(
10095                &mut t,
10096                Verdict {
10097                    status: run,
10098                    left_pr: false,
10099                    parked: false,
10100                    quota_hit: matches!(run, RunStatus::Stalled),
10101                    no_viable_candidates: false,
10102                },
10103                "why",
10104                2,
10105            );
10106            assert_eq!(t.status, want, "task status after {}", label(run));
10107            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
10108        }
10109    }
10110
10111    #[test]
10112    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
10113        let mut stalled = task();
10114        stalled.start("20260902-000000-aaaa".to_owned());
10115        settle(
10116            &mut stalled,
10117            Verdict {
10118                status: RunStatus::Stalled,
10119                left_pr: false,
10120                parked: false,
10121                quota_hit: true,
10122                no_viable_candidates: false,
10123            },
10124            "quota",
10125            1,
10126        );
10127        assert_eq!(stalled.attempts, 0);
10128        assert!(
10129            stalled.status.runnable(),
10130            "a machine problem must leave the task in line"
10131        );
10132
10133        let mut blocked = task();
10134        blocked.start("20260902-000000-aaaa".to_owned());
10135        settle(
10136            &mut blocked,
10137            Verdict {
10138                status: RunStatus::Blocked,
10139                left_pr: false,
10140                parked: false,
10141                quota_hit: false,
10142                no_viable_candidates: false,
10143            },
10144            "findings open",
10145            1,
10146        );
10147        assert_eq!(blocked.attempts, 1);
10148        assert_eq!(
10149            blocked.status,
10150            TaskStatus::Held,
10151            "the last attempt hands the task to a human"
10152        );
10153    }
10154
10155    #[test]
10156    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
10157        // Attempts to spare: without the pull request this task would go
10158        // straight back in line and run the whole competition again.
10159        let mut delivered = task();
10160        delivered.start("20260903-080619-01c2".to_owned());
10161        settle(
10162            &mut delivered,
10163            Verdict {
10164                status: RunStatus::Blocked,
10165                left_pr: true,
10166                parked: false,
10167                quota_hit: false,
10168                no_viable_candidates: false,
10169            },
10170            "no check status",
10171            4,
10172        );
10173        assert_eq!(
10174            delivered.status,
10175            TaskStatus::Held,
10176            "a pull request waiting on CI or a person is not a retryable failure"
10177        );
10178        assert!(
10179            !delivered.status.runnable(),
10180            "the loop must not pick this task up again"
10181        );
10182        assert_eq!(
10183            delivered.last_error.as_deref(),
10184            Some("no check status"),
10185            "the operator needs to be told what the gate was waiting for"
10186        );
10187
10188        // The same status without a pull request is a plain failure, and with
10189        // attempts left it is retried.
10190        let mut empty_handed = task();
10191        empty_handed.start("20260903-080619-01c2".to_owned());
10192        settle(
10193            &mut empty_handed,
10194            Verdict {
10195                status: RunStatus::Blocked,
10196                left_pr: false,
10197                parked: false,
10198                quota_hit: false,
10199                no_viable_candidates: false,
10200            },
10201            "findings open",
10202            4,
10203        );
10204        assert_eq!(empty_handed.status, TaskStatus::Failed);
10205        assert!(empty_handed.status.runnable());
10206    }
10207
10208    #[test]
10209    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
10210        // Every candidate agreed, with evidence, that nothing belonged in the
10211        // worktree. That is not a confirmed success to close automatically -
10212        // a human still has to check the claim - and it is not an ordinary
10213        // failure either, so this settles exactly like a pull request nobody
10214        // merged yet: `Held`, same as `Blocked` with a PR.
10215        let mut noop = task();
10216        noop.start("20260912-131304-391f".to_owned());
10217        settle(
10218            &mut noop,
10219            Verdict {
10220                status: RunStatus::VerifiedNoop,
10221                left_pr: false,
10222                parked: false,
10223                quota_hit: false,
10224                no_viable_candidates: true,
10225            },
10226            "candidate A: already fixed by b32cfc4, on main",
10227            4,
10228        );
10229        assert_eq!(
10230            noop.status,
10231            TaskStatus::Held,
10232            "an unverified claim is a request for a human, not a failure"
10233        );
10234        assert!(
10235            !noop.status.runnable(),
10236            "the loop must not requeue this on the same unverified claim"
10237        );
10238        // `Task::release` resets attempts to zero the moment a human looks at
10239        // the evidence and lets it run again, so it does not matter here
10240        // whether the one attempt already spent stays spent - what matters is
10241        // that nothing retries this task unattended in the meantime.
10242        assert_eq!(noop.attempts, 1);
10243    }
10244
10245    #[test]
10246    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
10247        // Parking is the operator asking for the process back - to replace the
10248        // binary, most of all. The run's work is intact on disk, so this is
10249        // not a failed attempt, and charging for it would mean a few upgrades
10250        // could exhaust a budget meant for agents that misbehaved.
10251        let mut parked = task();
10252        parked.start("20260903-183634-2d98".to_owned());
10253        settle(
10254            &mut parked,
10255            Verdict {
10256                status: RunStatus::Implementing,
10257                left_pr: false,
10258                quota_hit: false,
10259                parked: true,
10260                no_viable_candidates: false,
10261            },
10262            "parked after `implementing`",
10263            2,
10264        );
10265        assert_eq!(parked.attempts, 0, "a park is refunded");
10266        assert!(
10267            parked.status.runnable(),
10268            "and the task stays in line so the next loop resumes its run"
10269        );
10270        assert_eq!(parked.status, TaskStatus::Parked);
10271        assert_eq!(
10272            parked.park_reason.as_deref(),
10273            Some("parked after `implementing`"),
10274            "the card says where it stopped"
10275        );
10276        assert_eq!(parked.last_error, None, "nothing failed");
10277
10278        // Without the park flag the same non-terminal status is what it always
10279        // was: `execute` returning mid-flight, which is a bug and spends an
10280        // attempt so a task cannot loop on it forever.
10281        let mut broken = task();
10282        broken.start("20260903-183634-2d98".to_owned());
10283        settle(
10284            &mut broken,
10285            Verdict {
10286                status: RunStatus::Implementing,
10287                left_pr: false,
10288                quota_hit: false,
10289                parked: false,
10290                no_viable_candidates: false,
10291            },
10292            "returned mid-flight",
10293            2,
10294        );
10295        assert_eq!(broken.attempts, 1);
10296    }
10297
10298    #[test]
10299    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
10300        // Run e633: quorum lost because two judges answered with the wrong
10301        // JSON shape, `quota: []`. Refunding that takes the bound off the
10302        // retry loop, and each retry pays for a fresh hour-long implement
10303        // wave before it can fail the same way.
10304        let mut flaky = task();
10305        flaky.start("20260903-123023-e633".to_owned());
10306        settle(
10307            &mut flaky,
10308            Verdict {
10309                status: RunStatus::Stalled,
10310                left_pr: false,
10311                parked: false,
10312                quota_hit: false,
10313                no_viable_candidates: false,
10314            },
10315            "verdict rests on 1 of 3 judges",
10316            2,
10317        );
10318        assert_eq!(
10319            flaky.attempts, 1,
10320            "flakiness spends an attempt, so `max_attempts` still bounds it"
10321        );
10322        assert!(flaky.status.runnable(), "and it is still worth retrying");
10323
10324        // The same status, lost to a rate limit, is the machine's fault.
10325        let mut limited = task();
10326        limited.start("20260903-123023-e633".to_owned());
10327        settle(
10328            &mut limited,
10329            Verdict {
10330                status: RunStatus::Stalled,
10331                left_pr: false,
10332                parked: false,
10333                quota_hit: true,
10334                no_viable_candidates: false,
10335            },
10336            "judge-2, judge-3 out of quota",
10337            2,
10338        );
10339        assert_eq!(limited.attempts, 0, "a quota window is refunded");
10340        assert!(limited.status.runnable());
10341
10342        // And the bound really binds: a task that keeps stalling on flakiness
10343        // reaches a human instead of running the roster forever.
10344        let mut worn = task();
10345        for _ in 0..2 {
10346            worn.release();
10347        }
10348        worn.start("20260903-123023-e633".to_owned());
10349        worn.attempts = 2;
10350        settle(
10351            &mut worn,
10352            Verdict {
10353                status: RunStatus::Stalled,
10354                left_pr: false,
10355                parked: false,
10356                quota_hit: false,
10357                no_viable_candidates: false,
10358            },
10359            "no quorum again",
10360            2,
10361        );
10362        assert_eq!(worn.status, TaskStatus::Held);
10363        assert!(!worn.status.runnable());
10364    }
10365
10366    #[test]
10367    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
10368        // The implement wave loses every seat to the same rate limit and
10369        // `after_implement` bails with nothing viable, which surfaces as
10370        // `Failed` rather than `Stalled`. That is the same machine fact the
10371        // `Stalled`-quota row already refunds, and must be refunded the same
10372        // way, or a quota outage quietly holds every task it touches instead
10373        // of leaving them in line for the reset.
10374        let mut wiped_out = task();
10375        wiped_out.start("20260907-025000-a1b2".to_owned());
10376        settle(
10377            &mut wiped_out,
10378            Verdict {
10379                status: RunStatus::Failed,
10380                left_pr: false,
10381                parked: false,
10382                quota_hit: true,
10383                no_viable_candidates: true,
10384            },
10385            "no candidate produced a change; nothing to judge",
10386            2,
10387        );
10388        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
10389        assert!(
10390            wiped_out.status.runnable(),
10391            "a machine problem must leave the task in line"
10392        );
10393
10394        // This is the exemption that must stay narrow: a candidate that did
10395        // produce a change, and then failed for some other reason, still
10396        // spends the attempt even though a seat elsewhere hit its quota.
10397        // Otherwise every ordinary failure that happens to share a run with
10398        // an unrelated rate limit would be refunded for free.
10399        let mut partial_progress = task();
10400        partial_progress.start("20260907-025500-c3d4".to_owned());
10401        settle(
10402            &mut partial_progress,
10403            Verdict {
10404                status: RunStatus::Failed,
10405                left_pr: false,
10406                parked: false,
10407                quota_hit: true,
10408                no_viable_candidates: false,
10409            },
10410            "gate failed on the winning candidate",
10411            2,
10412        );
10413        assert_eq!(
10414            partial_progress.attempts, 1,
10415            "a candidate that actually produced a change spends the attempt \
10416             even though some other seat hit its quota"
10417        );
10418        assert!(partial_progress.status.runnable());
10419    }
10420
10421    #[test]
10422    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
10423        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
10424        // disk, and that construction must reach the same conclusion as the
10425        // one `attempt` builds from a live run, or a crash at exactly the
10426        // wrong moment gives a recovered task a different policy than one a
10427        // daemon finished settling itself.
10428        let mut t = task();
10429        t.start("20260907-025000-a1b2".to_owned());
10430        let mut state = run_state(RunStatus::Failed);
10431        state.quota.push(QuotaLoss {
10432            cause: crate::agent::QuotaCause::UsageLimit,
10433            agent: String::new(),
10434            seat: "cand-a".to_owned(),
10435            node: "implement".to_owned(),
10436            at: Timestamp::now(),
10437            reset: None,
10438        });
10439        assert!(
10440            state.viable().is_empty(),
10441            "no candidate was added, so nothing is viable"
10442        );
10443        reclaim(&mut t, Some(state), 2, "en");
10444        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
10445        assert!(t.status.runnable());
10446    }
10447
10448    #[test]
10449    fn a_held_task_is_never_offered_to_the_loop() {
10450        let dir = tempfile::tempdir().unwrap();
10451        let queue = Queue::at(dir.path().to_path_buf());
10452        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
10453            let mut t = task();
10454            t.id = format!("2026090{n}-000000-000{n}");
10455            t.priority = priority;
10456            queue.put(&mut t).unwrap();
10457        }
10458        let mut held = task();
10459        held.id = "20260909-000000-9999".to_owned();
10460        held.priority = 99;
10461        held.hold_machine(None);
10462        queue.put(&mut held).unwrap();
10463
10464        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
10465        assert_eq!(order.len(), 3);
10466        assert!(!order.contains(&held.id));
10467        assert_eq!(
10468            order.first().cloned(),
10469            queue.next_runnable().map(|t| t.id),
10470            "the loop's first candidate is exactly what the queue offers"
10471        );
10472        assert_eq!(
10473            order,
10474            vec![
10475                "20260902-000000-0002".to_owned(),
10476                "20260903-000000-0003".to_owned(),
10477                "20260901-000000-0001".to_owned(),
10478            ],
10479            "priority first, then oldest, so nothing starves"
10480        );
10481    }
10482
10483    #[test]
10484    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
10485        let dir = tempfile::tempdir().unwrap();
10486        let queue = Queue::at(dir.path().to_path_buf());
10487        let mut old = task();
10488        old.id = "20260101-000000-old0".to_owned();
10489        queue.put(&mut old).unwrap();
10490        let mut fresh = task();
10491        fresh.id = "20260101-000000-new0".to_owned();
10492        queue.put(&mut fresh).unwrap();
10493
10494        // No parseable pid at all, so age is the only signal there is to
10495        // check - unlike a real `Queue::claim`, which always names a real,
10496        // and therefore alive, pid this test cannot fake as dead.
10497        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
10498        std::thread::sleep(Duration::from_millis(60));
10499        let live = queue.claim(&fresh.id).unwrap();
10500
10501        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10502        assert_eq!(swept, vec![old.id.clone()]);
10503        assert!(
10504            queue.claim(&old.id).is_ok(),
10505            "an unparseable lock older than the threshold is swept"
10506        );
10507        assert!(
10508            queue.claim(&fresh.id).is_err(),
10509            "a live pid protects its lock regardless of age"
10510        );
10511        drop(live);
10512    }
10513
10514    #[test]
10515    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
10516        // A live worker's claim remains authoritative even beyond the sweep's
10517        // age limit. Sweeping it would permit a second competing attempt.
10518        let dir = tempfile::tempdir().unwrap();
10519        let queue = Queue::at(dir.path().to_path_buf());
10520        let mut t = task();
10521        t.id = "20260101-000000-live".to_owned();
10522        queue.put(&mut t).unwrap();
10523
10524        let claim = queue.claim(&t.id).unwrap();
10525        std::thread::sleep(Duration::from_millis(60));
10526
10527        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10528        assert!(
10529            swept.is_empty(),
10530            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
10531        );
10532        assert!(
10533            queue.claim(&t.id).is_err(),
10534            "the lock still protects its task"
10535        );
10536        drop(claim);
10537    }
10538
10539    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
10540    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
10541    fn injected_dead_pid() -> u32 {
10542        std::process::id().checked_add(1).unwrap_or(1)
10543    }
10544
10545    #[test]
10546    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
10547        let dir = tempfile::tempdir().unwrap();
10548        let queue = Queue::at(dir.path().to_path_buf());
10549        let mut t = task();
10550        t.id = "20260101-000000-dead".to_owned();
10551        queue.put(&mut t).unwrap();
10552        let dead_pid = injected_dead_pid();
10553
10554        // Written directly rather than through `Queue::claim`, which would
10555        // stamp this test process's own very much alive pid and defeat the
10556        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
10557        // like moments after it died, not six hours later.
10558        std::fs::write(
10559            dir.path().join(format!("{}.lock", t.id)),
10560            dead_pid.to_string(),
10561        )
10562        .unwrap();
10563
10564        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10565            pid != dead_pid
10566        });
10567        assert_eq!(
10568            swept,
10569            vec![t.id.clone()],
10570            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
10571        );
10572        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
10573    }
10574
10575    #[test]
10576    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
10577        let dir = tempfile::tempdir().unwrap();
10578        let queue = Queue::at(dir.path().to_path_buf());
10579        let mut t = task();
10580        t.id = "20260101-000000-late".to_owned();
10581        queue.put(&mut t).unwrap();
10582        let dead_pid = injected_dead_pid();
10583
10584        // Tick one, standing in for the sweep `poll` already runs at
10585        // startup: nothing to find yet.
10586        assert!(
10587            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
10588            "nothing has claimed the task yet"
10589        );
10590
10591        // A second daemon claims the task and dies before it ever writes
10592        // `running`, well after this loop's own startup sweep already ran.
10593        std::fs::write(
10594            dir.path().join(format!("{}.lock", t.id)),
10595            dead_pid.to_string(),
10596        )
10597        .unwrap();
10598
10599        // Tick two, standing in for a poll long into this daemon's uptime:
10600        // the same function, called again, notices what only just appeared -
10601        // proving the sweep is not a one-shot startup check.
10602        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10603            pid != dead_pid
10604        });
10605        assert_eq!(swept, vec![t.id.clone()]);
10606    }
10607
10608    #[test]
10609    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
10610        // `reclaim_orphaned_running` looks up the task's last run, which
10611        // touches `run::home()`; the first call anywhere in this binary wins,
10612        // so this is a no-op if another test already pinned one, and either
10613        // way the run id below is never written under it.
10614        crate::run::pin_test_home();
10615        let dir = tempfile::tempdir().unwrap();
10616        let queue = Queue::at(dir.path().to_path_buf());
10617        let mut t = task();
10618        t.id = "20260101-000000-crsh".to_owned();
10619        t.status = TaskStatus::Running;
10620        t.attempts = 1;
10621        // No `run.json` behind this id: standing in for a run this test does
10622        // not need to make readable, since the point is the lock, not the
10623        // recovery table `reclaim` already has its own tests for.
10624        t.runs.push("20260904-000000-4043".to_owned());
10625        queue.put(&mut t).unwrap();
10626        let dead_pid = injected_dead_pid();
10627
10628        // The crashed daemon's own claim, naming a pid nothing on the
10629        // machine holds anymore.
10630        std::fs::write(
10631            dir.path().join(format!("{}.lock", t.id)),
10632            dead_pid.to_string(),
10633        )
10634        .unwrap();
10635
10636        // Before the lock is swept the task looks claimed, and
10637        // `reclaim_orphaned_running` must leave it alone - this is exactly
10638        // the bug: a `running` task stranded behind a dead daemon's lock,
10639        // invisible to the claim-as-proof check because the lock outlived
10640        // the process that wrote it.
10641        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
10642        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10643
10644        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10645            pid != dead_pid
10646        });
10647        assert_eq!(swept, vec![t.id.clone()]);
10648
10649        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10650        assert_eq!(reclaimed, vec![t.id.clone()]);
10651        let after = queue.get(&t.id).unwrap();
10652        assert_eq!(
10653            after.status,
10654            TaskStatus::Held,
10655            "no run.json to recover from, so a human is asked"
10656        );
10657        assert_eq!(
10658            after.runs,
10659            vec!["20260904-000000-4043".to_owned()],
10660            "the crashed run's id is kept as evidence, not discarded"
10661        );
10662    }
10663
10664    #[test]
10665    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
10666        let dir = tempfile::tempdir().unwrap();
10667        let queue = Queue::at(dir.path().to_path_buf());
10668        let mut t = task();
10669        t.id = "20260101-000000-unknown".to_owned();
10670        queue.put(&mut t).unwrap();
10671        let dead_pid = injected_dead_pid();
10672        std::fs::write(
10673            dir.path().join(format!("{}.lock", t.id)),
10674            dead_pid.to_string(),
10675        )
10676        .unwrap();
10677
10678        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
10679        assert!(swept.is_empty(), "an unknown pid must keep its lock");
10680        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
10681    }
10682
10683    fn run_state_in(status: RunStatus, language: &str) -> RunState {
10684        let mut s = run_state(status);
10685        s.config.graph.language = language.to_owned();
10686        s
10687    }
10688
10689    fn unstarted_verdict(status: RunStatus) -> Verdict {
10690        Verdict {
10691            status,
10692            left_pr: false,
10693            quota_hit: false,
10694            parked: false,
10695            no_viable_candidates: false,
10696        }
10697    }
10698
10699    #[test]
10700    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
10701        let mut t = task();
10702        t.attempts = 1;
10703        settle_in(
10704            &mut t,
10705            unstarted_verdict(RunStatus::AlreadyInBase),
10706            "already in main",
10707            1,
10708            phrases("en"),
10709            None,
10710        );
10711        assert_eq!(t.status, TaskStatus::Done);
10712        assert_eq!(t.attempts, 0);
10713    }
10714
10715    #[test]
10716    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
10717        let reason = |language: &str| {
10718            let mut t = task();
10719            settle_in(
10720                &mut t,
10721                unstarted_verdict(RunStatus::Judging),
10722                "boom",
10723                1,
10724                phrases(language),
10725                None,
10726            );
10727            t.last_error.or(t.hold_reason).unwrap_or_default()
10728        };
10729        assert!(
10730            reason("en").starts_with("the graph stopped at `"),
10731            "{}",
10732            reason("en")
10733        );
10734        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
10735        assert!(reason("日本語").contains("boom"));
10736        assert_eq!(reason("fr"), reason("en"));
10737    }
10738
10739    #[test]
10740    fn describe_follows_the_run_language_and_keeps_the_run_id() {
10741        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
10742        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
10743        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
10744        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
10745        assert!(ja.contains("[run "), "{ja}");
10746        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
10747        assert!(ended.starts_with("run 終了: "), "{ended}");
10748        let mut de = run_state_in(RunStatus::Failed, "de");
10749        let mut en = run_state_in(RunStatus::Failed, "en");
10750        de.id = "same".to_owned();
10751        en.id = "same".to_owned();
10752        assert_eq!(describe(&de), describe(&en));
10753    }
10754
10755    #[test]
10756    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
10757        use crate::handover::Refused;
10758        let cases = [
10759            Refused::Foreign {
10760                branch: "b".into(),
10761                path: "/w/x".into(),
10762                why: "made by hand".into(),
10763            },
10764            Refused::Unsafe {
10765                branch: "b".into(),
10766                path: "/w/x".into(),
10767                why: "its worktree has uncommitted changes (a.rs)".into(),
10768            },
10769            Refused::ReleaseFailed {
10770                branch: "b".into(),
10771                path: "/w/x".into(),
10772                run: "ab12".into(),
10773            },
10774        ];
10775        for r in &cases {
10776            let en = (phrases("en").handover_refused)(r);
10777            assert_eq!(en, r.to_string());
10778            let ja = (phrases("ja").handover_refused)(r);
10779            assert!(
10780                !ja.contains("is checked out") && !ja.contains("try again"),
10781                "{ja}"
10782            );
10783            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
10784            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
10785                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
10786            }
10787        }
10788        assert!(phrases("en").handover_hint.contains("release the task"));
10789        assert!(phrases("ja").handover_hint.contains("解放"));
10790    }
10791
10792    #[test]
10793    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
10794        let build = |lang: &str| {
10795            let mut s = run_state_in(RunStatus::Blocked, lang);
10796            s.id = "same".to_owned();
10797            s.config.graph.review_rounds = 3;
10798            let mut r = review_round(3);
10799            r.expected = 3;
10800            r.answered = 1;
10801            s.reviews.push(r);
10802            s.event(
10803                "review",
10804                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
10805            );
10806            s
10807        };
10808        let en = describe(&build("en"));
10809        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
10810        let ja = describe(&build("ja"));
10811        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
10812        assert!(!ja.contains("never answered"), "{ja}");
10813        assert!(ja.contains("[run "), "{ja}");
10814
10815        // An incomplete panel whose verification failed is a different stop:
10816        // the real event must survive in ja too.
10817        let mut failed = build("ja");
10818        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
10819            command: "cargo test".to_owned(),
10820            code: Some(1),
10821            output_tail: String::new(),
10822            duration_ms: 0,
10823            resource_blocked: false,
10824            ..Default::default()
10825        });
10826        failed.event("review", "stopped; e2e failed: cargo test");
10827        let ja = describe(&failed);
10828        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
10829        assert!(!ja.contains("席のレビュアー"), "{ja}");
10830    }
10831
10832    #[test]
10833    fn refusals_and_recovery_prose_follow_the_language() {
10834        let home = crate::run::test_home();
10835        let t = held_task_with("r1");
10836        let q = action_question(
10837            "r1",
10838            ask::ChoiceAction::Resume {
10839                run: "r1".to_owned(),
10840            },
10841        );
10842        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
10843            ActionDecision::Refuse(s) => s,
10844            other => panic!("{other:?}"),
10845        };
10846        assert!(refuse(phrases("en")).contains("could not be read: gone"));
10847        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
10848        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
10849
10850        let mut held = task();
10851        reclaim(&mut held, None, 2, "ja");
10852        assert!(held.hold_reason.unwrap().contains("保留にしました"));
10853        let mut held = task();
10854        reclaim(&mut held, None, 2, "xx");
10855        assert!(held.hold_reason.unwrap().contains("held for a human"));
10856    }
10857
10858    fn run_state(status: RunStatus) -> RunState {
10859        let mut state = RunState::new(
10860            PathBuf::from("/repo"),
10861            "main".to_owned(),
10862            "abc1234def".to_owned(),
10863            "add retries".to_owned(),
10864            Config::default(),
10865        );
10866        state.status = status;
10867        state
10868    }
10869
10870    #[test]
10871    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
10872        crate::run::pin_test_home();
10873        let dir = tempfile::tempdir().unwrap();
10874        let mut state = run_state(RunStatus::Blocked);
10875        state.id = "20260101-000000-audit".into();
10876        state.save_under(dir.path()).unwrap();
10877        let mut t = task();
10878        t.start(state.id.clone());
10879        // The final state is newer than disk, as when a worker settles its
10880        // in-memory outcome or recovery is passed an already loaded run.
10881        state.status = RunStatus::Ready;
10882        settle_and_diagnose(
10883            &mut t,
10884            unstarted_verdict(RunStatus::Ready),
10885            "Verified local delivery",
10886            2,
10887            &state,
10888        );
10889        let completion = t.completion_history.last().unwrap();
10890        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
10891        assert_eq!(completion.prior_status, TaskStatus::Running);
10892        assert_eq!(
10893            completion.reason.as_deref(),
10894            Some("Verified local delivery")
10895        );
10896        let snapshot = completion.run.as_ref().unwrap();
10897        assert_eq!(snapshot.id, state.id);
10898        assert_eq!(snapshot.status, Some(RunStatus::Ready));
10899        assert_eq!(
10900            RunState::load_under(&state.id, dir.path()).unwrap().status,
10901            RunStatus::Blocked,
10902            "settlement records the actual outcome without rewriting run history"
10903        );
10904    }
10905
10906    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
10907        Candidate {
10908            index: 0,
10909            label,
10910            agent: "claude".to_owned(),
10911            branch: format!("magi/x/{label}"),
10912            worktree: PathBuf::from("/repo"),
10913            summary: summary.to_owned(),
10914            stat: String::new(),
10915            files: 0,
10916            commits: usize::from(!empty),
10917            empty,
10918            failed: failed.map(str::to_owned),
10919            verified_noop: None,
10920            duration_ms: 0,
10921            folded: false,
10922        }
10923    }
10924
10925    #[test]
10926    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
10927        let mut state = run_state(RunStatus::Blocked);
10928        state.gate = vec![
10929            CommandOutcome {
10930                command: "cargo make check".to_owned(),
10931                code: Some(0),
10932                output_tail: "ok".to_owned(),
10933                duration_ms: 0,
10934                resource_blocked: false,
10935                ..Default::default()
10936            },
10937            CommandOutcome {
10938                command: "cargo test".to_owned(),
10939                code: Some(101),
10940                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
10941                duration_ms: 0,
10942                resource_blocked: false,
10943                ..Default::default()
10944            },
10945        ];
10946        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
10947        assert!(d.contains("cargo test"), "{d}");
10948        assert!(
10949            !d.contains("cargo make check"),
10950            "a passing check is not a diagnostic: {d}"
10951        );
10952        assert!(d.contains("assertion failed"), "{d}");
10953    }
10954
10955    #[test]
10956    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
10957        let mut state = run_state(RunStatus::Blocked);
10958        state.event(
10959            "land",
10960            "stopped: the fixer produced no commit while 2 check(s) were failing \
10961             (build, lint); stopping instead of looping on an unchanged tree",
10962        );
10963        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
10964        assert!(d.contains("build"), "{d}");
10965        assert!(d.contains("lint"), "{d}");
10966        assert!(d.contains("fixer produced no commit"), "{d}");
10967    }
10968
10969    #[test]
10970    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
10971        // `describe`'s output becomes `Task::last_error` verbatim, and the
10972        // phone renders that in the same alarm-styled box an ordinary
10973        // failure gets. A bare `verified_noop` there would read exactly like
10974        // the failure this status exists to be told apart from.
10975        let state = run_state(RunStatus::VerifiedNoop);
10976        let d = describe(&state);
10977        assert!(
10978            d.contains("agent-verified no-op"),
10979            "expected the display label, not the wire spelling: {d}"
10980        );
10981        assert!(!d.contains("verified_noop"), "{d}");
10982    }
10983
10984    #[test]
10985    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
10986        let mut state = run_state(RunStatus::Failed);
10987        state.gate.push(crate::run::CommandOutcome {
10988            command: "cargo test".into(),
10989            code: Some(101),
10990            output_tail: format!(
10991                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
10992                "  41: 0x1234 - backtrace frame\n".repeat(10000)
10993            ),
10994            duration_ms: 1,
10995            resource_blocked: false,
10996            ..Default::default()
10997        });
10998        let d = diagnostic(&state).unwrap();
10999        assert!(d.contains("panicked at widget.rs:12"), "{d}");
11000        assert!(d.contains("assertion failed: widget missing"));
11001        assert!(d.contains("widget log"));
11002    }
11003
11004    #[test]
11005    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
11006        // The whole point of the feature: a run held as "no candidate produced
11007        // a change" can mean the implementer actually finished the task and
11008        // only left a clean local tree behind - see AGENTS.md on this exact
11009        // failure mode. The diagnostic has to carry what the agent actually
11010        // said, not just the fact that nothing was there to judge.
11011        let mut state = run_state(RunStatus::Failed);
11012        state.candidates = vec![candidate(
11013            'A',
11014            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
11015            true,
11016            None,
11017        )];
11018        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
11019        assert!(d.contains("candidate A"), "{d}");
11020        assert!(d.contains("tagged v1.2.3"), "{d}");
11021    }
11022
11023    #[test]
11024    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
11025        let mut state = run_state(RunStatus::Failed);
11026        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
11027        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
11028        assert!(d.contains("candidate A"), "{d}");
11029        assert!(d.contains("agent timed out"), "{d}");
11030    }
11031
11032    #[test]
11033    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
11034        // A viable candidate existed, the gate never ran, and nothing land
11035        // said matches - `Task::last_error` is left to explain this one alone.
11036        let mut state = run_state(RunStatus::Failed);
11037        state.candidates = vec![candidate('A', "did the work", false, None)];
11038        assert!(diagnostic(&state).is_none());
11039    }
11040
11041    #[test]
11042    fn diagnostic_is_bounded_however_much_a_run_printed() {
11043        let mut state = run_state(RunStatus::Blocked);
11044        state.gate = vec![
11045            CommandOutcome {
11046                command: "cargo test".to_owned(),
11047                code: Some(101),
11048                output_tail: "x".repeat(50_000),
11049                duration_ms: 0,
11050                resource_blocked: false,
11051                ..Default::default()
11052            },
11053            CommandOutcome {
11054                command: "cargo clippy".to_owned(),
11055                code: Some(1),
11056                output_tail: "y".repeat(50_000),
11057                duration_ms: 0,
11058                resource_blocked: false,
11059                ..Default::default()
11060            },
11061        ];
11062        state.candidates = vec![
11063            candidate('A', &"z".repeat(50_000), true, None),
11064            candidate('B', &"w".repeat(50_000), true, None),
11065        ];
11066        let d = diagnostic(&state).expect("plenty here to diagnose");
11067        assert!(
11068            d.len() <= DIAGNOSTIC_MAX,
11069            "diagnostic grew to {} bytes, unbounded",
11070            d.len()
11071        );
11072    }
11073
11074    #[test]
11075    fn selected_delivery_guards_survive_recovery_failure_accounting() {
11076        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
11077            let mut t = task();
11078            let mut state = run_state(status);
11079            t.pr_recovery = Some(crate::pr_recovery::Selection {
11080                url: "url".into(),
11081                branch: format!("magi/task-{}", t.id),
11082                head: "a".repeat(40),
11083                source_head: None,
11084                source_run: None,
11085                source_proof: None,
11086                disposition: Some(crate::pr_recovery::Disposition::Land),
11087                instruction: t.instruction.clone(),
11088                approved_at: Timestamp::now(),
11089            });
11090            state.pr_recovery = t.pr_recovery.clone();
11091            t.start(state.id.clone());
11092            settle_and_diagnose(
11093                &mut t,
11094                Verdict {
11095                    status,
11096                    left_pr: false,
11097                    quota_hit: false,
11098                    parked: false,
11099                    no_viable_candidates: false,
11100                },
11101                "delivery stopped",
11102                5,
11103                &state,
11104            );
11105            assert_eq!(t.status, TaskStatus::Held);
11106            let reason = t.hold_reason.as_deref().unwrap();
11107            if status == RunStatus::Ready {
11108                assert!(reason.contains("Selected PR delivery is incomplete"));
11109                assert!(t.recovery_budget.is_none());
11110            } else {
11111                assert!(reason.contains("Selected recovery stopped"));
11112                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
11113            }
11114            assert!(t.pr_recovery.is_some());
11115        }
11116    }
11117
11118    #[test]
11119    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
11120        let mut state = run_state(RunStatus::Voting);
11121        state.base_sync = Some(crate::run::BaseSync {
11122            tip: "base-tip".into(),
11123            behind: 3,
11124            attempts: 4,
11125            conflict: Some("base stopped".into()),
11126            already_in: None,
11127        });
11128        state.record_base_sync_stop("candidate-head");
11129        let mut t = task();
11130        t.start(state.id.clone());
11131        let verdict = Verdict {
11132            status: RunStatus::Blocked,
11133            left_pr: false,
11134            quota_hit: false,
11135            parked: false,
11136            no_viable_candidates: false,
11137        };
11138        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11139        assert_eq!(
11140            t.status,
11141            TaskStatus::Held,
11142            "unspent task attempts cannot start another competition"
11143        );
11144        let at = t.held_at;
11145        let cause = t.hold_notice_cause.clone();
11146        state.begin_pass();
11147        t.release_operator("test-resume", None);
11148        t.start(state.id.clone());
11149        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11150        assert_eq!(t.status, TaskStatus::Held);
11151        assert_eq!(t.held_at, at);
11152        assert_eq!(t.hold_notice_cause, cause);
11153    }
11154
11155    #[test]
11156    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
11157        let mut state = run_state(RunStatus::Blocked);
11158        state.gate = vec![CommandOutcome {
11159            command: "cargo test".to_owned(),
11160            code: Some(101),
11161            output_tail: "assertion failed".to_owned(),
11162            duration_ms: 0,
11163            resource_blocked: false,
11164            ..Default::default()
11165        }];
11166        let verdict = Verdict {
11167            status: RunStatus::Blocked,
11168            left_pr: false,
11169            quota_hit: false,
11170            parked: false,
11171            no_viable_candidates: false,
11172        };
11173
11174        // Attempt one of two still has a retry coming: no diagnostic yet, the
11175        // task is going to run again and this run's evidence would go stale.
11176        let mut t = task();
11177        t.start("run-1".to_owned());
11178        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11179        assert_eq!(t.status, TaskStatus::Failed);
11180        assert!(t.diagnostic.is_none());
11181
11182        // Attempt two exhausts the budget: now it is held, and the
11183        // diagnostic is what `magi task show` has to say more than one line.
11184        t.start("run-2".to_owned());
11185        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11186        assert_eq!(t.status, TaskStatus::Held);
11187        let d = t.diagnostic.expect("a held task must carry its diagnostic");
11188        assert!(d.contains("cargo test"), "{d}");
11189    }
11190
11191    fn verified_noop_run_state() -> RunState {
11192        let mut state = run_state(RunStatus::VerifiedNoop);
11193        let summary = r#"NO CHANGE NEEDED: {"status":"already_satisfied","requirements":[{"requirement":"requested fix already landed","satisfied":true,"evidence":["c1"]}],"checks":[{"id":"c1","kind":"commit","target":"b32cfc4","method":"git merge-base --is-ancestor b32cfc4 HEAD","observed":"exit 0; b32cfc4 is on main","passed":true}],"unresolved":[]}"#;
11194        let mut c = candidate('A', summary, true, None);
11195        c.verified_noop = Some(summary.to_owned());
11196        state.candidates = vec![c];
11197        state
11198    }
11199
11200    #[test]
11201    fn a_held_task_names_the_open_question_it_is_waiting_on() {
11202        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
11203        // `magi ask` question settled Held with `hold_reason: null`, so the
11204        // notification said nothing actionable. `note_open_question` should
11205        // append the question id to whatever `handed_off` already wrote.
11206        crate::run::pin_test_home();
11207        let home = crate::run::home();
11208        let state = verified_noop_run_state();
11209        let mut q = ask::Question::new(
11210            state.id.clone(),
11211            "implement".to_owned(),
11212            "impl-A".to_owned(),
11213            "is this really a no-op?".to_owned(),
11214            String::new(),
11215            Vec::new(),
11216        );
11217        Questions::at(home.join("questions")).put(&mut q).unwrap();
11218
11219        let verdict = Verdict {
11220            status: RunStatus::VerifiedNoop,
11221            left_pr: false,
11222            quota_hit: false,
11223            parked: false,
11224            no_viable_candidates: true,
11225        };
11226        let mut t = task();
11227        t.start(state.id.clone());
11228        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11229
11230        assert_eq!(t.status, TaskStatus::Held);
11231        let reason = t.hold_reason.expect("a held task must record why");
11232        assert!(
11233            reason.starts_with("run ended agent-verified no-op"),
11234            "the original settle reason must survive unchanged: {reason}"
11235        );
11236        assert!(
11237            reason.contains(q.short()),
11238            "the open question's id must be named so the notice is actionable: {reason}"
11239        );
11240    }
11241
11242    #[test]
11243    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
11244        crate::run::pin_test_home();
11245        let state = verified_noop_run_state();
11246
11247        let verdict = Verdict {
11248            status: RunStatus::VerifiedNoop,
11249            left_pr: false,
11250            quota_hit: false,
11251            parked: false,
11252            no_viable_candidates: true,
11253        };
11254        let mut t = task();
11255        t.start(state.id.clone());
11256        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11257
11258        assert_eq!(t.status, TaskStatus::Held);
11259        assert_eq!(
11260            t.hold_reason.as_deref(),
11261            Some("run ended agent-verified no-op"),
11262            "nothing to append when the question was already answered or never asked"
11263        );
11264    }
11265
11266    #[test]
11267    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
11268        crate::run::pin_test_home();
11269
11270        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
11271        // regression prose instead of valid structured evidence.
11272        let mut bad = run_state(RunStatus::VerifiedNoop);
11273        let mut c = candidate(
11274            'A',
11275            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
11276            true,
11277            None,
11278        );
11279        c.verified_noop = Some("Not established.".to_owned());
11280        bad.candidates = vec![c];
11281
11282        let mut t = task();
11283        t.start(bad.id.clone());
11284        let verdict = Verdict {
11285            status: RunStatus::VerifiedNoop,
11286            left_pr: false,
11287            quota_hit: true,
11288            parked: false,
11289            no_viable_candidates: true,
11290        };
11291        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
11292        assert_eq!(
11293            t.status,
11294            TaskStatus::Failed,
11295            "inconsistent verified_noop must retry as Failed when attempts remain"
11296        );
11297        assert_eq!(t.attempts, 1);
11298        assert_eq!(
11299            t.last_error.as_deref(),
11300            Some("no-change result lacks verified evidence")
11301        );
11302        assert!(t.hold_reason.is_none());
11303
11304        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
11305        // attempts exhausted holds as `failed`, never `verified_noop`, and
11306        // never auto-closes to `Done`.
11307        let mut t_exhausted = task();
11308        t_exhausted.start(bad.id.clone());
11309        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
11310        assert_eq!(t_exhausted.status, TaskStatus::Held);
11311        assert_eq!(t_exhausted.attempts, 1);
11312        assert_eq!(
11313            t_exhausted
11314                .hold_notice_cause
11315                .as_ref()
11316                .map(|c| c.stage.as_str()),
11317            Some("failed"),
11318            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
11319        );
11320        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
11321        assert!(
11322            !diag.contains("agent-verified no-op"),
11323            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
11324        );
11325        assert!(diag.contains("Not established"), "{diag}");
11326    }
11327
11328    #[test]
11329    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
11330        let mut state = verified_noop_run_state();
11331        let summary = state.candidates[0].summary.clone();
11332        state.candidates[0].summary = "Already satisfied.".to_owned();
11333        assert!(state.all_candidates_verified_noop());
11334
11335        state.candidates[0].summary = summary;
11336        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
11337        assert!(!state.all_candidates_verified_noop());
11338    }
11339
11340    #[test]
11341    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
11342        crate::run::pin_test_home();
11343        let mut first = run_state(RunStatus::Blocked);
11344        first.id = "20260101-000000-sup1".to_owned();
11345        first.save().unwrap();
11346        let mut second = run_state(RunStatus::Merged);
11347        second.id = "20260101-000000-sup2".to_owned();
11348        second.save().unwrap();
11349
11350        let mut t = task();
11351        t.runs = vec![first.id.clone(), second.id.clone()];
11352        t.status = TaskStatus::Done;
11353
11354        supersede_prior_runs(&t, &crate::run::home());
11355
11356        assert_eq!(
11357            RunState::load(&first.id).unwrap().status,
11358            RunStatus::Superseded,
11359            "the first attempt's Blocked no longer needs anyone's attention"
11360        );
11361        assert_eq!(
11362            RunState::load(&second.id).unwrap().status,
11363            RunStatus::Merged,
11364            "the run that actually succeeded is left exactly as it was"
11365        );
11366    }
11367
11368    #[test]
11369    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
11370        // `is_working_on` alone only proves a *daemon* claim; a `magi run
11371        // --resume` invoked by hand outside the daemon never touches
11372        // `daemon.json` at all, so it would look identical to a genuinely
11373        // idle run without also consulting `RunState::liveness`, which reads
11374        // this run's own recorded `driver_pid` instead.
11375        crate::run::pin_test_home();
11376        let mut first = run_state(RunStatus::Blocked);
11377        first.id = "20260101-000000-sup9".to_owned();
11378        // This test process's own pid: guaranteed alive without needing a
11379        // real second process or daemon.
11380        first.driver_pid = Some(std::process::id());
11381        first.driver_started_at = Some(
11382            crate::proc::process_started_at(std::process::id())
11383                .expect("this test process's own start time must be queryable"),
11384        );
11385        first.save().unwrap();
11386        let mut second = run_state(RunStatus::Merged);
11387        second.id = "20260101-000000-supa".to_owned();
11388        second.save().unwrap();
11389
11390        let mut t = task();
11391        t.runs = vec![first.id.clone(), second.id.clone()];
11392        t.status = TaskStatus::Done;
11393
11394        supersede_prior_runs(&t, &crate::run::home());
11395
11396        assert_eq!(
11397            RunState::load(&first.id).unwrap().status,
11398            RunStatus::Blocked,
11399            "a live driver_pid means something is still actually working this run, \
11400             even though no daemon claims it - rewriting under it would just be \
11401             undone the next time that process saves"
11402        );
11403    }
11404
11405    #[test]
11406    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
11407        // The first resweep must skip a still-live attempt exactly like
11408        // `supersede_prior_runs` itself does; a later resweep, once that
11409        // process is no longer actually driving it, is what closes the gap
11410        // `supersede_prior_runs` alone leaves - a task only ever reaches
11411        // `Done` once, so nothing else would ever look at this run again.
11412        let dir = tempfile::tempdir().unwrap();
11413        let home = dir.path().to_path_buf();
11414        let queue = Queue::at(dir.path().join("queue"));
11415
11416        let mut first = run_state(RunStatus::Blocked);
11417        first.id = "20260101-000000-supd".to_owned();
11418        first.driver_pid = Some(std::process::id());
11419        first.driver_started_at = Some(
11420            crate::proc::process_started_at(std::process::id())
11421                .expect("this test process's own start time must be queryable"),
11422        );
11423        first.save_under(&home).unwrap();
11424        let mut second = run_state(RunStatus::Merged);
11425        second.id = "20260101-000000-supe".to_owned();
11426        second.save_under(&home).unwrap();
11427
11428        let mut t = task();
11429        t.runs = vec![first.id.clone(), second.id.clone()];
11430        t.status = TaskStatus::Done;
11431        queue.put(&mut t).unwrap();
11432
11433        resweep_superseded_attempts(&queue, &home);
11434        assert_eq!(
11435            RunState::load_under(&first.id, &home).unwrap().status,
11436            RunStatus::Blocked,
11437            "still live on the first pass, so still untouched"
11438        );
11439
11440        // Stand in for the manual process no longer being the one driving
11441        // this run: same pid (this test process really is still alive), but
11442        // an identity marker that no longer matches it - see
11443        // `RunState::liveness`'s own doc for why a mismatched
11444        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
11445        let mut stale = RunState::load_under(&first.id, &home).unwrap();
11446        stale.driver_started_at = Some("1".to_owned());
11447        stale.save_under(&home).unwrap();
11448
11449        resweep_superseded_attempts(&queue, &home);
11450        assert_eq!(
11451            RunState::load_under(&first.id, &home).unwrap().status,
11452            RunStatus::Superseded,
11453            "the second pass catches up what the first one correctly skipped"
11454        );
11455    }
11456
11457    #[test]
11458    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
11459        crate::run::pin_test_home();
11460        let mut first = run_state(RunStatus::Blocked);
11461        first.id = "20260101-000000-sup3".to_owned();
11462        first.save().unwrap();
11463        let mut second = run_state(RunStatus::Blocked);
11464        second.id = "20260101-000000-sup4".to_owned();
11465        second.save().unwrap();
11466
11467        let mut t = task();
11468        t.runs = vec![first.id.clone(), second.id.clone()];
11469        // Still retrying: nothing about this task's story is settled yet, so
11470        // neither Blocked run may be relabelled, even though a later attempt
11471        // already exists.
11472        t.status = TaskStatus::Failed;
11473
11474        supersede_prior_runs(&t, &crate::run::home());
11475
11476        assert_eq!(
11477            RunState::load(&first.id).unwrap().status,
11478            RunStatus::Blocked
11479        );
11480        assert_eq!(
11481            RunState::load(&second.id).unwrap().status,
11482            RunStatus::Blocked
11483        );
11484    }
11485
11486    #[test]
11487    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
11488        // `magi task done` (or the API's equivalent) can close a task with no
11489        // run of its own ever having succeeded - there is nothing here that
11490        // counts as "the attempt that finished it", so nothing is rewritten.
11491        crate::run::pin_test_home();
11492        let mut first = run_state(RunStatus::Blocked);
11493        first.id = "20260101-000000-sup5".to_owned();
11494        first.save().unwrap();
11495
11496        let mut t = task();
11497        t.runs = vec![first.id.clone()];
11498        t.status = TaskStatus::Done;
11499
11500        supersede_prior_runs(&t, &crate::run::home());
11501
11502        assert_eq!(
11503            RunState::load(&first.id).unwrap().status,
11504            RunStatus::Blocked,
11505            "a single-attempt task has no earlier run to supersede"
11506        );
11507    }
11508
11509    #[test]
11510    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
11511        for status in [
11512            RunStatus::Blocked,
11513            RunStatus::Stalled,
11514            RunStatus::Failed,
11515            RunStatus::Ready,
11516            RunStatus::Merged,
11517        ] {
11518            let dir = tempfile::tempdir().unwrap();
11519            let home = dir.path();
11520            let mut first = run_state(RunStatus::Blocked);
11521            first.id = "20260101-000000-supb".to_owned();
11522            first.save_under(home).unwrap();
11523            let mut second = run_state(status);
11524            second.id = "20260101-000000-supc".to_owned();
11525            second.save_under(home).unwrap();
11526
11527            let mut t = task();
11528            t.runs = vec![first.id.clone(), second.id.clone()];
11529            t.hold_manual(Some("Unmerged work remains".into()));
11530            let mut context = CompletionContext::new(
11531                CompletionActor::Cli,
11532                Some("Discard the unmerged attempts".into()),
11533                home,
11534                &t,
11535            );
11536            context.discard = true;
11537            t.succeed(context);
11538            assert_eq!(t.completion_history.len(), 1);
11539
11540            supersede_prior_runs(&t, home);
11541
11542            assert_eq!(
11543                RunState::load_under(&first.id, home).unwrap().status,
11544                RunStatus::Blocked,
11545                "an audited manual close is not proof the earlier work landed"
11546            );
11547            assert_eq!(
11548                RunState::load_under(&second.id, home).unwrap().status,
11549                status,
11550                "the latest attempt retains its actual outcome"
11551            );
11552        }
11553    }
11554
11555    #[test]
11556    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
11557        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
11558        // to look" - `Failed` and `VerifiedNoop` are already their own
11559        // terminal answers and must not be relabelled into a third one.
11560        crate::run::pin_test_home();
11561        let mut failed = run_state(RunStatus::Failed);
11562        failed.id = "20260101-000000-sup6".to_owned();
11563        failed.save().unwrap();
11564        let mut noop = run_state(RunStatus::VerifiedNoop);
11565        noop.id = "20260101-000000-sup7".to_owned();
11566        noop.save().unwrap();
11567        let mut winner = run_state(RunStatus::Ready);
11568        winner.id = "20260101-000000-sup8".to_owned();
11569        winner.save().unwrap();
11570
11571        let mut t = task();
11572        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
11573        t.status = TaskStatus::Done;
11574
11575        supersede_prior_runs(&t, &crate::run::home());
11576
11577        assert_eq!(
11578            RunState::load(&failed.id).unwrap().status,
11579            RunStatus::Failed
11580        );
11581        assert_eq!(
11582            RunState::load(&noop.id).unwrap().status,
11583            RunStatus::VerifiedNoop
11584        );
11585    }
11586
11587    fn approval_question(run: &str) -> ask::Question {
11588        ask::Question::new(
11589            run.to_owned(),
11590            land::APPROVAL_NODE.to_owned(),
11591            "land".to_owned(),
11592            "merge?".to_owned(),
11593            String::new(),
11594            vec!["merge".to_owned(), "hold".to_owned()],
11595        )
11596    }
11597
11598    #[test]
11599    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
11600        crate::run::pin_test_home();
11601        let mut state = run_state(RunStatus::Landing);
11602        state.id = "20260101-000000-fre1".to_owned();
11603        state.parked = true;
11604        state.save().unwrap();
11605        ask::Questions::open()
11606            .put(&mut approval_question(&state.id))
11607            .unwrap();
11608
11609        let mut t = task();
11610        t.runs.push(state.id.clone());
11611        assert_eq!(
11612            land_resume_state(&t),
11613            LandResume::StillWaiting,
11614            "nobody has answered and the timeout has not passed"
11615        );
11616    }
11617
11618    #[test]
11619    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
11620        crate::run::pin_test_home();
11621        let mut state = run_state(RunStatus::Gating);
11622        state.id = "20260101-000000-gt01".to_owned();
11623        state.parked = true;
11624        state.config.graph.answer_timeout = 60;
11625        state.github_text = Some(crate::run::GithubTextAsk {
11626            rewrite: None,
11627            fingerprint: "f".into(),
11628            title: true,
11629            body: false,
11630            categories: vec!["title-language".into()],
11631            question: None,
11632            asks: 1,
11633            resolved: false,
11634            chosen_title: None,
11635            choice: None,
11636            publication: None,
11637        });
11638        state.save().unwrap();
11639        let store = ask::Questions::open();
11640        let mut q = ask::Question::new(
11641            state.id.clone(),
11642            crate::github_text::ASK_NODE.to_owned(),
11643            crate::github_text::ASK_SEAT.to_owned(),
11644            "s".into(),
11645            String::new(),
11646            vec!["use fallback".into()],
11647        );
11648        store.put(&mut q).unwrap();
11649        let mut t = task();
11650        t.runs.push(state.id.clone());
11651        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
11652        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11653        store.put(&mut q).unwrap();
11654        assert_eq!(land_resume_state(&t), LandResume::Ready);
11655        assert!(!store.get(&q.id).unwrap().status.open());
11656        // Once decided, a parked run is an ordinary candidate again.
11657        state.github_text.as_mut().unwrap().resolved = true;
11658        state.save().unwrap();
11659        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
11660    }
11661
11662    #[test]
11663    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
11664        // `ask::ask_and_wait`'s own deadline used to retire a question
11665        // nobody answered; land's approval bypasses that wait (see
11666        // `land::approval_gate`), so this is now the only place
11667        // `graph.answer_timeout` is enforced for a land approval at all.
11668        crate::run::pin_test_home();
11669        let mut state = run_state(RunStatus::Landing);
11670        state.id = "20260101-000000-exp1".to_owned();
11671        state.parked = true;
11672        state.config.graph.answer_timeout = 60;
11673        state.save().unwrap();
11674
11675        let store = ask::Questions::open();
11676        let mut q = approval_question(&state.id);
11677        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11678        store.put(&mut q).unwrap();
11679
11680        let mut t = task();
11681        t.runs.push(state.id.clone());
11682        assert_eq!(
11683            land_resume_state(&t),
11684            LandResume::Ready,
11685            "an expired question must not be waited on forever"
11686        );
11687
11688        let after = store.get(&q.id).unwrap();
11689        assert!(
11690            !after.status.open(),
11691            "the question is abandoned, not silently ignored"
11692        );
11693        assert!(
11694            after.resolution().is_none(),
11695            "an abandoned question is not read as a decision"
11696        );
11697    }
11698
11699    #[test]
11700    fn reclaim_settles_a_running_task_against_its_last_run() {
11701        let mut t = task();
11702        t.start("20260904-000000-4043".to_owned());
11703        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
11704        assert_eq!(
11705            t.status,
11706            TaskStatus::Done,
11707            "a run that actually finished must not stay `running` forever"
11708        );
11709    }
11710
11711    #[test]
11712    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
11713        let dir = tempfile::tempdir().unwrap();
11714        let queue = Queue::at(dir.path().join("queue"));
11715        let mut task = task();
11716        let mut run = run_state(RunStatus::Blocked);
11717        run.reserve_under(dir.path()).unwrap();
11718        run.driver_exited = true;
11719        run.save_under(dir.path()).unwrap();
11720        queue.put(&mut task).unwrap();
11721        let stale = task.clone();
11722        task.resume_override = Some(crate::queue::OperatorResume {
11723            question_id: "pending-resume".into(),
11724            at: Timestamp::now(),
11725            conductor_rehold: None,
11726            forced: true,
11727            pinned_run: Some(run.id.clone()),
11728        });
11729        task.start(run.id.clone());
11730        queue.put(&mut task).unwrap();
11731        // Discard every in-memory handoff, as a worker death before execute does.
11732        let mut recovered = queue.get(&task.id).unwrap();
11733        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
11734        reclaim(&mut recovered, Some(disk), 2, "en");
11735        queue.put(&mut recovered).unwrap();
11736        assert!(recovered.resume_override.is_none());
11737        assert_eq!(
11738            recovered.dispatched_resumes.get("pending-resume"),
11739            Some(&run.id)
11740        );
11741        let mut stale = stale;
11742        queue.put(&mut stale).unwrap();
11743        assert_eq!(
11744            stale.dispatched_resumes, recovered.dispatched_resumes,
11745            "a stale task writer cannot erase dispatch ownership"
11746        );
11747        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
11748        assert!(resumed.decision_starts.is_empty());
11749        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
11750        assert!(
11751            resumed.decision_starts.is_empty(),
11752            "handoff is not execution proof"
11753        );
11754        resumed.begin_pass();
11755        resumed.save_under(dir.path()).unwrap();
11756        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
11757        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
11758        disk.carry_dispatched_resumes(&recovered);
11759        disk.begin_pass();
11760        assert_eq!(
11761            disk.decision_starts.get("pending-resume"),
11762            Some(&0),
11763            "later execution must preserve the original pass receipt"
11764        );
11765    }
11766
11767    #[test]
11768    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
11769        let mut t = task();
11770        t.start("20260904-000000-4043".to_owned());
11771        t.last_error = Some("earlier trouble".to_owned());
11772        let mut state = run_state(RunStatus::Judging);
11773        state.parked = true;
11774        reclaim(&mut t, Some(state), 1, "en");
11775        assert_eq!(t.status, TaskStatus::Parked);
11776        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
11777        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11778        assert!(t.park_reason.is_some());
11779        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
11780        assert!(!t.fresh_start);
11781        assert!(t.status.runnable());
11782    }
11783
11784    #[test]
11785    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
11786        let mut t = task();
11787        t.start("20260904-000000-4043".to_owned());
11788        t.last_error = Some("earlier trouble".to_owned());
11789        settle(
11790            &mut t,
11791            Verdict {
11792                status: RunStatus::Judging,
11793                left_pr: false,
11794                quota_hit: false,
11795                parked: true,
11796                no_viable_candidates: false,
11797            },
11798            "parked after `judging`",
11799            1,
11800        );
11801        assert_eq!(t.status, TaskStatus::Parked);
11802        assert_eq!(t.attempts, 0);
11803        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11804        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
11805        assert_eq!(t.schema, crate::queue::SCHEMA);
11806        assert!(
11807            crate::notices::task_held(&t).is_none(),
11808            "a park is not news"
11809        );
11810        t.start("20260904-000000-4043".to_owned());
11811        assert_eq!(t.park_reason, None);
11812    }
11813
11814    #[test]
11815    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
11816        // A blocked run with attempts left goes back to `Failed`, exactly as
11817        // it would from `attempt` itself - `reclaim` must not invent a second
11818        // policy for a task a daemon merely stopped without reporting.
11819        let mut t = task();
11820        t.start("20260904-000000-4043".to_owned());
11821        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
11822        assert_eq!(t.status, TaskStatus::Failed);
11823        assert!(t.status.runnable());
11824    }
11825
11826    #[test]
11827    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
11828        let mut t = task();
11829        t.start("20260904-000000-4043".to_owned());
11830        assert_eq!(t.attempts, 1);
11831        let mut run = run_state(RunStatus::Implementing);
11832        run.id = "20260904-000000-4043".to_owned();
11833        run.begin_pass();
11834        let cause = crate::run::ParkCause::Upgrade {
11835            from: "0.121.0".to_owned(),
11836            to: Some("0.121.1".to_owned()),
11837        };
11838        run.end_pass_parked(cause.clone());
11839        run.parked = true;
11840        let verdict = Verdict {
11841            status: run.status,
11842            left_pr: false,
11843            quota_hit: false,
11844            parked: true,
11845            no_viable_candidates: false,
11846        };
11847        // A crash after the checkpoint but before queue settlement must
11848        // recover exactly the same scheduling evidence and refund.
11849        let mut orphan = t.clone();
11850        reclaim(&mut orphan, Some(run.clone()), 2, "en");
11851        assert_eq!(orphan.status, TaskStatus::Parked);
11852        assert_eq!(orphan.attempts, 0);
11853        assert_eq!(
11854            orphan.upgrade_resume_key(),
11855            Some((run.passes[0].started_at, orphan.id.as_str()))
11856        );
11857        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
11858        assert_eq!(t.attempts, 0);
11859        assert_eq!(t.passes.len(), 1);
11860        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11861        assert_eq!(t.passes[0].parked, Some(cause));
11862        assert_eq!(t.passes[0].pass_index, 0);
11863        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
11864        assert!(t.upgrade_resume_key().is_some());
11865
11866        // A resumed pass that then fails spends its attempt, and the earlier
11867        // pass's entry is untouched.
11868        t.start("20260904-000000-4043".to_owned());
11869        run.begin_pass();
11870        run.status = RunStatus::Failed;
11871        let verdict = Verdict {
11872            status: RunStatus::Failed,
11873            left_pr: false,
11874            quota_hit: false,
11875            parked: false,
11876            no_viable_candidates: false,
11877        };
11878        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
11879        assert_eq!(t.passes.len(), 2);
11880        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
11881        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
11882        assert_eq!(t.passes[1].pass_index, 1);
11883        assert_eq!(t.attempts, 1);
11884    }
11885
11886    #[test]
11887    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
11888        let mut t = task();
11889        t.start("20260904-000000-4043".to_owned());
11890        reclaim(&mut t, None, 2, "en");
11891        assert_eq!(t.status, TaskStatus::Held);
11892        assert!(
11893            t.last_error
11894                .as_deref()
11895                .is_some_and(|e| e.contains("running")),
11896            "the operator needs to know why this task was held"
11897        );
11898    }
11899
11900    #[test]
11901    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
11902        let dir = tempfile::tempdir().unwrap();
11903        let queue = Queue::at(dir.path().to_path_buf());
11904        let mut task = task();
11905        let run = "20261124-000000-dead";
11906        task.link_run(run);
11907        task.attempts = 2;
11908        task.status = TaskStatus::Running;
11909        task.sync_only = Some(crate::base_sync_only::Request {
11910            run: run.into(),
11911            at: Timestamp::now(),
11912        });
11913        queue.put(&mut task).unwrap();
11914        assert_eq!(
11915            reclaim_orphaned_running(&queue, 3, &Default::default()),
11916            vec![task.id.clone()]
11917        );
11918        let saved = queue.get(&task.id).unwrap();
11919        assert_eq!(saved.status, TaskStatus::Held);
11920        assert_eq!(saved.attempts, 2);
11921        assert_eq!(saved.execution_runs(), [run]);
11922        assert!(
11923            saved
11924                .last_error
11925                .unwrap()
11926                .contains("verification was not allowed")
11927        );
11928        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
11929    }
11930
11931    #[test]
11932    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
11933        use crate::base_sync_only::{Outcome, Pass, Request};
11934
11935        let mut state = run_state(RunStatus::Blocked);
11936        let mut task = task();
11937        let request = Request {
11938            run: state.id.clone(),
11939            at: Timestamp::now(),
11940        };
11941        task.start(state.id.clone());
11942        task.sync_only = Some(request.clone());
11943        // Dedicated dispatch saves Running with the pre-pass attempt count.
11944        task.attempts = 2;
11945        let mut pass = Pass::new(request, &state);
11946        pass.result = Outcome::AlreadyCurrent;
11947        state.sync_only_passes.push(pass);
11948        state.begin_pass();
11949
11950        reclaim(&mut task, Some(state), 3, "en");
11951
11952        assert_eq!(task.status, TaskStatus::Held);
11953        assert_eq!(task.attempts, 2);
11954        assert!(task.sync_only.is_none());
11955        let detail = task.hold_reason.unwrap();
11956        assert!(detail.contains("HEAD already contains the base"));
11957        assert!(detail.contains("verification was not allowed"));
11958    }
11959
11960    #[test]
11961    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
11962        let dir = tempfile::tempdir().unwrap();
11963        let queue = Queue::at(dir.path().to_path_buf());
11964
11965        // No run recorded, so this never has to touch `RunState::load`.
11966        let mut orphaned = task();
11967        orphaned.id = "20260904-000000-orph".to_owned();
11968        orphaned.status = TaskStatus::Running;
11969        orphaned.attempts = 1;
11970        queue.put(&mut orphaned).unwrap();
11971
11972        let mut alive = task();
11973        alive.id = "20260904-000000-live".to_owned();
11974        alive.status = TaskStatus::Running;
11975        alive.attempts = 1;
11976        queue.put(&mut alive).unwrap();
11977        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
11978
11979        let mut queued = task();
11980        queued.id = "20260904-000000-wait".to_owned();
11981        queue.put(&mut queued).unwrap();
11982
11983        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
11984        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
11985
11986        assert_eq!(
11987            queue.get(&orphaned.id).unwrap().status,
11988            TaskStatus::Held,
11989            "nothing was driving it and there was no run to recover"
11990        );
11991        assert_eq!(
11992            queue.get(&alive.id).unwrap().status,
11993            TaskStatus::Running,
11994            "a live claim must protect the task it belongs to"
11995        );
11996        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
11997    }
11998
11999    /// Read a run.json back from an explicit `home`, the same way
12000    /// `reclaim_abandoned_runs` itself does - never through the
12001    /// process-global `RunState::load`, which this test's own `home` (an
12002    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
12003    /// use at all.
12004    fn read_run_under(home: &Path, id: &str) -> RunState {
12005        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
12006        serde_json::from_str(&body).unwrap()
12007    }
12008
12009    #[test]
12010    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
12011        let dir = tempfile::tempdir().unwrap();
12012        let home = dir.path().to_path_buf();
12013        let now = Timestamp::now();
12014        let overrun_seat = || crate::run::ActiveSeat {
12015            node: "implement".to_owned(),
12016            started_at: now - jiff::SignedDuration::new(21_000, 0),
12017            timeout_secs: 3_600,
12018            attempt: 0,
12019            task: None,
12020            command: None,
12021            index: None,
12022            total: None,
12023        };
12024
12025        let mut dead = run_state(RunStatus::Implementing);
12026        dead.id = "20260101-000000-dead".to_owned();
12027        dead.active.insert("impl-A".to_owned(), overrun_seat());
12028        // A `driver_pid` the injected query below confirms gone outright —
12029        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
12030        dead.driver_pid = Some(4242);
12031        dead.save_under(&home).unwrap();
12032
12033        // Same shape, but a live daemon's heartbeat names it: must be left
12034        // exactly alone, however far past its own timeout the seat sits.
12035        let mut alive = run_state(RunStatus::Implementing);
12036        alive.id = "20260101-000000-aliv".to_owned();
12037        alive.active.insert("impl-A".to_owned(), overrun_seat());
12038        alive.save_under(&home).unwrap();
12039        let mut status = Status::new();
12040        status.current = vec![Current {
12041            worker: None,
12042            task: "20260101-000000-task".to_owned(),
12043            run: alive.id.clone(),
12044        }];
12045        write_status_to(&home.join("daemon.json"), &status).unwrap();
12046
12047        // The abandoned seat left an open question behind: nobody is left to
12048        // read an answer once the run is failed, and this must not wait for
12049        // some later daemon startup's own sweep to notice that.
12050        let questions = Questions::at(home.join("questions"));
12051        let mut q = ask::Question::new(
12052            dead.id.clone(),
12053            "implement".to_owned(),
12054            "impl-A".to_owned(),
12055            "Which storage backend?".to_owned(),
12056            String::new(),
12057            vec!["SQLite".to_owned(), "Redis".to_owned()],
12058        );
12059        questions.put(&mut q).unwrap();
12060
12061        let abandoned = reclaim_abandoned_runs_with(
12062            &home,
12063            now,
12064            |pid| if pid == 4242 { Some(false) } else { None },
12065            |_| panic!("a query answering Dead outright needs no identity corroboration"),
12066        );
12067        assert_eq!(abandoned, vec![dead.id.clone()]);
12068
12069        let reloaded = read_run_under(&home, &dead.id);
12070        assert_eq!(reloaded.status, RunStatus::Failed);
12071        assert!(reloaded.active.is_empty());
12072        assert!(
12073            !questions.get(&q.id).unwrap().status.open(),
12074            "the failed run's own open question must be settled in the same pass"
12075        );
12076
12077        let still_alive = read_run_under(&home, &alive.id);
12078        assert_eq!(
12079            still_alive.status,
12080            RunStatus::Implementing,
12081            "a live daemon's claim protects it"
12082        );
12083        assert!(!still_alive.active.is_empty());
12084    }
12085
12086    /// The exact shape a review round flagged as broken: `magi serve` running
12087    /// in this same `home` scans *every* run on disk, including a manual
12088    /// `magi review` / `magi run` this daemon never started and that
12089    /// therefore claims no heartbeat of its own. Before this scan asked
12090    /// `liveness` rather than just `is_working_on`, a manual run whose active
12091    /// seat merely ran a little past its own timeout — the CLI finishing up,
12092    /// its result still being collected — got wiped and failed by a daemon
12093    /// that had nothing to do with it, out from under a process that was
12094    /// still very much running.
12095    #[test]
12096    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
12097        let dir = tempfile::tempdir().unwrap();
12098        let home = dir.path().to_path_buf();
12099        let now = Timestamp::now();
12100
12101        let mut manual = run_state(RunStatus::Reviewing);
12102        manual.id = "20260101-000000-manl".to_owned();
12103        manual.active.insert(
12104            "review-1".to_owned(),
12105            crate::run::ActiveSeat {
12106                node: "review".to_owned(),
12107                started_at: now - jiff::SignedDuration::new(21_000, 0),
12108                timeout_secs: 3_600,
12109                attempt: 0,
12110                task: None,
12111                command: None,
12112                index: None,
12113                total: None,
12114            },
12115        );
12116        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
12117        // but a real, still-running process: `liveness` must corroborate this
12118        // as `Live`, not read the missing daemon claim as death.
12119        manual.driver_pid = Some(4242);
12120        manual.driver_started_at = Some("1790000000".to_owned());
12121        manual.save_under(&home).unwrap();
12122
12123        let abandoned = reclaim_abandoned_runs_with(
12124            &home,
12125            now,
12126            |pid| if pid == 4242 { Some(true) } else { None },
12127            |pid| {
12128                if pid == 4242 {
12129                    Some("1790000000".to_owned())
12130                } else {
12131                    None
12132                }
12133            },
12134        );
12135        assert!(
12136            abandoned.is_empty(),
12137            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
12138        );
12139
12140        let reloaded = read_run_under(&home, &manual.id);
12141        assert_eq!(reloaded.status, RunStatus::Reviewing);
12142        assert!(!reloaded.active.is_empty());
12143    }
12144
12145    #[test]
12146    fn an_already_claimed_task_is_skipped_rather_than_failed() {
12147        let dir = tempfile::tempdir().unwrap();
12148        let queue = Queue::at(dir.path().to_path_buf());
12149        let mut only = task();
12150        queue.put(&mut only).unwrap();
12151
12152        let _elsewhere = queue.claim(&only.id).unwrap();
12153        let candidates = runnable(&queue);
12154        assert_eq!(candidates.len(), 1, "the task is still runnable");
12155        assert!(
12156            queue.claim(&candidates[0].id).is_err(),
12157            "the loop cannot take a claim somebody else holds"
12158        );
12159
12160        let after = queue.get(&only.id).unwrap();
12161        assert_eq!(after.status, TaskStatus::Queued);
12162        assert_eq!(
12163            after.attempts, 0,
12164            "losing the race is not an attempt at the task"
12165        );
12166        assert_eq!(after.last_error, None);
12167    }
12168
12169    #[test]
12170    fn the_status_file_round_trips_and_its_heartbeat_advances() {
12171        let dir = tempfile::tempdir().unwrap();
12172        let path = dir.path().join("daemon.json");
12173
12174        let mut status = Status::new();
12175        status.idle = false;
12176        status.completed = 7;
12177        status.current = vec![Current {
12178            worker: None,
12179            task: "20260902-000000-t111".to_owned(),
12180            run: "20260902-000001-r111".to_owned(),
12181        }];
12182        write_status_to(&path, &status).unwrap();
12183        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12184        assert_eq!(first.schema, SCHEMA);
12185        assert_eq!(first.pid, std::process::id());
12186        assert!(!first.idle);
12187        assert_eq!(first.completed, 7);
12188        assert_eq!(first.current, status.current);
12189        assert!(
12190            !path.with_extension("json.tmp").exists(),
12191            "the temp file is renamed, not left behind"
12192        );
12193
12194        std::thread::sleep(Duration::from_millis(5));
12195        status.updated_at = Timestamp::now();
12196        status.polls = 3;
12197        write_status_to(&path, &status).unwrap();
12198        let second: Status =
12199            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12200        assert!(
12201            second.updated_at > first.updated_at,
12202            "a reader can only detect staleness if the heartbeat moves"
12203        );
12204        assert_eq!(
12205            second.started_at, first.started_at,
12206            "the start time is not a heartbeat"
12207        );
12208        assert_eq!(second.polls, 3);
12209    }
12210
12211    #[test]
12212    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
12213        let dir = tempfile::tempdir().unwrap();
12214
12215        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
12216
12217        let mut status = Status::new();
12218        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
12219        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12220        let stale = read_status(dir.path()).unwrap();
12221        assert!(
12222            !stale.running(Timestamp::now()),
12223            "a minute without a heartbeat is a dead daemon, not a busy one"
12224        );
12225        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
12226
12227        status.updated_at = Timestamp::now();
12228        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12229        let fresh = read_status(dir.path()).unwrap();
12230        assert!(fresh.running(Timestamp::now()));
12231    }
12232
12233    #[test]
12234    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
12235        let dir = tempfile::tempdir().unwrap();
12236        let now = Timestamp::now();
12237        let mine = "20260903-080619-01c2";
12238
12239        assert!(
12240            !is_working_on(dir.path(), mine, now),
12241            "no status file means nobody is working on anything"
12242        );
12243
12244        let mut status = Status::new();
12245        status.current = vec![Current {
12246            worker: None,
12247            task: "20260903-080340-0167".to_owned(),
12248            run: mine.to_owned(),
12249        }];
12250        status.updated_at = now;
12251        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12252        assert!(is_working_on(dir.path(), mine, now));
12253        assert!(
12254            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
12255            "a daemon busy with one run is not working on another"
12256        );
12257
12258        // A killed daemon stops writing heartbeats but leaves the file behind
12259        // naming the run it died in. That run must not be undeletable forever.
12260        status.updated_at = now - jiff::SignedDuration::from_secs(600);
12261        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12262        assert!(
12263            !is_working_on(dir.path(), mine, now),
12264            "a stale heartbeat is a dead daemon, so its run is a leftover"
12265        );
12266    }
12267
12268    #[test]
12269    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
12270        let dir = tempfile::tempdir().unwrap();
12271        let now = Timestamp::now();
12272
12273        assert!(
12274            !is_working_on_short(dir.path(), "01c2", now),
12275            "no status file means nobody is working on anything"
12276        );
12277
12278        let mut status = Status::new();
12279        status.current = vec![Current {
12280            worker: None,
12281            task: "20260903-080340-0167".to_owned(),
12282            run: "20260903-080619-01c2".to_owned(),
12283        }];
12284        status.updated_at = now;
12285        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12286        assert!(
12287            is_working_on_short(dir.path(), "01c2", now),
12288            "the run's short id is the last block of its full id"
12289        );
12290        assert!(
12291            !is_working_on_short(dir.path(), "3cbf", now),
12292            "a daemon busy with one worktree bay is not working on another"
12293        );
12294    }
12295
12296    #[test]
12297    fn a_newer_status_file_still_yields_a_reading() {
12298        let dir = tempfile::tempdir().unwrap();
12299        // A field this build has never heard of must not turn the reading into
12300        // nothing at all; that is the whole reason the reader is permissive.
12301        std::fs::write(
12302            dir.path().join("daemon.json"),
12303            serde_json::json!({
12304                "schema": 2,
12305                "updated_at": Timestamp::now().to_string(),
12306                "idle": true,
12307                "surprise": { "nested": [1, 2, 3] },
12308            })
12309            .to_string(),
12310        )
12311        .unwrap();
12312
12313        let reading = read_status(dir.path()).expect("a forward-compatible read");
12314        assert!(reading.running(Timestamp::now()));
12315        assert!(reading.idle);
12316        assert!(reading.current.is_empty());
12317    }
12318
12319    #[test]
12320    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
12321        // A daemon started before `current` became a list keeps writing this
12322        // shape on every heartbeat until it is restarted. A rolling upgrade
12323        // - a newer `magi web` or `magi doctor` reading an older `magi
12324        // serve`'s heartbeat - must still see the run it is on, not "no
12325        // daemon" from a type mismatch failing the whole struct.
12326        let dir = tempfile::tempdir().unwrap();
12327        std::fs::write(
12328            dir.path().join("daemon.json"),
12329            serde_json::json!({
12330                "schema": 1,
12331                "pid": 4242,
12332                "updated_at": Timestamp::now().to_string(),
12333                "idle": false,
12334                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
12335                "completed": 3,
12336                "polls": 9,
12337            })
12338            .to_string(),
12339        )
12340        .unwrap();
12341
12342        let reading = read_status(dir.path()).expect("an older shape must still parse");
12343        assert!(reading.running(Timestamp::now()));
12344        assert_eq!(
12345            reading.current,
12346            vec![Current {
12347                worker: None,
12348                task: "20260902-140501-aaaa".to_owned(),
12349                run: "20260902-140502-bbbb".to_owned(),
12350            }]
12351        );
12352    }
12353
12354    #[test]
12355    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
12356        let dir = tempfile::tempdir().unwrap();
12357        std::fs::write(
12358            dir.path().join("daemon.json"),
12359            serde_json::json!({
12360                "schema": 1,
12361                "updated_at": Timestamp::now().to_string(),
12362                "idle": true,
12363                "current": null,
12364            })
12365            .to_string(),
12366        )
12367        .unwrap();
12368        let with_null = read_status(dir.path()).expect("null must still parse");
12369        assert!(with_null.current.is_empty());
12370
12371        std::fs::write(
12372            dir.path().join("daemon.json"),
12373            serde_json::json!({
12374                "schema": 1,
12375                "updated_at": Timestamp::now().to_string(),
12376                "idle": true,
12377            })
12378            .to_string(),
12379        )
12380        .unwrap();
12381        let absent = read_status(dir.path()).expect("a missing field must still parse");
12382        assert!(absent.current.is_empty());
12383    }
12384
12385    #[test]
12386    fn a_task_without_a_repository_runs_in_the_daemons_default() {
12387        let fallback = Path::new("/default");
12388        let mut blank = task();
12389        blank.repo = PathBuf::new();
12390        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
12391        let mut dot = task();
12392        dot.repo = PathBuf::from(".");
12393        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
12394        assert_eq!(
12395            repo_for(&task(), fallback),
12396            PathBuf::from("/repo"),
12397            "a task that names a repository keeps it"
12398        );
12399    }
12400
12401    #[test]
12402    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
12403        let dir = tempfile::tempdir().unwrap();
12404        let repo = dir.path();
12405        let path = repo.join("explicit.toml");
12406        std::fs::write(
12407            &path,
12408            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
12409        )
12410        .unwrap();
12411        let opts = Opts {
12412            config: Some(path),
12413            ..Opts::default()
12414        };
12415        let queue = Queue::at(repo.join("queue"));
12416        let mut new = task();
12417        queue.put(&mut new).unwrap();
12418        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
12419        assert_eq!(
12420            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
12421            BuildCache::Isolated
12422        );
12423
12424        let mut old = task();
12425        old.schema = 22;
12426        queue.put(&mut old).unwrap();
12427        let mut old = queue.get(&old.id).unwrap();
12428        let config = resolved(&old);
12429        assert_eq!(config.verify.build_cache, BuildCache::Shared);
12430        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
12431        old.hold_manual(Some("wait".into()));
12432        queue.put(&mut old).unwrap();
12433
12434        let mut saved = queue.get(&old.id).unwrap();
12435        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
12436        saved
12437            .overrides
12438            .as_mut()
12439            .unwrap()
12440            .merge_over(&crate::queue::RunOverrides {
12441                build_cache: Some(BuildCache::Isolated),
12442                ..Default::default()
12443            });
12444        queue.put(&mut saved).unwrap();
12445        assert_eq!(
12446            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
12447            BuildCache::Isolated
12448        );
12449    }
12450
12451    #[test]
12452    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
12453        let dir = tempfile::tempdir().unwrap();
12454        let path = dir.path().join("explicit.toml");
12455        let write = |verify: &str| {
12456            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
12457        };
12458        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
12459        let opts = Opts {
12460            config: Some(path.clone()),
12461            ..Opts::default()
12462        };
12463        let mut task = task();
12464        task.set_urgent(true).unwrap();
12465        let resolved = |task: &Task| {
12466            prepare_for(dir.path(), &opts, task)
12467                .unwrap()
12468                .verify
12469                .build_cache
12470        };
12471        assert_eq!(resolved(&task), BuildCache::Isolated);
12472        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
12473        assert_eq!(resolved(&task), BuildCache::Shared);
12474        task.change_build_cache(None).unwrap();
12475        assert_eq!(resolved(&task), BuildCache::Isolated);
12476        task.set_urgent(false).unwrap();
12477        assert_eq!(resolved(&task), BuildCache::Shared);
12478
12479        // Urgent work must never be the one stopped by isolation: with no
12480        // shared cache to wait behind, or with a verification command isolated
12481        // mode cannot run, an urgent task keeps the configured mode.
12482        task.set_urgent(true).unwrap();
12483        write("e2e = [\"npm test\"]\n");
12484        assert_eq!(resolved(&task), BuildCache::Shared);
12485        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
12486        assert_eq!(resolved(&task), BuildCache::Shared);
12487        // An explicit choice stays strict and is applied as asked.
12488        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
12489        assert_eq!(resolved(&task), BuildCache::Isolated);
12490    }
12491
12492    #[test]
12493    fn task_implementers_edit_inherits_daemon_config_and_merge() {
12494        let dir = tempfile::tempdir().unwrap();
12495        let path = dir.path().join("explicit.toml");
12496        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
12497        let opts = Opts {
12498            config: Some(path),
12499            merge: Some("none".into()),
12500            ..Default::default()
12501        };
12502        let mut t = task();
12503        t.set_implementers(
12504            2,
12505            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12506                .unwrap(),
12507        )
12508        .unwrap();
12509        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12510        assert_eq!(cfg.graph.implementers, 2);
12511        assert_eq!(cfg.graph.judges, 1);
12512        assert_eq!(cfg.merge.mode, MergeMode::None);
12513        t.set_implementers(1, &cfg).unwrap();
12514        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12515        apply_task_implementers(&mut cfg, &t);
12516        assert_eq!(cfg.graph.implementers, 1);
12517        assert_eq!(cfg.graph.judges, 1);
12518        assert_eq!(cfg.merge.mode, MergeMode::None);
12519    }
12520
12521    #[test]
12522    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
12523        let dir = tempfile::tempdir().unwrap();
12524        let repo = dir.path().join("repo");
12525        std::fs::create_dir(&repo).unwrap();
12526        std::fs::write(
12527            repo.join("magi.toml"),
12528            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
12529        )
12530        .unwrap();
12531        let daemon_config = dir.path().join("daemon.toml");
12532        std::fs::write(
12533            &daemon_config,
12534            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
12535        )
12536        .unwrap();
12537        let opts = Opts {
12538            config: Some(daemon_config),
12539            merge: Some("pr".into()),
12540            ..Default::default()
12541        };
12542        let q = Queue::at(dir.path().join("queue"));
12543        let validation: Config =
12544            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12545                .unwrap();
12546        // No provenance field on legacy direct tasks: both shapes stay isolated.
12547        for record in ["{}", r#"{"candidates":2}"#] {
12548            let overrides = serde_json::from_str(record).unwrap();
12549            let filing = crate::direct::Filing {
12550                instruction: "work".into(),
12551                title: "direct".into(),
12552                repo: repo.clone(),
12553                source: crate::queue::Source::Human,
12554                solo: false,
12555                overrides,
12556                review_of: None,
12557                sources: Default::default(),
12558            };
12559            let filed =
12560                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
12561            let crate::direct::Filed::Standalone {
12562                mut task,
12563                claim: _claim,
12564            } = filed
12565            else {
12566                panic!("local filing")
12567            };
12568            let before = prepare_for(&repo, &opts, &task).unwrap();
12569            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
12570            assert_eq!(
12571                before.merge.mode,
12572                MergeMode::None,
12573                "daemon --merge must not leak"
12574            );
12575            for n in [2, 1, 2] {
12576                task.set_implementers(n, &validation).unwrap();
12577                q.put(&mut task).unwrap();
12578                task = q.get(&task.id).unwrap();
12579                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
12580                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
12581                apply_task_implementers(&mut cfg, &task);
12582                assert_eq!(cfg.graph.implementers, usize::from(n));
12583                assert_eq!(cfg.graph.judges, 2);
12584                assert_eq!(cfg.merge.mode, MergeMode::None);
12585            }
12586        }
12587    }
12588
12589    #[test]
12590    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
12591        let cfg: Config =
12592            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12593                .unwrap();
12594        let mut t = task();
12595        t.review_of = Some("review-target".into());
12596        t.hold_manual(Some("retry".into()));
12597        let mut previous = RunState::new(
12598            PathBuf::from("/repo"),
12599            "main".into(),
12600            "abc1234".into(),
12601            "review".into(),
12602            cfg.clone(),
12603        );
12604        previous.config.graph.implementers = 2;
12605        for count in [1, 3] {
12606            t.set_implementers(count, &cfg).unwrap();
12607            t.release();
12608            assert_eq!(t.review_of.as_deref(), Some("review-target"));
12609            for proposed in [
12610                Starter::Resume(previous.id.clone()),
12611                Starter::Review("recovery-target".into()),
12612            ] {
12613                assert_eq!(
12614                    starter_with_implementers(&t, Some(&previous), proposed),
12615                    Starter::Review("review-target".into())
12616                );
12617            }
12618            let mut configured = cfg.clone();
12619            apply_task_implementers(&mut configured, &t);
12620            assert_eq!(configured.graph.implementers, usize::from(count));
12621            assert_eq!(previous.config.graph.implementers, 2);
12622        }
12623    }
12624
12625    #[test]
12626    fn task_implementers_dispatch_and_resume_agree() {
12627        let mut t = task();
12628        let cfg: crate::config::Config =
12629            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12630                .unwrap();
12631        let mut run = RunState::new(
12632            PathBuf::from("/repo"),
12633            "main".into(),
12634            "abc1234".into(),
12635            "work".into(),
12636            cfg.clone(),
12637        );
12638        run.config.graph.implementers = 2;
12639        for n in [2, 1, 3, 2] {
12640            t.set_implementers(n, &cfg).unwrap();
12641            let mut dispatched = cfg.clone();
12642            apply_task_implementers(&mut dispatched, &t);
12643            assert_eq!(dispatched.graph.implementers, usize::from(n));
12644            assert_eq!(implementers_match(&t, &run), n == 2);
12645            for proposed in [
12646                Starter::Resume(run.id.clone()),
12647                Starter::Review("old-branch".into()),
12648            ] {
12649                let expected = if n == 2 {
12650                    proposed.clone()
12651                } else {
12652                    Starter::Start
12653                };
12654                assert_eq!(
12655                    starter_with_implementers(&t, Some(&run), proposed),
12656                    expected
12657                );
12658            }
12659            assert_eq!(
12660                run.config.graph.implementers, 2,
12661                "history must not be rewritten"
12662            );
12663        }
12664        t.solo = false;
12665        t.overrides = None;
12666        assert!(implementers_match(&t, &run));
12667    }
12668
12669    #[test]
12670    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
12671        // Three seats said out loud. What `solo` promises is one candidate
12672        // *whatever the config asks for*, so the contrast has to be a number
12673        // this test owns - it used to be `Config::default()`'s, which became
12674        // 1 when one implementation became the default and left the two
12675        // halves of this test asserting the same thing.
12676        let mut solo_cfg = Config::default();
12677        solo_cfg.graph.implementers = 3;
12678        let mut solo_task = task();
12679        solo_task.solo = true;
12680        apply_task_implementers(&mut solo_cfg, &solo_task);
12681        assert_eq!(solo_cfg.graph.implementers, 1);
12682
12683        let mut plain_cfg = Config::default();
12684        plain_cfg.graph.implementers = 3;
12685        let plain_task = task();
12686        assert!(!plain_task.solo);
12687        apply_task_implementers(&mut plain_cfg, &plain_task);
12688        assert_eq!(
12689            plain_cfg.graph.implementers, 3,
12690            "a task that did not ask to run alone keeps the config's candidates"
12691        );
12692    }
12693
12694    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
12695        QuotaLoss {
12696            cause: crate::agent::QuotaCause::UsageLimit,
12697            agent: String::new(),
12698            seat: seat.into(),
12699            node: "judge".into(),
12700            at: at.parse().unwrap(),
12701            reset: reset.map(str::to_string),
12702        }
12703    }
12704
12705    #[test]
12706    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
12707        let now = Timestamp::now();
12708        for reset in [None, Some("in 1h")] {
12709            let auth = crate::agent::Quota {
12710                cause: crate::agent::QuotaCause::Authentication,
12711                agent: "alpha".into(),
12712                reset: reset.map(str::to_owned),
12713            };
12714            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
12715            assert_eq!(cooldown_until(&[loss], now), None);
12716        }
12717    }
12718
12719    #[test]
12720    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
12721        let old: Vec<QuotaLoss> = (1..=4)
12722            .map(|i| {
12723                loss(
12724                    &format!("judge-{i}"),
12725                    "2026-09-23T05:23:00Z",
12726                    Some("2:40pm (Asia/Tokyo)"),
12727                )
12728            })
12729            .collect();
12730        let fresh = losses_this_attempt(&old, &old);
12731        assert!(fresh.is_empty());
12732        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
12733        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
12734    }
12735
12736    #[test]
12737    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
12738        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
12739        let now = Timestamp::now();
12740        let mut after = old.clone();
12741        after.push(loss("judge-2", &now.to_string(), None));
12742        let fresh = losses_this_attempt(&old, &after);
12743        assert_eq!(fresh, vec![after[1].clone()]);
12744        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
12745        assert_eq!(
12746            until,
12747            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
12748        );
12749    }
12750
12751    #[test]
12752    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
12753        // `recover_stall` removes judge-1's loss and the retry then hits quota
12754        // again: the vector is the same length, so an index diff sees nothing.
12755        let before = vec![
12756            loss("judge-1", "2026-09-23T05:23:00Z", None),
12757            loss("judge-2", "2026-09-23T05:24:00Z", None),
12758        ];
12759        let after = vec![
12760            loss("judge-2", "2026-09-23T05:24:00Z", None),
12761            loss("judge-1", "2026-09-24T01:00:00Z", None),
12762        ];
12763        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
12764    }
12765
12766    #[test]
12767    fn merge_overrides_are_parsed_or_refused() {
12768        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
12769        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
12770        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
12771        assert!(merge_mode("squash").is_err());
12772    }
12773
12774    #[test]
12775    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
12776        let now = Timestamp::now();
12777        let fallback = Duration::from_secs(300);
12778        let cap = Duration::from_secs(1800);
12779
12780        // No reset hint at all: the fallback.
12781        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
12782
12783        // A reset ten minutes out, well inside the cap: waited for exactly.
12784        let soon = now + jiff::SignedDuration::from_secs(600);
12785        assert_eq!(
12786            quota_wait(Some(soon), now, fallback, cap),
12787            Duration::from_secs(600)
12788        );
12789
12790        // A reset already in the past is not trusted: the fallback, not a
12791        // zero or negative wait that would spin the loop right back around.
12792        let past = now - jiff::SignedDuration::from_secs(60);
12793        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
12794
12795        // A reset further out than the cap is trusted for direction but not
12796        // for magnitude: a parsing slip must not sleep the loop for a day.
12797        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
12798        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
12799    }
12800
12801    #[test]
12802    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
12803        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12804
12805        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
12806        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
12807
12808        // Same clock reading, but it has already gone by today: read as
12809        // tomorrow's, since the CLI would not still be reporting a limit past
12810        // its own stated reset.
12811        let already_past =
12812            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
12813        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
12814
12815        assert!(
12816            parse_reset_hint("session limit reached", now, now).is_none(),
12817            "free text with no recognised shape is not guessed at"
12818        );
12819        assert!(
12820            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
12821            "an unresolvable zone name is not guessed at either"
12822        );
12823    }
12824
12825    #[test]
12826    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
12827        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12828
12829        let at = parse_reset_hint(
12830            "You've hit your usage limit. Visit \
12831             https://chatgpt.com/codex/settings/usage to purchase more \
12832             credits or try again at Sep 19th, 2026 5:10 PM.",
12833            now,
12834            now,
12835        )
12836        .expect("the codex reset wording is a recognised shape");
12837        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
12838
12839        // The month is explicit, so a date already earlier in the same
12840        // sentence-implied year than `now` is trusted as written rather than
12841        // rolled forward a year the way the bracketed shape rolls a
12842        // same-day clock reading to tomorrow.
12843        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
12844            .expect("an explicit year needs no rollover");
12845        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
12846
12847        assert!(
12848            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
12849            "a two-digit year is not the documented shape and is not guessed at"
12850        );
12851        assert!(
12852            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
12853            "a four-letter month name is not the documented three-letter abbreviation"
12854        );
12855        assert!(
12856            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
12857            "an explicit zone on the dated shape is a format nobody has \
12858             documented, and is refused rather than guessed at as UTC"
12859        );
12860    }
12861
12862    #[test]
12863    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
12864        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
12865        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
12866
12867        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
12868        assert_eq!(at.as_second() - recorded.as_second(), 3769);
12869
12870        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
12871        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
12872
12873        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
12874            assert!(
12875                parse_reset_hint(bad, now, recorded).is_none(),
12876                "{bad:?} must not be guessed at"
12877            );
12878        }
12879    }
12880
12881    /// A loop whose queue lives in a temp tree and whose poll interval is far
12882    /// longer than the test's patience, so anything that waits out a poll
12883    /// instead of noticing the stop fails rather than merely being slow.
12884    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
12885        let config = dir.join("magi.toml");
12886        std::fs::write(
12887            &config,
12888            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
12889        )
12890        .unwrap();
12891        let opts = Opts {
12892            poll: Duration::from_secs(30),
12893            config: Some(config),
12894            // The explicit fixture config keeps startup cleanup from reading
12895            // machine configuration. This fictional repository likewise
12896            // keeps any best-effort git cleanup away from this checkout.
12897            repo: dir.join("repo"),
12898            ..Opts::default()
12899        };
12900        // The status file goes in a directory that does not exist yet, so its
12901        // creation is itself evidence the loop published one. `worktrees`
12902        // must be just as fictional: the janitor reclaims worktrees under it
12903        // for real, and a test that let it fall through to
12904        // `crate::run::default_worktree_root()` would have it reclaim
12905        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
12906        // which is exactly what happened before this function took the
12907        // parameter at all.
12908        let home = dir.join("home");
12909        // These control-only fixtures do not launch native workers. Give the
12910        // independently tested maintenance services a fresh cadence receipt.
12911        let stamps = home.join("service-ticks");
12912        std::fs::create_dir_all(&stamps).unwrap();
12913        for service in ["waiter", "deputies", "release-watch"] {
12914            std::fs::write(
12915                stamps.join(service),
12916                Timestamp::now().as_second().to_string(),
12917            )
12918            .unwrap();
12919        }
12920        for operation in [
12921            "conductor",
12922            "maintenance",
12923            "housekeeping",
12924            "disk-pressure",
12925            "fold",
12926            "cache",
12927            "fetch",
12928            "chat-goals",
12929            "decisions",
12930        ] {
12931            std::fs::write(
12932                stamps.join(format!("daemon-{operation}")),
12933                serde_json::to_vec(&Timestamp::now()).unwrap(),
12934            )
12935            .unwrap();
12936        }
12937        let worktrees = dir.join("wt");
12938        (
12939            opts,
12940            Queue::at(dir.join("queue")),
12941            home.join("daemon.json"),
12942            home,
12943            worktrees,
12944        )
12945    }
12946
12947    #[tokio::test]
12948    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
12949        let dir = tempfile::tempdir().unwrap();
12950        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12951        let mut waiting = task();
12952        waiting.repo = opts.repo.clone();
12953        waiting.hold_machine(crate::disk::gate(1, 100));
12954        waiting.mark_disk_capacity();
12955        waiting.attempts = 2;
12956        queue.put(&mut waiting).unwrap();
12957        let mut busy = task();
12958        busy.status = TaskStatus::Running;
12959        queue.put(&mut busy).unwrap();
12960        let payload = serde_json::to_value(ServiceWorker {
12961            opts,
12962            queue: queue.root().to_owned(),
12963            worktrees_root: worktrees,
12964            operation: "maintenance".into(),
12965        })
12966        .unwrap();
12967        run_service_worker(&home, payload.clone()).await.unwrap();
12968        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
12969        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12970        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
12971        run_service_worker(&home, payload).await.unwrap();
12972        assert!(
12973            crate::worker::active(&home).unwrap().is_empty(),
12974            "monitoring only queues; normal dispatch owns launches"
12975        );
12976        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
12977    }
12978
12979    #[tokio::test]
12980    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
12981        let dir = tempfile::tempdir().unwrap();
12982        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12983        let cfg = Config::default();
12984        start_service(
12985            &home,
12986            &opts,
12987            &queue,
12988            &worktrees,
12989            "housekeeping",
12990            Some(&cfg),
12991            true,
12992        )
12993        .await
12994        .unwrap();
12995        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
12996        let read = |path: &Path| -> serde_json::Value {
12997            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
12998        };
12999        assert_eq!(read(&receipt)["detail"], "cadence not due");
13000        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
13001        start_service(
13002            &home,
13003            &opts,
13004            &queue,
13005            &worktrees,
13006            "housekeeping",
13007            Some(&cfg),
13008            true,
13009        )
13010        .await
13011        .unwrap();
13012        assert_eq!(
13013            read(&receipt)["detail"],
13014            "active work or runnable task queue"
13015        );
13016        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
13017        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
13018        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
13019        start_service(
13020            &home,
13021            &opts,
13022            &queue,
13023            &worktrees,
13024            "disk-pressure",
13025            Some(&cfg),
13026            false,
13027        )
13028        .await
13029        .unwrap();
13030        assert_eq!(
13031            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
13032            "no active work; idle housekeeping owns scan"
13033        );
13034        assert!(crate::worker::active(&home).unwrap().is_empty());
13035    }
13036
13037    /// The folding turn exists exactly where idle housekeeping does not: with
13038    /// work busy or runnable. On `origin/main` the only caller of
13039    /// `clean::fold_due` was housekeeping, so a queue that was never empty
13040    /// admitted no finished-run folding at all.
13041    #[test]
13042    fn the_fold_turn_is_admitted_exactly_where_housekeeping_is_not() {
13043        let on = Config::default();
13044        for busy in [false, true] {
13045            for runnable in [false, true] {
13046                assert_ne!(
13047                    housekeeping_eligible(busy, runnable),
13048                    fold_turn_eligible(busy, runnable, Some(&on)),
13049                    "busy={busy} runnable={runnable}"
13050                );
13051            }
13052        }
13053        assert!(!housekeeping_eligible(true, true), "the 1275 machine");
13054        assert!(!fold_turn_eligible(true, true, None));
13055        let mut off = Config::default();
13056        off.disk.auto_fold = false;
13057        assert!(!fold_turn_eligible(true, true, Some(&off)));
13058        assert!(fold_turn_eligible(true, true, Some(&Config::default())));
13059    }
13060
13061    #[tokio::test]
13062    async fn the_fold_service_says_why_it_skipped_a_dispatch() {
13063        let dir = tempfile::tempdir().unwrap();
13064        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13065        let read = || -> serde_json::Value {
13066            serde_json::from_slice(
13067                &std::fs::read(home.join("source-eviction-fold-dispatch.json")).unwrap(),
13068            )
13069            .unwrap()
13070        };
13071        let tick = home.join("service-ticks/daemon-fold");
13072        let cfg = Config::default();
13073        let dispatch = |busy: bool, cfg: Config| {
13074            let (home, opts, queue, worktrees) = (&home, &opts, &queue, &worktrees);
13075            async move {
13076                start_service(home, opts, queue, worktrees, "fold", Some(&cfg), busy)
13077                    .await
13078                    .unwrap();
13079            }
13080        };
13081        dispatch(true, cfg.clone()).await;
13082        assert_eq!(read()["detail"], "cadence not due");
13083
13084        std::fs::remove_file(&tick).unwrap();
13085        dispatch(false, cfg.clone()).await;
13086        assert_eq!(
13087            read()["detail"],
13088            "idle machine; housekeeping owns finished-run folding"
13089        );
13090        let mut off = cfg.clone();
13091        off.disk.auto_fold = false;
13092        dispatch(true, off).await;
13093        assert_eq!(read()["detail"], "auto_fold disabled");
13094        // An unreadable startup configuration is its own reason, not "idle".
13095        start_service(&home, &opts, &queue, &worktrees, "fold", None, true)
13096            .await
13097            .unwrap();
13098        assert_eq!(read()["detail"], "startup configuration unavailable");
13099
13100        // A housekeeping worker already folding: one folding service at a time.
13101        let directory = home.join("workers/jobs/abcdef");
13102        std::fs::create_dir_all(&directory).unwrap();
13103        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13104        crate::pr_head::try_lock_file(&lease).unwrap();
13105        let mut job = crate::worker::Job {
13106            id: "abcdef".into(),
13107            sequence: 1,
13108            kind: "daemon-service".into(),
13109            key: "service:daemon-housekeeping".into(),
13110            payload: serde_json::Value::Null,
13111            generation: "fixture".into(),
13112            version: None,
13113            status: crate::worker::Status::Running,
13114            result: None,
13115            pid: Some(std::process::id()),
13116            created_at: Timestamp::now().as_second() as u64,
13117            finished_at: None,
13118        };
13119        let record = directory.join("job.json");
13120        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13121        dispatch(true, cfg).await;
13122        assert_eq!(
13123            read()["detail"],
13124            "another finished-run folding service is active"
13125        );
13126        assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
13127        job.status = crate::worker::Status::Finished;
13128        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13129        drop(lease);
13130    }
13131
13132    /// Issue 1275 through the scheduler's own admission: a leased task worker is
13133    /// busy, another task is runnable, and a confirmed merged run of the same
13134    /// repository is long past its grace. `poll` admits the fold service (the
13135    /// worker runs inline here: a unit test has no `magi` executable to exec),
13136    /// the historical worktree goes, the repository's active checkout stays and
13137    /// the merged run's evidence is kept. Removing `"fold"` from the operation
13138    /// list in `poll` leaves the worktree standing and fails this test.
13139    #[tokio::test]
13140    async fn the_scheduler_folds_a_merged_run_beside_a_busy_worker_and_a_runnable_task() {
13141        let dir = tempfile::tempdir().unwrap();
13142        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13143        let repo = dir.path().join("checkout");
13144        std::fs::create_dir_all(&repo).unwrap();
13145        crate::clean::tests::init_repo(&repo);
13146        std::fs::write(
13147            opts.config.as_ref().unwrap(),
13148            "[disk]\nmin_free_bytes = 0\nauto_fold = true\ncache_limit_bytes = 0\n",
13149        )
13150        .unwrap();
13151        let (id, historical) = crate::clean::tests::merged_run_with_worktree(
13152            &home,
13153            &repo,
13154            &worktrees,
13155            "20260801-000000-s001",
13156        )
13157        .await;
13158        let active = dir.path().join("active");
13159        crate::git::worktree_add_branch(&repo, &active, "magi/active", "main")
13160            .await
13161            .unwrap();
13162        // The busy worker belongs to the scheduler's own queue and owns a
13163        // recorded run of the same repository that is eligible on paper
13164        // (finished, past its grace). Its execution lease is held, as a
13165        // driving worker holds it.
13166        let (owned_id, owned_worktree) = crate::clean::tests::due_run_with_winner_worktree(
13167            &home.join("runs"),
13168            &worktrees,
13169            &repo,
13170            "20260801-000000-s002",
13171            RunStatus::Superseded,
13172        )
13173        .await;
13174        let owned_run = home.join("runs").join(&owned_id);
13175        let owned_record = std::fs::read(owned_run.join("run.json")).unwrap();
13176        let mut busy = task();
13177        busy.repo = repo.clone();
13178        busy.status = TaskStatus::Running;
13179        busy.link_run(&owned_id);
13180        queue.put(&mut busy).unwrap();
13181        let worker_lease = crate::worker::running_fixture(
13182            &home,
13183            &format!("task:{}", busy.id),
13184            serde_json::to_value(TaskWorker {
13185                opts: Opts::default(),
13186                queue: queue.root().to_owned(),
13187                task: busy.id.clone(),
13188                lane: PermitKind::default(),
13189                standalone: true,
13190            })
13191            .unwrap(),
13192        )
13193        .unwrap();
13194        let execution = crate::driver::maintenance(&home, &owned_id).unwrap();
13195        let mut waiting = task();
13196        waiting.repo = repo.clone();
13197        queue.put(&mut waiting).unwrap();
13198        std::fs::remove_file(home.join("service-ticks/daemon-fold")).unwrap();
13199
13200        let mut cfg = Config::default();
13201        cfg.disk.auto_fold = true;
13202        INLINE_SERVICES.with(|inline| inline.set(true));
13203        let status = Arc::new(Mutex::new(Status::new()));
13204        let stop = Stop::new();
13205        let mut dispatch = Box::pin(poll(
13206            &opts,
13207            &queue,
13208            &status,
13209            &home,
13210            &worktrees,
13211            &stop,
13212            DispatchLimits {
13213                max_concurrent: 0,
13214                pause_for_interrupts: false,
13215                recovery_cfg: Some(cfg),
13216            },
13217        ));
13218        let receipt = home.join("source-eviction-fold-worker.json");
13219        let completed = async {
13220            loop {
13221                let done = std::fs::read(&receipt)
13222                    .ok()
13223                    .and_then(|body| serde_json::from_slice::<serde_json::Value>(&body).ok())
13224                    .is_some_and(|receipt| receipt["outcome"] == "completed");
13225                if done {
13226                    break;
13227                }
13228                tokio::time::sleep(Duration::from_millis(25)).await;
13229            }
13230        };
13231        tokio::select! {
13232            result = &mut dispatch => panic!("the scheduler stopped before the fold service ran: {result:?}"),
13233            result = tokio::time::timeout(Duration::from_secs(120), completed) => {
13234                result.expect("the scheduler never admitted the fold service");
13235            }
13236        }
13237        stop.stop();
13238        dispatch.await.unwrap();
13239        INLINE_SERVICES.with(|inline| inline.set(false));
13240
13241        assert!(!historical.exists(), "the merged run's worktree is folded");
13242        assert!(
13243            active.join("README.md").is_file(),
13244            "the repository's active checkout is untouched"
13245        );
13246        let run = home.join("runs").join(&id);
13247        assert!(run.join("run.json").is_file());
13248        assert!(run.join("artifacts/fold-evidence/manifest.json").is_file());
13249        let read = |name: &str| -> serde_json::Value {
13250            serde_json::from_slice(&std::fs::read(home.join(name)).unwrap()).unwrap()
13251        };
13252        assert_eq!(
13253            read("source-eviction-fold-dispatch.json")["detail"],
13254            "eligible and cadence due"
13255        );
13256        let worker = read("source-eviction-fold-worker.json");
13257        assert_eq!(worker["fold"]["records"], 2);
13258        assert_eq!(worker["fold"]["folded"], 1);
13259        assert_eq!(worker["fold"]["invoked"], 1);
13260        assert_eq!(
13261            worker["fold"]["live"], 1,
13262            "the busy worker's own run is left alone: {worker}"
13263        );
13264        // The run the busy worker owns - eligible on paper (finished, past its
13265        // grace) - keeps its checkout, its candidate and its record, byte for byte.
13266        assert!(owned_worktree.exists());
13267        assert_eq!(
13268            std::fs::read(owned_run.join("run.json")).unwrap(),
13269            owned_record
13270        );
13271        assert!(
13272            !RunState::load_under(&owned_id, &home).unwrap().candidates[0].folded,
13273            "the owned run's candidate is not folded"
13274        );
13275        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13276        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13277        drop(execution);
13278        drop(worker_lease);
13279    }
13280
13281    /// On a platform without process containment the disk-pressure service
13282    /// refuses to reclaim, and says so in both places an operator looks: the
13283    /// persisted retention report and the worker receipt. Driven through the
13284    /// service handler itself, so removing either publication fails this test.
13285    #[tokio::test]
13286    async fn the_disk_pressure_service_reports_a_platform_without_containment() {
13287        let dir = tempfile::tempdir().unwrap();
13288        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13289        let payload = serde_json::to_value(ServiceWorker {
13290            opts,
13291            queue: queue.root().to_owned(),
13292            worktrees_root: worktrees,
13293            operation: "disk-pressure".into(),
13294        })
13295        .unwrap();
13296        let _platform = crate::retention::WithoutContainment::new();
13297        run_service_worker(&home, payload).await.unwrap();
13298
13299        let refusal = "Automatic output reclamation requires Unix process containment";
13300        let report: serde_json::Value =
13301            serde_json::from_slice(&std::fs::read(home.join("retention.json")).unwrap()).unwrap();
13302        assert_eq!(report["failures"], serde_json::json!([refusal]));
13303        let receipt: serde_json::Value = serde_json::from_slice(
13304            &std::fs::read(home.join("source-eviction-disk-pressure-worker.json")).unwrap(),
13305        )
13306        .unwrap();
13307        assert_eq!(receipt["outcome"], "retention swept");
13308        assert_eq!(receipt["retention"]["failure_count"], 1);
13309        assert_eq!(
13310            receipt["retention"]["failures"],
13311            serde_json::json!([refusal])
13312        );
13313    }
13314
13315    #[tokio::test]
13316    async fn goal_observation_service_does_not_block_scheduler_decisions() {
13317        let dir = tempfile::tempdir().unwrap();
13318        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
13319        let queue = Queue::at(home.join("queue"));
13320        let mut task = task();
13321        task.repo = opts.repo.clone();
13322        task.chat = Some("decision-chat".into());
13323        task.hold_machine(Some("waiting for a decision".into()));
13324        queue.put(&mut task).unwrap();
13325        let questions = Questions::at(home.join("questions"));
13326        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
13327        question.node = crate::conduct::NODE.into();
13328        question.status = ask::QuestionStatus::Open;
13329        question.answer = None;
13330        question.answered_at = None;
13331        questions.put(&mut question).unwrap();
13332        questions
13333            .update(&question.id, |q| {
13334                q.answer(ask::Answer::Choice("resume で続行する".into()))
13335            })
13336            .unwrap();
13337
13338        let talks = crate::talk::Talks::at(home.join("talks"));
13339        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
13340        decision_chat.pending = "Keep this unsent status question".into();
13341        talks.put(&mut decision_chat).unwrap();
13342        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
13343        talk.goals.push(serde_json::from_value(serde_json::json!({
13344            "id":"goal","purpose":"follow the retained job","scope":"one task",
13345            "condition":{"description":"land the result","kind":"runs_merged"},
13346            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
13347            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
13348            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
13349        })).unwrap());
13350        talks.put(&mut talk).unwrap();
13351
13352        // A retained service lease models an observation still waiting on its
13353        // external dependency. Admission must neither await nor repeat it.
13354        let directory = home.join("workers/jobs/abcdef");
13355        std::fs::create_dir_all(&directory).unwrap();
13356        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13357        crate::pr_head::try_lock_file(&lease).unwrap();
13358        let mut job = crate::worker::Job {
13359            id: "abcdef".into(),
13360            sequence: 1,
13361            kind: "daemon-service".into(),
13362            key: "service:daemon-chat-goals".into(),
13363            payload: serde_json::Value::Null,
13364            generation: "fixture".into(),
13365            version: None,
13366            status: crate::worker::Status::Running,
13367            result: None,
13368            pid: Some(std::process::id()),
13369            created_at: Timestamp::now().as_second() as u64,
13370            finished_at: None,
13371        };
13372        let record = directory.join("job.json");
13373        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13374        let status = Arc::new(Mutex::new(Status::new()));
13375        let stop = Stop::new();
13376        let mut dispatch = Box::pin(poll(
13377            &opts,
13378            &queue,
13379            &status,
13380            &home,
13381            &worktrees,
13382            &stop,
13383            DispatchLimits {
13384                max_concurrent: 1,
13385                pause_for_interrupts: false,
13386                recovery_cfg: None,
13387            },
13388        ));
13389        std::future::poll_fn(|cx| {
13390            assert!(dispatch.as_mut().poll(cx).is_pending());
13391            std::task::Poll::Ready(())
13392        })
13393        .await;
13394        assert!(lock(&status).polls > 0);
13395        let saved = queue.get(&task.id).unwrap();
13396        assert_eq!(saved.status, TaskStatus::Done);
13397        assert!(saved.action_applied(&question.id));
13398        assert!(
13399            talks
13400                .get("decision-chat")
13401                .unwrap()
13402                .pending
13403                .contains("Keep this unsent status question")
13404        );
13405        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
13406        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
13407        assert_eq!(
13408            goal.started,
13409            Some(1),
13410            "only the observation worker may reconcile its goal"
13411        );
13412        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
13413
13414        stop.stop();
13415        dispatch.await.unwrap();
13416        job.status = crate::worker::Status::Finished;
13417        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13418        drop(lease);
13419    }
13420
13421    #[test]
13422    fn a_stop_is_idempotent_and_once_set_stays_set() {
13423        let stop = Stop::new();
13424        assert!(!stop.stopped());
13425
13426        stop.stop();
13427        assert!(stop.stopped());
13428        stop.stop();
13429        assert!(stop.stopped(), "a second stop is not a toggle");
13430
13431        let shared = stop.clone();
13432        assert!(
13433            shared.stopped(),
13434            "a clone is the same stop; that is how the loop and its caller share one"
13435        );
13436    }
13437
13438    #[tokio::test]
13439    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
13440        for operation in ["conductor", "maintenance", "housekeeping"] {
13441            let dir = tempfile::tempdir().unwrap();
13442            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
13443            opts.once = true;
13444            opts.poll = Duration::from_millis(1);
13445            // This test exercises answer scheduling, not explicit discard:
13446            // ordinary Done requires a completed retained execution.
13447            let mut state = run_state(RunStatus::Ready);
13448            state.reserve_under(&home).unwrap();
13449            state.save_under(&home).unwrap();
13450            let mut task = task();
13451            task.runs.push(state.id.clone());
13452            queue.put(&mut task).unwrap();
13453            let claim = queue.claim(&task.id).unwrap();
13454
13455            // Model a live service holding the task's claim across the
13456            // scheduler's dispatch scan. No real subprocess or timed race.
13457            let directory = home.join("workers/jobs/abcdef");
13458            std::fs::create_dir_all(&directory).unwrap();
13459            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13460            crate::pr_head::try_lock_file(&lease).unwrap();
13461            let mut job = crate::worker::Job {
13462                id: "abcdef".into(),
13463                sequence: 1,
13464                kind: "daemon-service".into(),
13465                key: format!("service:daemon-{operation}"),
13466                payload: serde_json::Value::Null,
13467                generation: "fixture".into(),
13468                version: None,
13469                status: crate::worker::Status::Running,
13470                result: None,
13471                pid: Some(std::process::id()),
13472                created_at: Timestamp::now().as_second() as u64,
13473                finished_at: None,
13474            };
13475            let record = directory.join("job.json");
13476            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13477
13478            let status = Arc::new(Mutex::new(Status::new()));
13479            let stop = Stop::new();
13480            let mut drain = Box::pin(poll(
13481                &opts,
13482                &queue,
13483                &status,
13484                &home,
13485                &worktrees,
13486                &stop,
13487                DispatchLimits {
13488                    max_concurrent: 1,
13489                    pause_for_interrupts: false,
13490                    recovery_cfg: None,
13491                },
13492            ));
13493            std::future::poll_fn(|cx| {
13494                use std::future::Future;
13495                assert!(
13496                    drain.as_mut().poll(cx).is_pending(),
13497                    "--once must wait for {operation} to release its queue claim"
13498                );
13499                std::task::Poll::Ready(())
13500            })
13501            .await;
13502            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
13503
13504            // An answer arrives while the service still owns the claim. A
13505            // fresh scheduling pass must apply it before declaring idle.
13506            let questions = Questions::at(home.join("questions"));
13507            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13508            questions.put(&mut q).unwrap();
13509            drop(claim);
13510            // Model services that took longer than their cadence, without a
13511            // wall-clock sleep. The final scans must not respawn them even
13512            // though their receipts now permit another periodic invocation.
13513            let expired =
13514                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
13515            for service in [operation, "housekeeping"] {
13516                std::fs::write(
13517                    home.join("service-ticks").join(format!("daemon-{service}")),
13518                    &expired,
13519                )
13520                .unwrap();
13521            }
13522            job.status = crate::worker::Status::Finished;
13523            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13524            drop(lease);
13525            tokio::time::timeout(Duration::from_secs(2), drain)
13526                .await
13527                .expect("the settled service must allow the drain to finish")
13528                .unwrap();
13529            let after = queue.get(&task.id).unwrap();
13530            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
13531            assert!(after.action_applied(&q.id));
13532            for service in [operation, "housekeeping"] {
13533                assert_eq!(
13534                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
13535                        .unwrap(),
13536                    expired,
13537                    "the final once rescan must not restart {service}"
13538                );
13539            }
13540        }
13541    }
13542
13543    #[test]
13544    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
13545        let stop = Stop::new();
13546        stop.busy.store(1, Ordering::SeqCst);
13547        assert!(
13548            !stop.finishing(),
13549            "a busy loop nobody has asked to stop is just running"
13550        );
13551
13552        stop.stop();
13553        assert!(
13554            stop.finishing(),
13555            "a stop asked for mid-run has not landed until the run is settled"
13556        );
13557
13558        stop.busy.store(0, Ordering::SeqCst);
13559        assert!(
13560            !stop.finishing(),
13561            "once the run is settled the stop has landed and there is nothing to finish"
13562        );
13563    }
13564
13565    #[test]
13566    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
13567        let stop = Stop::new();
13568        stop.busy.store(2, Ordering::SeqCst);
13569        stop.stop();
13570        assert!(stop.finishing(), "two runs still in flight");
13571
13572        stop.busy.store(1, Ordering::SeqCst);
13573        assert!(
13574            stop.finishing(),
13575            "one run finished, but a sibling is still working"
13576        );
13577
13578        stop.busy.store(0, Ordering::SeqCst);
13579        assert!(
13580            !stop.finishing(),
13581            "the last run out is what actually lands the stop"
13582        );
13583    }
13584
13585    #[tokio::test]
13586    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
13587        let dir = tempfile::tempdir().unwrap();
13588        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13589        let stop = Stop::new();
13590        stop.stop();
13591
13592        let began = std::time::Instant::now();
13593        tokio::time::timeout(
13594            Duration::from_secs(2),
13595            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13596        )
13597        .await
13598        .expect("a stopped loop must return, not sit out its poll interval")
13599        .expect("the loop's own setup and teardown must not fail");
13600        assert!(
13601            began.elapsed() < opts.poll,
13602            "returned only after {:?}, which is a poll interval, not a stop",
13603            began.elapsed()
13604        );
13605    }
13606
13607    #[tokio::test]
13608    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
13609        let dir = tempfile::tempdir().unwrap();
13610        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13611        let stop = Stop::new();
13612
13613        // Asked for after the loop is already parked on its empty queue, which
13614        // is the case an operator tapping stop on a phone actually hits.
13615        let asker = {
13616            let stop = stop.clone();
13617            tokio::spawn(async move {
13618                tokio::time::sleep(Duration::from_millis(20)).await;
13619                stop.stop();
13620            })
13621        };
13622
13623        let began = std::time::Instant::now();
13624        tokio::time::timeout(
13625            Duration::from_secs(2),
13626            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13627        )
13628        .await
13629        .expect("a stop asked for while idle must wake the wait")
13630        .expect("the loop's own setup and teardown must not fail");
13631        asker.await.unwrap();
13632        assert!(
13633            began.elapsed() < opts.poll,
13634            "returned only after {:?}, so the stop waited on the sleep",
13635            began.elapsed()
13636        );
13637    }
13638
13639    #[tokio::test]
13640    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
13641        let dir = tempfile::tempdir().unwrap();
13642        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13643        let stop = Stop::new();
13644        stop.stop();
13645
13646        tokio::time::timeout(
13647            Duration::from_secs(2),
13648            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13649        )
13650        .await
13651        .expect("a stopped loop must return")
13652        .expect("the loop's own setup and teardown must not fail");
13653
13654        assert!(
13655            home.is_dir(),
13656            "the loop did publish a status file, so its removal is the teardown and not an absence"
13657        );
13658        assert!(
13659            !status_file.exists(),
13660            "a stopped loop clears its status file"
13661        );
13662        assert!(
13663            read_status(&home).is_none(),
13664            "a reader must see no daemon at all, not a heartbeat that merely stopped"
13665        );
13666    }
13667
13668    #[tokio::test]
13669    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
13670        let dir = tempfile::tempdir().unwrap();
13671        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13672
13673        let mut settled = RunState::new(
13674            dir.path().join("repo"),
13675            "main".to_owned(),
13676            "abc1234".to_owned(),
13677            "fixture".to_owned(),
13678            Config::default(),
13679        );
13680        settled.status = RunStatus::Ready;
13681        let run_dir = home.join("runs").join(&settled.id);
13682        std::fs::create_dir_all(&run_dir).unwrap();
13683        std::fs::write(
13684            run_dir.join("run.json"),
13685            serde_json::to_string_pretty(&settled).unwrap(),
13686        )
13687        .unwrap();
13688        let questions = Questions::at(home.join("questions"));
13689        let mut question = ask::Question::new(
13690            settled.id.clone(),
13691            "review".to_owned(),
13692            "reviewer-1".to_owned(),
13693            "Continue?".to_owned(),
13694            String::new(),
13695            Vec::new(),
13696        );
13697        questions.put(&mut question).unwrap();
13698
13699        run_service_worker(
13700            &home,
13701            serde_json::to_value(ServiceWorker {
13702                opts,
13703                queue: queue.root().to_path_buf(),
13704                worktrees_root: worktrees,
13705                operation: "housekeeping".to_owned(),
13706            })
13707            .unwrap(),
13708        )
13709        .await
13710        .unwrap();
13711
13712        assert_eq!(
13713            questions.get(&question.id).unwrap().status,
13714            ask::QuestionStatus::Abandoned,
13715            "the independent housekeeping worker settles ended-run questions"
13716        );
13717    }
13718
13719    #[test]
13720    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
13721        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13722
13723        assert!(
13724            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
13725            "never checked before: due at once"
13726        );
13727
13728        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
13729        assert!(
13730            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
13731            "well inside the interval: not due yet"
13732        );
13733
13734        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
13735        assert!(
13736            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
13737            "exactly at the edge: not yet due, same convention as `clean::due`"
13738        );
13739
13740        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13741        assert!(
13742            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
13743            "past the interval: due again"
13744        );
13745    }
13746
13747    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
13748    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
13749    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
13750    /// and the congestion test below both need, and must not drift apart.
13751    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
13752        let config = dir.join("magi.toml");
13753        // A literal (single-quoted) TOML string, not a basic one: the cache
13754        // path is a Windows path full of backslashes, and a basic string
13755        // would have TOML try to interpret `\U` (from `\Users\...`) as a
13756        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
13757        // `{{ vars.cache }}` rendering documents.
13758        std::fs::write(
13759            &config,
13760            format!(
13761                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
13762                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
13763                cache_dir.display()
13764            ),
13765        )
13766        .unwrap();
13767        Opts {
13768            config: Some(config),
13769            repo: dir.join("repo"),
13770            ..Opts::default()
13771        }
13772    }
13773
13774    #[tokio::test]
13775    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
13776        let dir = tempfile::tempdir().unwrap();
13777        let home = dir.path().join("home");
13778        let cache_dir = dir.path().join("cache");
13779        std::fs::create_dir_all(&cache_dir).unwrap();
13780        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13781        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13782
13783        // Nobody has asked this daemon to stop, which is the ordinary case;
13784        // the skip that a stop buys is asserted by its own test below.
13785        let running = Stop::new();
13786        let mut last_checked = None;
13787        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13788        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
13789            .await;
13790        assert_eq!(
13791            crate::disk::dir_size(&cache_dir),
13792            0,
13793            "over the cap on the first check ever: pruned at once, no idle queue required"
13794        );
13795        assert_eq!(last_checked, Some(t0));
13796
13797        // A fresh oversized file lands, but the next check is not due yet.
13798        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
13799        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
13800        maybe_prune_cache_between_runs(
13801            &opts.repo,
13802            &opts,
13803            &home,
13804            &running,
13805            &mut last_checked,
13806            too_soon,
13807        )
13808        .await;
13809        assert_eq!(
13810            crate::disk::dir_size(&cache_dir),
13811            10,
13812            "too soon since the last check: left alone rather than rescanned every call"
13813        );
13814        assert_eq!(
13815            last_checked,
13816            Some(t0),
13817            "an idle check does not reset the clock"
13818        );
13819
13820        // Once the interval elapses, the same oversized cache is caught again.
13821        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13822        maybe_prune_cache_between_runs(
13823            &opts.repo,
13824            &opts,
13825            &home,
13826            &running,
13827            &mut last_checked,
13828            due_again,
13829        )
13830        .await;
13831        assert_eq!(
13832            crate::disk::dir_size(&cache_dir),
13833            0,
13834            "due again: pruned back under the cap"
13835        );
13836    }
13837
13838    /// A stop must not queue behind housekeeping. The prune below is a
13839    /// synchronous walk of the whole cache with no await point in it, so a
13840    /// loop that entered it could not get back to its own `stopped()` test
13841    /// until the walk finished - and because no run is in flight at this
13842    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
13843    /// the stop had already landed. The idle branch has always made this same
13844    /// check before reaching `janitor`; the between-runs path makes it too.
13845    #[tokio::test]
13846    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
13847        let dir = tempfile::tempdir().unwrap();
13848        let home = dir.path().join("home");
13849        let cache_dir = dir.path().join("cache");
13850        std::fs::create_dir_all(&cache_dir).unwrap();
13851        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13852        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13853
13854        let stop = Stop::new();
13855        stop.stop();
13856        assert!(
13857            !stop.finishing(),
13858            "no run is in flight at a between-runs boundary, so nothing else \
13859             would tell the operator this stop had not taken effect yet"
13860        );
13861
13862        let mut last_checked = None;
13863        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13864        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
13865            .await;
13866        assert_eq!(
13867            crate::disk::dir_size(&cache_dir),
13868            10,
13869            "over its cap, and due for the first check ever, but a stop outranks \
13870             it: the cap is a standing policy the next start measures again"
13871        );
13872        assert_eq!(
13873            last_checked, None,
13874            "a check that never happened must not claim the interval"
13875        );
13876    }
13877
13878    /// A backlog must not starve cache pruning. The finite cache worker runs
13879    /// independently of queue drain and must not consume any task attempts.
13880    #[tokio::test]
13881    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
13882        let dir = tempfile::tempdir().unwrap();
13883        let cache_dir = dir.path().join("cache");
13884        std::fs::create_dir_all(&cache_dir).unwrap();
13885        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
13886
13887        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
13888        opts.poll = Duration::from_millis(20);
13889        opts.max_attempts = 1_000;
13890
13891        let queue = Queue::at(dir.path().join("queue"));
13892        for i in 0..128 {
13893            let mut task = Task::new(
13894                format!("queued work {i}"),
13895                format!("queued work {i}"),
13896                opts.repo.clone(),
13897                Source::Human,
13898            );
13899            queue.put(&mut task).unwrap();
13900        }
13901
13902        let home = dir.path().join("home");
13903        let worktrees = dir.path().join("wt");
13904        run_service_worker(
13905            &home,
13906            serde_json::to_value(ServiceWorker {
13907                opts,
13908                queue: queue.root().to_path_buf(),
13909                worktrees_root: worktrees,
13910                operation: "cache".to_owned(),
13911            })
13912            .unwrap(),
13913        )
13914        .await
13915        .unwrap();
13916        let after = queue.list();
13917        assert_eq!(after.len(), 128);
13918        assert!(
13919            after
13920                .iter()
13921                .all(|task| task.status.runnable() && task.attempts == 0)
13922        );
13923
13924        assert_eq!(
13925            crate::disk::dir_size(&cache_dir),
13926            0,
13927            "an oversized cache must not be left to grow unboundedly just because the \
13928             queue kept the loop busy the whole time"
13929        );
13930    }
13931
13932    #[test]
13933    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
13934        let dir = tempfile::tempdir().unwrap();
13935        let queue = Queue::at(dir.path().join("queue"));
13936        let questions = Questions::at(dir.path().join("questions"));
13937        let mut task = task();
13938        queue.put(&mut task).unwrap();
13939
13940        let mut task_question = ask::Question::new(
13941            task.id.clone(),
13942            crate::conduct::NODE.to_owned(),
13943            "conduct".to_owned(),
13944            "Which backend?".to_owned(),
13945            String::new(),
13946            Vec::new(),
13947        );
13948        questions.put(&mut task_question).unwrap();
13949        task.block(vec![task_question.id.clone()], None);
13950        queue.put(&mut task).unwrap();
13951
13952        let mut run_question = ask::Question::new(
13953            "20260101-000000-run1".to_owned(),
13954            "review".to_owned(),
13955            "reviewer-1".to_owned(),
13956            "Run question".to_owned(),
13957            String::new(),
13958            Vec::new(),
13959        );
13960        questions.put(&mut run_question).unwrap();
13961
13962        // A question from another node whose `run` happens to equal this
13963        // task's id — the same field, filled in for an unrelated reason. Only
13964        // `crate::conduct::NODE` questions use `run` as a task id; this one
13965        // must never be touched by this reconciliation, even after release.
13966        let mut coincidental = ask::Question::new(
13967            task.id.clone(),
13968            "review".to_owned(),
13969            "reviewer-1".to_owned(),
13970            "Unrelated review question".to_owned(),
13971            String::new(),
13972            Vec::new(),
13973        );
13974        questions.put(&mut coincidental).unwrap();
13975
13976        reconcile_task_questions(&queue, &questions);
13977        assert!(questions.get(&task_question.id).unwrap().status.open());
13978        assert!(questions.get(&run_question.id).unwrap().status.open());
13979        assert!(questions.get(&coincidental.id).unwrap().status.open());
13980
13981        task.release();
13982        queue.put(&mut task).unwrap();
13983        reconcile_task_questions(&queue, &questions);
13984        assert_eq!(
13985            questions.get(&task_question.id).unwrap().status,
13986            ask::QuestionStatus::Abandoned
13987        );
13988        assert!(
13989            questions.get(&run_question.id).unwrap().status.open(),
13990            "run questions remain the run janitor's responsibility"
13991        );
13992        assert!(
13993            questions.get(&coincidental.id).unwrap().status.open(),
13994            "a non-conductor question must not be abandoned just because its \
13995             run id coincides with a task id"
13996        );
13997    }
13998
13999    #[test]
14000    fn a_freshly_started_running_task_is_never_stalled() {
14001        let dir = tempfile::tempdir().unwrap();
14002        let mut t = task();
14003        t.start("run-1".to_owned());
14004        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
14005        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
14006        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
14007    }
14008
14009    #[test]
14010    fn a_long_running_task_with_no_live_daemon_is_stalled() {
14011        let dir = tempfile::tempdir().unwrap();
14012        let mut t = task();
14013        t.start("run-1".to_owned());
14014        t.updated_at = Timestamp::now()
14015            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14016        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
14017        assert_eq!(
14018            stalled_tasks(
14019                &Queue::at(dir.path().join("q")),
14020                dir.path(),
14021                Timestamp::now()
14022            )
14023            .len(),
14024            0,
14025            "the task was never written to this queue"
14026        );
14027    }
14028
14029    #[test]
14030    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
14031        let dir = tempfile::tempdir().unwrap();
14032        let mut t = task();
14033        t.id = "20260903-080340-0167".to_owned();
14034        t.start("20260903-080619-01c2".to_owned());
14035        t.updated_at = Timestamp::now()
14036            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14037
14038        let mut status = Status::new();
14039        status.current = vec![Current {
14040            worker: None,
14041            task: t.id.clone(),
14042            run: "20260903-080619-01c2".to_owned(),
14043        }];
14044        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
14045
14046        assert!(
14047            !is_stalled(&t, dir.path(), Timestamp::now()),
14048            "a live daemon's own heartbeat rules out stalled, however long the task has run"
14049        );
14050    }
14051
14052    /// Rewrite a task's `updated_at` on disk directly, bypassing
14053    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
14054    /// a fixture look like it has genuinely been `running` for a while.
14055    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
14056        let path = queue.path_of(id);
14057        let body = std::fs::read_to_string(&path).unwrap();
14058        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
14059        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
14060        v["updated_at"] = serde_json::Value::String(old.to_string());
14061        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
14062    }
14063
14064    #[test]
14065    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
14066        // The realistic `poll()` ordering, not `is_stalled` in isolation:
14067        // `reclaim_orphaned_running` runs first, on every poll, and settles
14068        // any `running` task whose claim it can actually take. For most
14069        // crashes that is immediate - a dead pid is proof enough for
14070        // `sweep_stale_claims` to drop the lock the same tick, and the very
14071        // next claim attempt succeeds. But a lock whose pid cannot be parsed
14072        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
14073        // `sweep_stale_claims`'s own doc), so the lock - and the claim
14074        // failure behind it - can legitimately outlive many polls. This is
14075        // exactly the gap `stalled_tasks` exists to surface well before that
14076        // six-hour sweep would: reclaim leaves the task `running`, and it
14077        // must still reach the conductor as stalled.
14078        let dir = tempfile::tempdir().unwrap();
14079        let queue = Queue::at(dir.path().join("queue"));
14080        let home = dir.path().join("home");
14081
14082        let mut t = task();
14083        t.id = "20260101-000001-lock".to_owned();
14084        t.start("run-1".to_owned());
14085        queue.put(&mut t).unwrap();
14086        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14087        std::fs::write(
14088            dir.path().join("queue").join(format!("{}.lock", t.id)),
14089            "not a pid",
14090        )
14091        .unwrap();
14092
14093        let now = Timestamp::now();
14094        assert!(
14095            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
14096            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
14097             and reclaim must leave the task alone"
14098        );
14099        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14100
14101        let stalled = stalled_tasks(&queue, &home, now);
14102        assert_eq!(
14103            stalled.len(),
14104            1,
14105            "reclaim's inability to claim it yet must not hide it from the conductor"
14106        );
14107        assert_eq!(stalled[0].id, t.id);
14108    }
14109
14110    #[test]
14111    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
14112        let dir = tempfile::tempdir().unwrap();
14113        crate::run::set_home(dir.path().join("run-home"));
14114        let queue = Queue::at(dir.path().join("queue"));
14115        let home = dir.path().join("home");
14116        let questions = Questions::at(dir.path().join("questions"));
14117
14118        let mut t = task();
14119        t.id = "20260101-000003-dead".to_owned();
14120        t.start("missing-run".to_owned());
14121        queue.put(&mut t).unwrap();
14122        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14123
14124        // This is the real poll ordering: retain the deterministic stalled
14125        // input before a claim proves the owner is gone and reclaims it.
14126        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14127        assert_eq!(
14128            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
14129            [&t.id]
14130        );
14131        assert_eq!(
14132            reclaim_orphaned_running(&queue, 2, &Default::default()),
14133            [t.id.clone()]
14134        );
14135        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14136
14137        // Reclaim drops its guard before conductor decisions are applied, so
14138        // the decision for the captured stalled input has a real write path.
14139        crate::conduct::apply(
14140            &queue,
14141            &questions,
14142            &crate::conduct::Verdict {
14143                decisions: vec![crate::conduct::Decision {
14144                    id: t.id.clone(),
14145                    recovery: Some(crate::conduct::Recovery::Requeue),
14146                    ..crate::conduct::Decision::default()
14147                }],
14148            },
14149        )
14150        .unwrap();
14151        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14152    }
14153
14154    #[test]
14155    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
14156        let dir = tempfile::tempdir().unwrap();
14157        let queue = Queue::at(dir.path().join("queue"));
14158        let home = dir.path().join("home");
14159
14160        let mut fresh = task();
14161        fresh.id = "20260101-000001-aaaa".to_owned();
14162        fresh.start("run-1".to_owned());
14163        queue.put(&mut fresh).unwrap();
14164
14165        let mut old = task();
14166        old.id = "20260101-000002-bbbb".to_owned();
14167        old.start("run-2".to_owned());
14168        queue.put(&mut old).unwrap();
14169        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
14170
14171        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14172        assert_eq!(stalled.len(), 1);
14173        assert_eq!(stalled[0].id, old.id);
14174    }
14175
14176    #[test]
14177    fn queued_and_finished_task_views_partition_by_status() {
14178        let dir = tempfile::tempdir().unwrap();
14179        let queue = Queue::at(dir.path().join("queue"));
14180
14181        let mut queued = task();
14182        queued.id = "20260101-000001-aaaa".to_owned();
14183        queue.put(&mut queued).unwrap();
14184
14185        let mut failed = task();
14186        failed.id = "20260101-000002-bbbb".to_owned();
14187        failed.start("run-1".to_owned());
14188        failed.fail("gate red", 5);
14189        queue.put(&mut failed).unwrap();
14190
14191        let mut held = task();
14192        held.id = "20260101-000003-cccc".to_owned();
14193        held.hold_machine(None);
14194        queue.put(&mut held).unwrap();
14195
14196        let mut running = task();
14197        running.id = "20260101-000004-dddd".to_owned();
14198        running.start("run-2".to_owned());
14199        queue.put(&mut running).unwrap();
14200
14201        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
14202        assert_eq!(queued_ids, [queued.id.clone()]);
14203
14204        let mut finished_ids: Vec<String> =
14205            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
14206        finished_ids.sort_unstable();
14207        let mut want = vec![failed.id.clone(), held.id.clone()];
14208        want.sort_unstable();
14209        assert_eq!(finished_ids, want);
14210    }
14211
14212    #[test]
14213    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
14214        for short in [false, true] {
14215            let dir = tempfile::tempdir().unwrap();
14216            let queue = Queue::at(dir.path().join("queue"));
14217            let questions = ask::Questions::at(dir.path().join("questions"));
14218            let mut running = task();
14219            running.id = "20261013-192213-feb2".into();
14220            running.start("existing-run".into());
14221            queue.put(&mut running).unwrap();
14222            let mut middle = task();
14223            middle.id = "20261013-193611-ca5b".into();
14224            middle.block(
14225                vec![if short {
14226                    "feb2".into()
14227                } else {
14228                    running.id.clone()
14229                }],
14230                None,
14231            );
14232            queue.put(&mut middle).unwrap();
14233            let mut waiting = task();
14234            waiting.id = "20261013-202849-ee37".into();
14235            waiting.block(
14236                vec![if short {
14237                    "ca5b".into()
14238                } else {
14239                    middle.id.clone()
14240                }],
14241                Some("wait for implementation".into()),
14242            );
14243            queue.put(&mut waiting).unwrap();
14244            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
14245            let inv = crate::blockers::Inventory::load(&queue, &questions);
14246            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
14247            assert!(inv.stuck().is_empty());
14248            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14249            assert!(report.quarantined.is_empty());
14250            assert!(report.asked.is_empty());
14251            resolve_blockers(&queue, &questions);
14252            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14253            assert!(questions.list().is_empty());
14254            // Finishing the transitive prerequisite alone does not satisfy
14255            // the task's direct dependency.
14256            running.succeed(CompletionContext::new(
14257                CompletionActor::DaemonSettle,
14258                None,
14259                dir.path(),
14260                &running,
14261            ));
14262            queue.put(&mut running).unwrap();
14263            resolve_blockers(&queue, &questions);
14264            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
14265            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14266            middle = queue.get(&middle.id).unwrap();
14267            middle.succeed(CompletionContext::new(
14268                CompletionActor::DaemonSettle,
14269                None,
14270                dir.path(),
14271                &middle,
14272            ));
14273            queue.put(&mut middle).unwrap();
14274            resolve_blockers(&queue, &questions);
14275            let after = queue.get(&waiting.id).unwrap();
14276            assert_eq!(after.status, TaskStatus::Queued);
14277            assert!(after.blocked_by.is_empty());
14278            assert_eq!(after.instruction, waiting.instruction);
14279        }
14280    }
14281
14282    #[test]
14283    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
14284        for future_schema in [false, true] {
14285            let name = "20261013-193611-ca5b";
14286            let mut future = task();
14287            future.id = name.into();
14288            future.schema = crate::queue::SCHEMA + 1;
14289            let contents = if future_schema {
14290                serde_json::to_string(&future).unwrap()
14291            } else {
14292                "corrupt".into()
14293            };
14294            let dir = tempfile::tempdir().unwrap();
14295            let queue = Queue::at(dir.path().join("queue"));
14296            let questions = ask::Questions::at(dir.path().join("questions"));
14297            let mut waiting = task();
14298            waiting.id = "20261013-202849-ee37".into();
14299            waiting.block(vec!["ca5b".into()], None);
14300            queue.put(&mut waiting).unwrap();
14301            std::fs::write(queue.path_of(name), contents).unwrap();
14302            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
14303            assert!(
14304                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
14305            );
14306            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14307            assert!(report.asked.is_empty());
14308            resolve_blockers(&queue, &questions);
14309            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14310            assert!(questions.list().is_empty());
14311        }
14312        let dir = tempfile::tempdir().unwrap();
14313        let queue = Queue::at(dir.path().join("queue"));
14314        let questions = ask::Questions::at(dir.path().join("questions"));
14315        let mut waiting = task();
14316        waiting.id = "20261013-202849-ee37".into();
14317        waiting.block(vec!["ca5b".into()], None);
14318        queue.put(&mut waiting).unwrap();
14319        let mut done = task();
14320        done.id = "20261013-193611-ca5b".into();
14321        done.succeed(CompletionContext::new(
14322            CompletionActor::Cli,
14323            None,
14324            dir.path(),
14325            &done,
14326        ));
14327        queue.put(&mut done).unwrap();
14328        // An unreadable second match must not disappear from uniqueness
14329        // checks just because Queue::list skips it.
14330        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
14331        assert!(queue.get("ca5b").is_err());
14332        assert_eq!(
14333            crate::queue::dependency(&queue, &questions, "ca5b"),
14334            crate::queue::Dependency::Ambiguous
14335        );
14336        resolve_blockers(&queue, &questions);
14337        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14338        assert!(report.asked.is_empty());
14339        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14340        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
14341    }
14342
14343    #[test]
14344    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
14345        for held in [false, true] {
14346            for question in [false, true] {
14347                for reference in ["ca5b", "20261013-193611-ca5b"] {
14348                    let dir = tempfile::tempdir().unwrap();
14349                    let queue = Queue::at(dir.path().join("queue"));
14350                    let questions = ask::Questions::at(dir.path().join("questions"));
14351                    let mut prerequisite = task();
14352                    prerequisite.id = "20261013-193611-ca5b".into();
14353                    prerequisite.start("existing-run".into());
14354                    queue.put(&mut prerequisite).unwrap();
14355                    let mut waiting = task();
14356                    waiting.id = "20261013-202849-ee37".into();
14357                    if held {
14358                        waiting.hold_machine(Some("waiting for separate consent".into()));
14359                    }
14360                    queue.put(&mut waiting).unwrap();
14361                    let reason = "Deleting saved data requires separate owner consent";
14362                    crate::conduct::apply(
14363                        &queue,
14364                        &questions,
14365                        &crate::conduct::Verdict {
14366                            decisions: vec![crate::conduct::Decision {
14367                                id: waiting.id.clone(),
14368                                blocked_by: vec![reference.into()],
14369                                question: question.then(|| "May the saved data be deleted?".into()),
14370                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
14371                                reason: Some(reason.into()),
14372                                ..crate::conduct::Decision::default()
14373                            }],
14374                        },
14375                    )
14376                    .unwrap();
14377                    let before = queue.get(&waiting.id).unwrap();
14378                    if question {
14379                        assert_eq!(before.status, TaskStatus::Blocked);
14380                        let q = questions.get(&before.blocked_by[0]).unwrap();
14381                        assert_eq!(q.summary, "May the saved data be deleted?");
14382                        assert!(q.status.open());
14383                    } else {
14384                        assert_eq!(before.status, TaskStatus::Held);
14385                        let recorded_reason = before.hold_reason.as_deref().unwrap();
14386                        assert!(recorded_reason.starts_with(reason));
14387                        if held {
14388                            assert!(recorded_reason.contains("waiting for separate consent"));
14389                        }
14390                    }
14391                    prerequisite.succeed(CompletionContext::new(
14392                        CompletionActor::DaemonSettle,
14393                        None,
14394                        dir.path(),
14395                        &prerequisite,
14396                    ));
14397                    queue.put(&mut prerequisite).unwrap();
14398                    resolve_blockers(&queue, &questions);
14399                    let after = queue.get(&waiting.id).unwrap();
14400                    assert_eq!(after.status, before.status);
14401                    assert_eq!(after.blocked_by, before.blocked_by);
14402                    assert_eq!(after.hold_reason, before.hold_reason);
14403                    assert_eq!(after.instruction, waiting.instruction);
14404                    if question {
14405                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
14406                    }
14407                    assert!(
14408                        queue.next_runnable().is_none(),
14409                        "dependency completion is not consent"
14410                    );
14411                }
14412            }
14413        }
14414    }
14415
14416    #[test]
14417    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
14418        let dir = tempfile::tempdir().unwrap();
14419        let queue = Queue::at(dir.path().join("queue"));
14420        let questions = ask::Questions::at(dir.path().join("questions"));
14421
14422        let mut dep = task();
14423        dep.id = "20260101-000001-dep0".to_owned();
14424        dep.succeed(CompletionContext::new(
14425            CompletionActor::DaemonSettle,
14426            None,
14427            dir.path(),
14428            &dep,
14429        ));
14430        queue.put(&mut dep).unwrap();
14431
14432        let mut still_going = task();
14433        still_going.id = "20260101-000002-dep1".to_owned();
14434        queue.put(&mut still_going).unwrap();
14435
14436        let mut blocked = task();
14437        blocked.id = "20260101-000003-main".to_owned();
14438        blocked.block(
14439            vec![dep.id.clone(), still_going.id.clone()],
14440            Some("waits on both".to_owned()),
14441        );
14442        queue.put(&mut blocked).unwrap();
14443
14444        resolve_blockers(&queue, &questions);
14445
14446        let after = queue.get(&blocked.id).unwrap();
14447        assert_eq!(
14448            after.status,
14449            TaskStatus::Blocked,
14450            "one dependency is still outstanding"
14451        );
14452        assert_eq!(after.blocked_by, [still_going.id.clone()]);
14453    }
14454
14455    #[test]
14456    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
14457        let dir = tempfile::tempdir().unwrap();
14458        let queue = Queue::at(dir.path().join("queue"));
14459        let questions = ask::Questions::at(dir.path().join("questions"));
14460
14461        let mut q = crate::ask::Question::new(
14462            "20260101-000001-main".to_owned(),
14463            crate::conduct::NODE.to_owned(),
14464            "conduct".to_owned(),
14465            "Which backend?".to_owned(),
14466            String::new(),
14467            Vec::new(),
14468        );
14469        questions.put(&mut q).unwrap();
14470        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
14471            .unwrap();
14472        questions.put(&mut q).unwrap();
14473
14474        let mut blocked = task();
14475        blocked.id = "20260101-000001-main".to_owned();
14476        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
14477        queue.put(&mut blocked).unwrap();
14478
14479        resolve_blockers(&queue, &questions);
14480
14481        let after = queue.get(&blocked.id).unwrap();
14482        assert_eq!(
14483            after.status,
14484            TaskStatus::Queued,
14485            "the only blocker resolved"
14486        );
14487        assert_eq!(after.answers.len(), 1);
14488        assert_eq!(after.answers[0].question, "Which backend?");
14489        assert_eq!(after.answers[0].answer, "SQLite");
14490
14491        // And the run this task starts next is told about it.
14492        let instruction = instruction_for(&after);
14493        assert!(instruction.contains("Which backend?"));
14494        assert!(instruction.contains("SQLite"));
14495    }
14496
14497    #[test]
14498    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
14499        let dir = tempfile::tempdir().unwrap();
14500        let queue = Queue::at(dir.path().join("queue"));
14501        let questions = ask::Questions::at(dir.path().join("questions"));
14502
14503        let mut q = crate::ask::Question::new(
14504            "20260101-000001-main".to_owned(),
14505            crate::conduct::NODE.to_owned(),
14506            "conduct".to_owned(),
14507            "Is the setup done?".to_owned(),
14508            String::new(),
14509            Vec::new(),
14510        );
14511        q.abandon("no answer within 60s of asking");
14512        questions.put(&mut q).unwrap();
14513
14514        let mut blocked = task();
14515        blocked.id = "20260101-000001-main".to_owned();
14516        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
14517        queue.put(&mut blocked).unwrap();
14518
14519        resolve_blockers(&queue, &questions);
14520
14521        let after = queue.get(&blocked.id).unwrap();
14522        assert_eq!(
14523            after.status,
14524            TaskStatus::Held,
14525            "never left blocked on nothing"
14526        );
14527        assert!(!after.operator_held(), "a machine hold, for triage");
14528        assert!(
14529            after
14530                .hold_reason
14531                .as_deref()
14532                .unwrap_or_default()
14533                .contains("went unanswered")
14534        );
14535    }
14536
14537    #[test]
14538    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
14539        // Reproduces the reported bug (task 3958): a task held out of
14540        // attempts, blocked on a `crate::conduct` follow-up question, must
14541        // come back `held` once that question is answered - never `queued`,
14542        // whatever the answer said - or it silently re-enters the
14543        // competition queue with its attempts already exhausted.
14544        let dir = tempfile::tempdir().unwrap();
14545        let queue = Queue::at(dir.path().join("queue"));
14546        let questions = ask::Questions::at(dir.path().join("questions"));
14547
14548        let mut q = crate::ask::Question::new(
14549            "20260101-000001-main".to_owned(),
14550            crate::conduct::NODE.to_owned(),
14551            "conduct".to_owned(),
14552            "How should this be handled?".to_owned(),
14553            String::new(),
14554            Vec::new(),
14555        );
14556        questions.put(&mut q).unwrap();
14557        q.answer(crate::ask::Answer::Text(
14558            "leave it held, a human will look at it later".to_owned(),
14559        ))
14560        .unwrap();
14561        questions.put(&mut q).unwrap();
14562
14563        let mut held = task();
14564        held.id = "20260101-000001-main".to_owned();
14565        held.hold_machine(Some("out of attempts".to_owned()));
14566        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
14567        queue.put(&mut held).unwrap();
14568
14569        resolve_blockers(&queue, &questions);
14570
14571        let after = queue.get(&held.id).unwrap();
14572        assert_eq!(after.status, TaskStatus::Held);
14573        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
14574        assert_eq!(
14575            after.answers[0].answer,
14576            "leave it held, a human will look at it later"
14577        );
14578    }
14579
14580    #[test]
14581    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
14582        let dir = tempfile::tempdir().unwrap();
14583        let queue = Queue::at(dir.path().join("queue"));
14584        let questions = ask::Questions::at(dir.path().join("questions"));
14585        let mut dep = task();
14586        dep.id = "20260101-000001-gone".to_owned();
14587        queue.put(&mut dep).unwrap();
14588        let mut blocked = task();
14589        blocked.id = "20260101-000003-main".to_owned();
14590        blocked.block(vec![dep.id.clone()], None);
14591        queue.put(&mut blocked).unwrap();
14592
14593        // Claimed, so `remove` cannot rewrite it and the resolver must.
14594        let claim = queue.claim(&blocked.id).unwrap();
14595        queue.remove(&dep.id, false, &questions).unwrap();
14596        drop(claim);
14597        resolve_blockers(&queue, &questions);
14598
14599        let after = queue.get(&blocked.id).unwrap();
14600        assert_eq!(after.status, TaskStatus::Queued);
14601        assert!(after.blocked_by.is_empty());
14602    }
14603
14604    #[test]
14605    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
14606        // Reproduces the reported bug: a task blocked on a task id that was
14607        // removed (`magi task rm`, or deleted by hand) can never see that id
14608        // reach `Done`, so the ordinary per-id loop has nothing to notice and
14609        // would otherwise leave the task `blocked` forever with no way for an
14610        // operator to find out why.
14611        let dir = tempfile::tempdir().unwrap();
14612        let queue = Queue::at(dir.path().join("queue"));
14613        let questions = ask::Questions::at(dir.path().join("questions"));
14614
14615        let mut still_going = task();
14616        still_going.id = "20260101-000002-dep1".to_owned();
14617        queue.put(&mut still_going).unwrap();
14618
14619        let mut blocked = task();
14620        blocked.id = "20260101-000003-main".to_owned();
14621        blocked.block(
14622            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
14623            Some("waits on both".to_owned()),
14624        );
14625        queue.put(&mut blocked).unwrap();
14626
14627        resolve_blockers(&queue, &questions);
14628
14629        let after = queue.get(&blocked.id).unwrap();
14630        assert_eq!(
14631            after.status,
14632            TaskStatus::Held,
14633            "a missing dependency must not leave the task blocked forever"
14634        );
14635        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
14636        assert!(after.blocked_by.is_empty());
14637        let reason = after.hold_reason.as_deref().unwrap_or_default();
14638        assert!(
14639            reason.contains("20260101-000001-gone"),
14640            "the missing id must be named so an operator can tell what happened: {reason}"
14641        );
14642        assert!(
14643            reason.contains(&still_going.id),
14644            "the still-valid dependency must not silently vanish from the record: {reason}"
14645        );
14646    }
14647
14648    #[test]
14649    fn instruction_for_is_unchanged_without_any_answers() {
14650        let t = task();
14651        assert_eq!(instruction_for(&t), t.instruction);
14652    }
14653
14654    #[test]
14655    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
14656        let dir = tempfile::tempdir().unwrap();
14657        let q = Queue::at(dir.path().join("queue"));
14658        let src = dir.path().join("shot.png");
14659        std::fs::write(&src, "x").unwrap();
14660        let mut t = task();
14661        q.attach(&mut t, &[src]).unwrap();
14662        let paths = task_attachments(&q, &t).unwrap();
14663        assert_eq!(paths.len(), 1);
14664        assert!(paths[0].is_absolute() && paths[0].is_file());
14665        std::fs::remove_file(&paths[0]).unwrap();
14666        let err = task_attachments(&q, &t).unwrap_err().to_string();
14667        assert!(err.contains("shot.png"), "{err}");
14668    }
14669
14670    #[tokio::test]
14671    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
14672        let dir = tempfile::tempdir().unwrap();
14673        let queue_path = dir.path().join("queue");
14674        let queue = Queue::at(queue_path.clone());
14675        let mut t = task();
14676        t.source = Source::Agent {
14677            run: "originating-chat".into(),
14678            node: crate::queue::CHAT_NODE.into(),
14679        };
14680        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
14681            stage: "config-fetch",
14682            target: "origin/main".into(),
14683        });
14684        record_config_failure(&mut t, &fetch);
14685        t.hold_machine(Some(format!("{fetch:#}")));
14686        let fetch_key = t.chat_notice_due().unwrap();
14687        t.chat_notices.push(fetch_key.clone());
14688        queue.put(&mut t).unwrap();
14689
14690        let queue = Queue::at(queue_path);
14691        let mut t = queue.get(&t.id).unwrap();
14692        let a = dir.path().join("a.toml");
14693        let b = dir.path().join("b.toml");
14694        for (path, text, new_cause) in [
14695            (&a, "[graph", true),
14696            (&a, "[verify", false),
14697            (&a, "[graph]\nimplementers = 'invalid-type'", true),
14698            (&b, "[graph]\nimplementers = 'invalid-type'", true),
14699        ] {
14700            t.release_operator("test", None);
14701            std::fs::write(path, text).unwrap();
14702            let error = Config::discover_fetched(dir.path(), Some(path))
14703                .await
14704                .unwrap_err();
14705            record_config_failure(&mut t, &error);
14706            t.hold_machine(Some(format!("{error:#}")));
14707            let due = t.chat_notice_due();
14708            assert_eq!(due.is_some(), new_cause, "{error:#}");
14709            if let Some(key) = due {
14710                assert_ne!(key, fetch_key);
14711                t.chat_notices.push(key);
14712            }
14713        }
14714        t.succeed(CompletionContext::new(
14715            CompletionActor::DaemonSettle,
14716            None,
14717            dir.path(),
14718            &t,
14719        ));
14720        assert_eq!(
14721            t.chat_notice_due(),
14722            Some(format!(
14723                "done:{}",
14724                t.completion_history.last().unwrap().occurrence
14725            ))
14726        );
14727    }
14728
14729    #[test]
14730    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
14731        let dir = tempfile::tempdir().unwrap();
14732        let queue_path = dir.path().join("queue");
14733        let queue = Queue::at(queue_path.clone());
14734        let mut t = task();
14735        t.source = crate::queue::Source::Agent {
14736            run: "originating-chat".into(),
14737            node: crate::queue::CHAT_NODE.into(),
14738        };
14739        let a = dir.path().join("a.png");
14740        let b = dir.path().join("b.png");
14741        std::fs::write(&a, "a").unwrap();
14742        std::fs::write(&b, "b").unwrap();
14743        queue.attach(&mut t, &[a, b]).unwrap();
14744        let paths = task_attachments(&queue, &t).unwrap();
14745        for path in &paths {
14746            std::fs::remove_file(path).unwrap();
14747        }
14748        let missing = task_attachments(&queue, &t).unwrap_err();
14749        t.attempts += 1;
14750        let reason = missing.to_string();
14751        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14752        let first = t.chat_notice_due().expect("first attachment notice");
14753        t.chat_notices.push(first.clone());
14754        queue.put(&mut t).unwrap();
14755
14756        let queue = Queue::at(queue_path.clone());
14757        let mut t = queue.get(&t.id).unwrap();
14758        assert!(t.chat_notice_due().is_none(), "restart does not replay");
14759        t.release_operator("test", None);
14760        t.attempts += 1;
14761        let missing = task_attachments(&queue, &t).unwrap_err();
14762        t.fail_startup_target(
14763            "startup-attachments",
14764            missing.name,
14765            "same missing attachment with regenerated wording",
14766            1,
14767        );
14768        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
14769
14770        std::fs::write(&paths[0], "restored").unwrap();
14771        t.release_operator("test", None);
14772        t.attempts += 1;
14773        let missing = task_attachments(&queue, &t).unwrap_err();
14774        let reason = missing.to_string();
14775        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14776        let second = t
14777            .chat_notice_due()
14778            .expect("different attachment must notify");
14779        assert_ne!(first, second);
14780        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
14781    }
14782
14783    #[test]
14784    fn resumed_instruction_is_unchanged_without_any_answers() {
14785        let t = task();
14786        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
14787    }
14788
14789    #[test]
14790    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
14791        let mut t = task();
14792        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14793        // The run's own instruction on disk predates the answer: it is the
14794        // plain original text `Runner::start` saved before the operator was
14795        // ever asked anything.
14796        let old = t.instruction.clone();
14797
14798        let refreshed = resumed_instruction(&old, &t);
14799        assert!(refreshed.starts_with(&old), "the original text is kept");
14800        assert!(refreshed.contains("Which backend?"));
14801        assert!(refreshed.contains("SQLite"));
14802    }
14803
14804    #[test]
14805    fn resumed_instruction_keeps_an_original_answers_heading() {
14806        let mut t = task();
14807        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
14808        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14809
14810        let refreshed = resumed_instruction(&t.instruction, &t);
14811
14812        assert!(
14813            refreshed.starts_with(&t.instruction),
14814            "an answers heading in the original instruction is not the appended block"
14815        );
14816        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
14817        assert!(refreshed.contains("Which backend?"));
14818        assert!(refreshed.contains("SQLite"));
14819
14820        let repeated = resumed_instruction(&refreshed, &t);
14821        assert_eq!(
14822            repeated, refreshed,
14823            "only the final appended block is refreshed"
14824        );
14825    }
14826
14827    #[test]
14828    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
14829        let mut t = task();
14830        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14831
14832        // A first resume appends the block; a second resume of the same run,
14833        // with no new answer in between, must reproduce exactly the same
14834        // text rather than appending the block a second time.
14835        let once = resumed_instruction(&t.instruction, &t);
14836        let twice = resumed_instruction(&once, &t);
14837        assert_eq!(once, twice);
14838        assert_eq!(once.matches("Which backend?").count(), 1);
14839
14840        // A later answer replaces the block wholesale rather than growing it.
14841        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
14842        let refreshed = resumed_instruction(&once, &t);
14843        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
14844        assert!(refreshed.contains("Which backend?"));
14845        assert!(refreshed.contains("Which cache?"));
14846    }
14847
14848    #[test]
14849    fn prepare_instruction_covers_all_three_starters() {
14850        let mut t = task();
14851        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14852
14853        // Start: a fresh run gets the task text plus every answer so far —
14854        // exactly `instruction_for`.
14855        assert_eq!(
14856            prepare_instruction(&Starter::Start, None, &t),
14857            Some(instruction_for(&t))
14858        );
14859
14860        // Resume: the run's prior instruction is refreshed with the answer,
14861        // not discarded and not left stale.
14862        let old = t.instruction.clone();
14863        assert_eq!(
14864            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
14865            Some(resumed_instruction(&old, &t))
14866        );
14867
14868        // Review: a review-only pass builds its own instruction from the
14869        // branch's history in `crate::graph`, with no task statement at all -
14870        // this boundary must leave it alone.
14871        assert_eq!(
14872            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
14873            None
14874        );
14875    }
14876
14877    #[test]
14878    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
14879        assert_eq!(
14880            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
14881            Starter::Review("magi/eba2/A".to_owned())
14882        );
14883    }
14884
14885    #[test]
14886    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
14887        assert_eq!(
14888            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
14889            Starter::Start,
14890            "a vanished review branch must not fall back to resuming the old run either"
14891        );
14892    }
14893
14894    #[test]
14895    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
14896        let mut t = task();
14897        t.start("old-run".to_owned());
14898        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
14899        t.release();
14900        let branch = t.review_branch.take();
14901        assert_eq!(
14902            choose_starter(branch.as_deref(), true, Some("old-run")),
14903            Starter::Review("magi/eba2/A".to_owned()),
14904            "a review wins over resuming the old run"
14905        );
14906    }
14907
14908    #[test]
14909    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
14910        assert_eq!(
14911            choose_starter(None, false, Some("some-run")),
14912            Starter::Resume("some-run".to_owned())
14913        );
14914        assert_eq!(choose_starter(None, false, None), Starter::Start);
14915    }
14916
14917    #[test]
14918    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
14919        let mut released = task();
14920        released.start("stalled-run".to_owned());
14921        released.requeue();
14922        let unfinished = (!released.fresh_start)
14923            .then(|| Some("stalled-run".to_owned()))
14924            .flatten();
14925        assert_eq!(
14926            choose_starter(None, false, unfinished.as_deref()),
14927            Starter::Start,
14928            "release keeps run history but must not resume it"
14929        );
14930        assert_eq!(released.runs, ["stalled-run"]);
14931    }
14932
14933    #[test]
14934    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
14935        let dir = tempfile::tempdir().unwrap();
14936        let queue = Queue::at(dir.path().join("queue"));
14937        let mut state = run_state(RunStatus::Blocked);
14938        state.merge_decision = Some(crate::merge_decision::Decision {
14939            question: "hold-inquiry".into(),
14940            target: crate::merge_decision::Target {
14941                pr: "https://example.test/pull/1".into(),
14942                head: "reviewed-head".into(),
14943                language: "en".into(),
14944            },
14945            choice: land::HOLD.into(),
14946            closed: false,
14947            replacement_run: None,
14948            replacement_pr: None,
14949        });
14950        let mut t = task();
14951        t.start(state.id.clone());
14952        settle_and_diagnose(
14953            &mut t,
14954            Verdict {
14955                status: RunStatus::Blocked,
14956                left_pr: true,
14957                quota_hit: false,
14958                parked: false,
14959                no_viable_candidates: false,
14960            },
14961            "held",
14962            2,
14963            &state,
14964        );
14965        queue.put(&mut t).unwrap();
14966        t.release_operator("chat", None);
14967        t.edit("revised".into(), "revised instruction".into())
14968            .unwrap();
14969        queue.put(&mut t).unwrap();
14970        drop(state);
14971        assert_eq!(
14972            queue
14973                .get(&t.id)
14974                .unwrap()
14975                .decision_effects
14976                .get("hold-inquiry"),
14977            Some(&format!("decision: {}", land::HOLD))
14978        );
14979    }
14980
14981    fn stopped_public_run(status: RunStatus) -> RunState {
14982        let mut state = run_state(status);
14983        state.driver_exited = true;
14984        state.config.graph.land = true;
14985        state.config.graph.review_rounds = 1;
14986        state.reviews = vec![review_round(1)];
14987        state.merge = Some(crate::run::MergeOutcome {
14988            mode: MergeMode::Pr,
14989            ok: false,
14990            detail: "landing stopped".into(),
14991            empty: false,
14992        });
14993        state.pr = Some(crate::run::PrRecord {
14994            url: "https://example.test/pull/1".into(),
14995            number: 1,
14996            state: "open".into(),
14997            checks: "red".into(),
14998            round: 1,
14999            rounds: 1,
15000            red_at_merge: Vec::new(),
15001        });
15002        state
15003    }
15004
15005    #[test]
15006    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
15007        for status in [RunStatus::Blocked, RunStatus::Gating] {
15008            let home = tempfile::tempdir().unwrap();
15009            let mut state = stopped_public_run(status);
15010            state.save_under(home.path()).unwrap();
15011            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
15012            assert!(!exhausted_review_budget(&state));
15013            let mut task = held_task_with(&state.id);
15014            task.release();
15015            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15016            assert_eq!(
15017                choose_starter(None, false, unfinished.as_deref()),
15018                Starter::Resume(state.id.clone())
15019            );
15020            let question = action_question(&state.id, resume_action(&state.id));
15021            assert_eq!(
15022                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15023                    state.clone()
15024                )),
15025                ActionDecision::Resume(state.id.clone())
15026            );
15027            // The control-plane command uses this same preflight before pinning.
15028            assert_eq!(
15029                crate::resume::validate(home.path(), &state.id).unwrap().id,
15030                state.id
15031            );
15032            let queue = Queue::at(home.path().join("queue"));
15033            let mut controlled = Task::new(
15034                "resume land".into(),
15035                state.instruction.clone(),
15036                state.repo.clone(),
15037                Source::Agent {
15038                    run: "talk".into(),
15039                    node: crate::queue::CHAT_NODE.into(),
15040                },
15041            );
15042            controlled.runs.push(state.id.clone());
15043            controlled.hold_machine(Some("land stopped".into()));
15044            queue.put(&mut controlled).unwrap();
15045            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15046            assert_eq!(resumed.status, TaskStatus::Queued);
15047            assert_eq!(
15048                resumed.resume_override.unwrap().pinned_run,
15049                Some(state.id.clone())
15050            );
15051            assert_eq!(resumed.attempts, 0);
15052        }
15053    }
15054
15055    #[test]
15056    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
15057        for review_rounds in [0, 1] {
15058            let home = tempfile::tempdir().unwrap();
15059            let mut state = run_state(RunStatus::Blocked);
15060            state.config.graph.review_rounds = review_rounds;
15061            if review_rounds > 0 {
15062                let mut review = review_round(1);
15063                review.clean = true;
15064                state.reviews = vec![review];
15065            }
15066            state.gate_ran = true;
15067            state.gate = vec![crate::run::CommandOutcome {
15068                command: "verify".into(),
15069                code: Some(1),
15070                output_tail: "gate failed after repair budget exhausted".into(),
15071                duration_ms: 0,
15072                resource_blocked: false,
15073                ..Default::default()
15074            }];
15075            state.save_under(home.path()).unwrap();
15076            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15077            assert!(exhausted_review_budget(&state));
15078            let mut task = held_task_with(&state.id);
15079            task.release();
15080            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
15081            let question = action_question(&state.id, resume_action(&state.id));
15082            assert_ne!(
15083                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15084                    state.clone()
15085                )),
15086                ActionDecision::Resume(state.id.clone())
15087            );
15088            let error = crate::resume::validate(home.path(), &state.id)
15089                .unwrap_err()
15090                .to_string();
15091            assert!(!error.contains("review budget exhausted"), "{error}");
15092            assert!(
15093                error.contains(if review_rounds == 0 {
15094                    "review is disabled"
15095                } else {
15096                    "gate already ran"
15097                }),
15098                "{error}"
15099            );
15100
15101            // An unexecuted gate still has work to do with or without reviews.
15102            state.gate_ran = false;
15103            state.gate.clear();
15104            assert!(!exhausted_review_budget(&state));
15105            assert_eq!(
15106                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
15107                Some(state.id)
15108            );
15109        }
15110    }
15111
15112    #[test]
15113    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
15114        let home = tempfile::tempdir().unwrap();
15115        let mut state = run_state(RunStatus::Blocked);
15116        state.config.graph.review_rounds = 1;
15117        let mut unresolved = review_round(1);
15118        unresolved.blocking = 1;
15119        unresolved.e2e.push(crate::run::CommandOutcome {
15120            command: "verify".into(),
15121            code: Some(1),
15122            output_tail: "previous verification failed".into(),
15123            duration_ms: 0,
15124            resource_blocked: false,
15125            artifact: None,
15126            failure_evidence: None,
15127            rerun_comparison: None,
15128        });
15129        state.reviews.push(unresolved);
15130        state.base_sync = Some(crate::run::BaseSync {
15131            tip: "base".into(),
15132            behind: 1,
15133            attempts: 0,
15134            conflict: None,
15135            already_in: None,
15136        });
15137        state.reserve_base_operation("winner", "base");
15138        state.resource_block = Some(crate::run::ResourceBlock {
15139            cause: crate::run::ResourceBlockCause::Other,
15140            node: "rebase".into(),
15141            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
15142            detail: "recording exec failed".into(),
15143            at: jiff::Timestamp::now(),
15144        });
15145        state.save_under(home.path()).unwrap();
15146        assert_eq!(
15147            crate::resume::validate(home.path(), &state.id).unwrap().id,
15148            state.id
15149        );
15150        assert_eq!(
15151            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
15152            crate::repair_budget::legacy::Class::SequencerInfrastructure
15153        );
15154        state.finish_base_operation(None);
15155        state.save_under(home.path()).unwrap();
15156        assert!(crate::resume::validate(home.path(), &state.id).is_err());
15157    }
15158
15159    #[test]
15160    fn resource_blocked_verification_resumes_the_same_run() {
15161        for (kind, stage) in [
15162            ("cache", "clean"),
15163            ("coordination", "clean"),
15164            ("cache", "review-e2e"),
15165            ("coordination", "no-reviews"),
15166            ("coordination", "handoff"),
15167        ] {
15168            let home = tempfile::tempdir().unwrap();
15169            let mut state = run_state(RunStatus::Blocked);
15170            state.config.graph.review_rounds = 1;
15171            let mut review = review_round(1);
15172            review.clean = true;
15173            state.reviews = vec![review];
15174            if stage == "review-e2e" {
15175                let review = &mut state.reviews[0];
15176                review.clean = false;
15177                review.blocking = 1;
15178                review.e2e = vec![crate::run::CommandOutcome {
15179                    command: "verify".into(),
15180                    code: None,
15181                    output_tail: "resource wait expired".into(),
15182                    duration_ms: 0,
15183                    resource_blocked: true,
15184                    ..Default::default()
15185                }];
15186            } else if stage == "no-reviews" {
15187                state.config.graph.review_rounds = 0;
15188                state.reviews.clear();
15189            } else if stage == "handoff" {
15190                // A completed final verification can hand off to the gate
15191                // even when the review still carries contested findings.
15192                let review = &mut state.reviews[0];
15193                review.clean = false;
15194                review.blocking = 1;
15195                review.e2e = vec![crate::run::CommandOutcome {
15196                    command: "verify".into(),
15197                    code: Some(0),
15198                    output_tail: String::new(),
15199                    duration_ms: 0,
15200                    resource_blocked: false,
15201                    ..Default::default()
15202                }];
15203            }
15204            state.gate_ran = false;
15205            state.resource_block = Some(crate::run::ResourceBlock {
15206                cause: crate::run::ResourceBlockCause::Other,
15207                node: if stage == "review-e2e" {
15208                    "review"
15209                } else {
15210                    "gate"
15211                }
15212                .into(),
15213                kind: kind.into(),
15214                detail: "resource wait expired".into(),
15215                at: jiff::Timestamp::now(),
15216            });
15217            state.save_under(home.path()).unwrap();
15218            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15219            assert!(!exhausted_review_budget(&state));
15220            let mut task = held_task_with(&state.id);
15221            task.release();
15222            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15223            assert_eq!(
15224                choose_starter(None, false, unfinished.as_deref()),
15225                Starter::Resume(state.id.clone())
15226            );
15227            let question = action_question(&state.id, resume_action(&state.id));
15228            assert_eq!(
15229                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15230                    state.clone()
15231                )),
15232                ActionDecision::Resume(state.id.clone())
15233            );
15234            assert_eq!(
15235                crate::resume::validate(home.path(), &state.id).unwrap().id,
15236                state.id
15237            );
15238            let queue = Queue::at(home.path().join("queue"));
15239            let mut controlled = Task::new(
15240                "resume verification".into(),
15241                state.instruction.clone(),
15242                state.repo.clone(),
15243                Source::Agent {
15244                    run: "talk".into(),
15245                    node: crate::queue::CHAT_NODE.into(),
15246                },
15247            );
15248            controlled.runs.push(state.id.clone());
15249            controlled.hold_machine(Some("verification resource unavailable".into()));
15250            queue.put(&mut controlled).unwrap();
15251            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15252            assert_eq!(resumed.status, TaskStatus::Queued);
15253            assert_eq!(
15254                resumed.resume_override.unwrap().pinned_run,
15255                Some(state.id.clone())
15256            );
15257            assert_eq!(resumed.attempts, 0);
15258
15259            // A genuinely unresolved final review still exhausts the budget.
15260            state.config.graph.review_rounds = 1;
15261            let mut unresolved = review_round(1);
15262            unresolved.blocking = 1;
15263            state.reviews = vec![unresolved];
15264            state.resource_block = None;
15265            state.save_under(home.path()).unwrap();
15266            assert!(exhausted_review_budget(&state));
15267            assert!(crate::resume::validate(home.path(), &state.id).is_err());
15268        }
15269    }
15270
15271    #[tokio::test]
15272    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
15273        if !crate::standalone_test(
15274            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
15275        ) {
15276            return;
15277        }
15278        let home = tempfile::tempdir().unwrap();
15279        let mut owner = stopped_public_run(RunStatus::Blocked);
15280        owner.save_under(home.path()).unwrap();
15281        let history = vec![owner.id.clone()];
15282        let repo = owner.repo.clone();
15283        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
15284        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
15285        let initial =
15286            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
15287        assert!(
15288            initial.is_pending(),
15289            "a busy record must not hold or resume the task"
15290        );
15291        owner.retired_to = Some("20260101-000001-bbbb".into());
15292        owner.save_under(home.path()).unwrap();
15293        drop(lock);
15294        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
15295            .await
15296            .expect("ownership lock released")
15297            .expect("read settled owner");
15298        assert!(
15299            result.is_none(),
15300            "the retired owner must not be resumed from a stale read"
15301        );
15302    }
15303
15304    #[tokio::test]
15305    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
15306        if !crate::standalone_test(
15307            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
15308        ) {
15309            return;
15310        }
15311        let home = tempfile::tempdir().unwrap();
15312        let mut owner = stopped_public_run(RunStatus::Blocked);
15313        let repo = tempfile::tempdir().unwrap();
15314        crate::git::git(repo.path(), &["init"]).await.unwrap();
15315        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
15316        owner.id = "20260101-000000-aaaa".into();
15317        owner.save_under(home.path()).unwrap();
15318        let mut successor = run_state(RunStatus::Blocked);
15319        successor.id = "20260101-000001-bbbb".into();
15320        successor.save_under(home.path()).unwrap();
15321        let runs = vec![owner.id.clone(), successor.id.clone()];
15322        assert_eq!(
15323            public_resume_owner(home.path(), &runs, &owner.repo)
15324                .await
15325                .unwrap()
15326                .unwrap()
15327                .id,
15328            owner.id
15329        );
15330        let subdir = owner.repo.join("nested");
15331        std::fs::create_dir(&subdir).unwrap();
15332        assert_eq!(
15333            public_resume_owner(home.path(), &runs, &subdir)
15334                .await
15335                .unwrap()
15336                .unwrap()
15337                .id,
15338            owner.id
15339        );
15340        #[cfg(unix)]
15341        {
15342            let alias = home.path().join("repo-alias");
15343            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
15344            assert_eq!(
15345                public_resume_owner(home.path(), &runs, &alias.join("nested"))
15346                    .await
15347                    .unwrap()
15348                    .unwrap()
15349                    .id,
15350                owner.id
15351            );
15352        }
15353        let different = tempfile::tempdir().unwrap();
15354        crate::git::git(different.path(), &["init"]).await.unwrap();
15355        assert!(
15356            public_resume_owner(home.path(), &runs, different.path())
15357                .await
15358                .is_err()
15359        );
15360        // Explicit retirement leaves the historical approval on disk but
15361        // removes the predecessor from public-delivery admission.
15362        owner.status = RunStatus::Superseded;
15363        owner.pr.as_mut().unwrap().state = "closed".into();
15364        owner.save_under(home.path()).unwrap();
15365        assert!(
15366            public_resume_owner(home.path(), &runs, &owner.repo)
15367                .await
15368                .unwrap()
15369                .is_none()
15370        );
15371        std::fs::remove_file(
15372            home.path()
15373                .join("runs")
15374                .join(&successor.id)
15375                .join("run.json"),
15376        )
15377        .unwrap();
15378        assert!(
15379            public_resume_owner(home.path(), &runs, &owner.repo)
15380                .await
15381                .is_err()
15382        );
15383    }
15384
15385    #[test]
15386    fn an_ordinary_release_keeps_a_resumable_run_available() {
15387        let mut released = task();
15388        released.start("stalled-run".to_owned());
15389        released.release();
15390        let unfinished = (!released.fresh_start)
15391            .then(|| Some("stalled-run".to_owned()))
15392            .flatten();
15393        assert_eq!(
15394            choose_starter(None, false, unfinished.as_deref()),
15395            Starter::Resume("stalled-run".to_owned()),
15396            "manual release must preserve the normal resume path"
15397        );
15398    }
15399
15400    #[test]
15401    fn resume_refusals_explain_admission_without_changing_task_or_run() {
15402        use crate::handover::{ResumeRefusal, resume_refusal_under};
15403        let home = tempfile::tempdir().unwrap();
15404        let mut exhausted = run_state(RunStatus::Blocked);
15405        exhausted.driver_exited = true;
15406        exhausted.config.graph.review_rounds = 3;
15407        exhausted.reviews = (1..=3).map(review_round).collect();
15408        for refusal in [
15409            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
15410            ResumeRefusal::Status(RunStatus::Ready),
15411            ResumeRefusal::Released("20261022-000000-aaaa".into()),
15412            ResumeRefusal::Retired("retirement-successor".into()),
15413            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
15414        ] {
15415            let mut state = exhausted.clone();
15416            let expected = match refusal {
15417                ResumeRefusal::Status(_) => {
15418                    state.status = RunStatus::Ready;
15419                    "status `ready`"
15420                }
15421                ResumeRefusal::Released(ref target) => {
15422                    state.released_to = Some(target.clone());
15423                    "execution was released"
15424                }
15425                ResumeRefusal::Retired(ref target) => {
15426                    state.retired_to = Some(target.clone());
15427                    "execution was retired"
15428                }
15429                ResumeRefusal::OwnershipTransferred(ref target) => {
15430                    state.pr_taken_over_by = Some(target.clone());
15431                    "PR ownership was transferred"
15432                }
15433                _ => "review budget exhausted (3/3 rounds used)",
15434            };
15435            assert_eq!(
15436                resume_refusal_under(&state, Some(home.path())),
15437                Some(refusal.clone())
15438            );
15439            assert_eq!(
15440                refusal.successor(),
15441                state
15442                    .released_to
15443                    .as_deref()
15444                    .or(state.retired_to.as_deref())
15445                    .or(state.pr_taken_over_by.as_deref())
15446            );
15447            state.save_under(home.path()).unwrap();
15448            let queue = Queue::at(home.path().join("queue"));
15449            let mut task = Task::new(
15450                "retained implementation".into(),
15451                state.instruction.clone(),
15452                state.repo.clone(),
15453                Source::Agent {
15454                    run: "talk".into(),
15455                    node: crate::queue::CHAT_NODE.into(),
15456                },
15457            );
15458            task.runs.push(state.id.clone());
15459            task.hold_machine(Some("stopped".into()));
15460            queue.put(&mut task).unwrap();
15461            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
15462            let before_run = serde_json::to_value(&state).unwrap();
15463            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
15464                .unwrap_err()
15465                .to_string();
15466            assert!(error.contains(expected), "{error}");
15467            assert!(!error.contains("only a stalled or blocked"), "{error}");
15468            if matches!(refusal, ResumeRefusal::Status(_)) {
15469                assert!(
15470                    error.contains("is final; there is nothing left to resume"),
15471                    "{error}"
15472                );
15473            }
15474            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
15475                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
15476                assert!(error.contains("review-only successor with a new review budget"));
15477                assert!(error.contains("does not resume this run"));
15478            }
15479            for target in [
15480                &state.released_to,
15481                &state.retired_to,
15482                &state.pr_taken_over_by,
15483            ]
15484            .into_iter()
15485            .flatten()
15486            {
15487                let short = if state.retired_to.as_ref() == Some(target) {
15488                    target.as_str()
15489                } else {
15490                    crate::run::short_of(target)
15491                };
15492                assert!(
15493                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
15494                    "{error}"
15495                );
15496                if short != target {
15497                    assert!(!error.contains(target), "full successor id leaked: {error}");
15498                }
15499            }
15500            assert_eq!(
15501                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
15502                before_task
15503            );
15504            assert_eq!(
15505                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
15506                    .unwrap(),
15507                before_run
15508            );
15509            let question = action_question(&state.id, resume_action(&state.id));
15510            for phrases in [&PHRASES_EN, &PHRASES_JA] {
15511                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
15512                    RunState::load_under(id, home.path())
15513                });
15514                let ActionDecision::Refuse(detail) = decision else {
15515                    panic!(
15516                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
15517                        state.id,
15518                        home.path().display()
15519                    );
15520                };
15521                assert!(detail.contains(expected), "{detail}");
15522            }
15523        }
15524        // Preserve predicate ordering, while keeping every recorded destination visible.
15525        exhausted.status = RunStatus::Ready;
15526        exhausted.released_to = Some("released".into());
15527        exhausted.retired_to = Some("retired".into());
15528        exhausted.pr_taken_over_by = Some("owner".into());
15529        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
15530        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
15531        let detail = reason.diagnostic(&exhausted);
15532        for target in ["released", "retired", "owner"] {
15533            assert!(detail.contains(&format!("magi show {target}")));
15534        }
15535    }
15536
15537    #[test]
15538    fn resume_action_ignores_question_checkpoints_in_another_home() {
15539        crate::run::pin_test_home();
15540        let home = tempfile::tempdir().unwrap();
15541        let mut state = run_state(RunStatus::Blocked);
15542        // The private directory reserves this fixture's identity even while
15543        // other tests write questions into the process-wide store.
15544        state.id = format!(
15545            "resume-context-{}",
15546            home.path().file_name().unwrap().to_str().unwrap()
15547        );
15548        state.driver_exited = true;
15549        state.config.graph.review_rounds = 1;
15550        state.reviews = vec![review_round(1)];
15551        state.save_under(home.path()).unwrap();
15552        let task = held_task_with(&state.id);
15553        let answer = action_question(&state.id, resume_action(&state.id));
15554        let mut checkpoint = approval_question(&state.id);
15555        let foreign = Questions::open();
15556        foreign.put(&mut checkpoint).unwrap();
15557        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
15558        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15559            RunState::load_under(id, home.path())
15560        });
15561        let matching: Vec<_> = foreign
15562            .list()
15563            .into_iter()
15564            .filter(|q| q.run == state.id && q.status.open())
15565            .collect();
15566        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
15567        assert!(
15568            matches!(decision, ActionDecision::Refuse(_)),
15569            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
15570            state.id,
15571            home.path().display(),
15572            crate::run::test_home().display()
15573        );
15574        assert_eq!(
15575            refusal,
15576            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
15577        );
15578        let local = Questions::at(home.path().join("questions"));
15579        for status in [
15580            ask::QuestionStatus::Open,
15581            ask::QuestionStatus::Answered,
15582            ask::QuestionStatus::Abandoned,
15583        ] {
15584            let mut question = checkpoint.clone();
15585            match status {
15586                ask::QuestionStatus::Open => {}
15587                ask::QuestionStatus::Answered => {
15588                    question
15589                        .answer(ask::Answer::Choice(question.choices[0].clone()))
15590                        .unwrap();
15591                }
15592                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
15593            }
15594            local.put(&mut question).unwrap();
15595            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15596                RunState::load_under(id, home.path())
15597            });
15598            if status.open() {
15599                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
15600            } else {
15601                assert!(
15602                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
15603                    "status={status:?}, decision={decision:?}"
15604                );
15605            }
15606        }
15607    }
15608
15609    #[test]
15610    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
15611        let home = tempfile::tempdir().unwrap();
15612        let mut state = run_state(RunStatus::Stalled);
15613        state.id = format!(
15614            "resume-driver-{}",
15615            home.path().file_name().unwrap().to_str().unwrap()
15616        );
15617        state.driver_claimed = Some(false);
15618        state.save_under(home.path()).unwrap();
15619        let task = held_task_with(&state.id);
15620        let question = action_question(&state.id, resume_action(&state.id));
15621        let decide = || {
15622            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
15623                RunState::load_under(id, home.path())
15624            })
15625        };
15626        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
15627        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
15628        let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
15629        match decide() {
15630            ActionDecision::Refuse(detail) => {
15631                assert!(
15632                    detail.starts_with("run already has a live driver: "),
15633                    "{detail}"
15634                );
15635                assert!(
15636                    detail.contains(&expected_lock.display().to_string()),
15637                    "{detail}"
15638                );
15639            }
15640            other => panic!("expected live driver refusal, got {other:?}"),
15641        }
15642        drop(lease);
15643        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
15644    }
15645
15646    #[test]
15647    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
15648        let home = tempfile::tempdir().unwrap();
15649        let mut state = run_state(RunStatus::Blocked);
15650        state.driver_exited = true;
15651        state.config.graph.review_rounds = 1;
15652        state.reviews = vec![review_round(1)];
15653        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
15654        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
15655            let mut saved = state.clone();
15656            match checkpoint {
15657                "publication" => saved.pr_publication_pending = true,
15658                "approval" => {
15659                    saved.land_approval = Some(crate::run::LandApproval {
15660                        question: "approval".into(),
15661                        head: "head".into(),
15662                    })
15663                }
15664                "armed" => saved.land_armed_head = Some("head".into()),
15665                "landing" => saved.status = RunStatus::Landing,
15666                _ => {
15667                    let mut question = ask::Question::new(
15668                        saved.id.clone(),
15669                        "review".into(),
15670                        "review-1".into(),
15671                        "continue?".into(),
15672                        String::new(),
15673                        vec!["continue".into()],
15674                    );
15675                    ask::Questions::at(home.path().join("questions"))
15676                        .put(&mut question)
15677                        .unwrap();
15678                }
15679            }
15680            saved.save_under(home.path()).unwrap();
15681            assert!(
15682                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
15683                "{checkpoint}"
15684            );
15685            assert!(
15686                crate::resume::validate(home.path(), &saved.id).is_ok(),
15687                "{checkpoint}"
15688            );
15689        }
15690    }
15691
15692    #[test]
15693    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
15694        let mut state = run_state(RunStatus::Blocked);
15695        state.config.graph.review_rounds = 3;
15696        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
15697        assert!(exhausted_review_budget(&state));
15698
15699        // One round still unused: resuming can still ask a reviewer something.
15700        state.reviews.pop();
15701        assert!(!exhausted_review_budget(&state));
15702
15703        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
15704        // count: only a `Blocked` run re-enters the review loop on resume.
15705        let mut stalled = run_state(RunStatus::Stalled);
15706        stalled.config.graph.review_rounds = 1;
15707        stalled.reviews = vec![review_round(1)];
15708        assert!(!exhausted_review_budget(&stalled));
15709    }
15710
15711    fn review_round(round: usize) -> crate::run::ReviewRound {
15712        crate::run::ReviewRound {
15713            round,
15714            head: "deadbeef".to_owned(),
15715            verified_head: None,
15716            verified_at: None,
15717            reviews: Vec::new(),
15718            e2e: Vec::new(),
15719            verify_retried: false,
15720            e2e_deferred: false,
15721            e2e_defer_reason: None,
15722            fix: None,
15723            blocking: 0,
15724            answered: 1,
15725            expected: 1,
15726            clean: false,
15727            progressed: true,
15728            vote_split: false,
15729            reconsideration: Vec::new(),
15730            verdict: None,
15731        }
15732    }
15733
15734    #[test]
15735    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
15736        let mut run = RunState::new(
15737            PathBuf::from("/repo"),
15738            "main".to_owned(),
15739            "abc1234def".to_owned(),
15740            "add retries".to_owned(),
15741            Config::default(),
15742        );
15743        run.status = RunStatus::Judging;
15744        run.parked = true;
15745        let mut task = Task::new(
15746            "add retries".to_owned(),
15747            "add retries".to_owned(),
15748            PathBuf::from("/repo"),
15749            crate::queue::Source::Human,
15750        );
15751        task.status = TaskStatus::Failed;
15752        task.runs = vec![run.id.clone()];
15753        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
15754        assert!(with(&task, &run), "parked after judging is the case");
15755        let mut parked_task = task.clone();
15756        parked_task.status = TaskStatus::Parked;
15757        assert!(with(&parked_task, &run), "the Parked status is the case");
15758
15759        let mut not_parked = run.clone();
15760        not_parked.parked = false;
15761        not_parked.status = RunStatus::Stalled;
15762        assert!(!with(&task, &not_parked), "a stall is the conductor's");
15763
15764        let mut fresh = task.clone();
15765        fresh.fresh_start = true;
15766        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
15767
15768        let mut review = task.clone();
15769        review.review_branch = Some("magi/x/A".to_owned());
15770        assert!(!with(&review, &run), "review is ranked before resume");
15771
15772        let mut held = task.clone();
15773        held.status = TaskStatus::Held;
15774        assert!(!with(&held, &run), "a hold stays visible to the conductor");
15775
15776        let mut released = run.clone();
15777        released.released_to = Some("20260901-000000-new1".to_owned());
15778        assert!(!with(&task, &released), "nothing left to resume into");
15779
15780        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
15781            "unreadable"
15782        )));
15783    }
15784
15785    #[test]
15786    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
15787        let mut released = RunState::new(
15788            PathBuf::from("/repo"),
15789            "main".to_owned(),
15790            "abc1234def".to_owned(),
15791            "add retries".to_owned(),
15792            Config::default(),
15793        );
15794        released.status = RunStatus::Blocked;
15795        assert_eq!(
15796            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15797            Some(released.id.clone())
15798        );
15799        released.released_to = Some("20260901-000000-new1".to_owned());
15800        assert_eq!(
15801            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
15802            None,
15803            "there is nothing left to resume it into"
15804        );
15805    }
15806
15807    #[test]
15808    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
15809        // Mirrors the failure this exists to close: a task's last run ended
15810        // `Blocked` with the review budget spent, `crate::conduct` chose
15811        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
15812        // evidence), and without this check `attempt` would go on treating
15813        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
15814        // review loop iterates zero times over an already-spent budget, so
15815        // the resumed run settles right back to `Blocked` having asked nobody
15816        // anything, and `Requeue`'s promised fresh competition never happens.
15817        let mut exhausted = RunState::new(
15818            PathBuf::from("/repo"),
15819            "main".to_owned(),
15820            "abc1234def".to_owned(),
15821            "add retries".to_owned(),
15822            Config::default(),
15823        );
15824        exhausted.status = RunStatus::Blocked;
15825        exhausted.config.graph.review_rounds = 1;
15826        exhausted.reviews = vec![review_round(1)];
15827
15828        assert_eq!(
15829            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
15830            None,
15831            "an exhausted `Blocked` run must not be offered as resumable"
15832        );
15833
15834        // A `Blocked` run with rounds still unused is genuinely worth
15835        // resuming, and must still be found.
15836        let mut has_budget_left = RunState::new(
15837            PathBuf::from("/repo"),
15838            "main".to_owned(),
15839            "abc1234def".to_owned(),
15840            "add retries".to_owned(),
15841            Config::default(),
15842        );
15843        has_budget_left.status = RunStatus::Blocked;
15844        has_budget_left.config.graph.review_rounds = 3;
15845        has_budget_left.reviews = vec![review_round(1)];
15846
15847        assert_eq!(
15848            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
15849                Ok(has_budget_left.clone())
15850            }),
15851            Some(has_budget_left.id.clone())
15852        );
15853    }
15854
15855    #[test]
15856    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
15857        let mut run = RunState::new(
15858            PathBuf::from("/repo"),
15859            "main".to_owned(),
15860            "abc1234def".to_owned(),
15861            "add retries".to_owned(),
15862            Config::default(),
15863        );
15864        run.status = RunStatus::Blocked;
15865        run.config.graph.review_rounds = 1;
15866        run.reviews = vec![review_round(1)];
15867        run.pr_publication_pending = true;
15868        assert_eq!(
15869            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
15870            Some(run.id.clone()),
15871            "a spent review budget must not turn a failed publication into a re-competition"
15872        );
15873    }
15874
15875    #[test]
15876    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
15877        let mut task = Task::new(
15878            "recover work".into(),
15879            "recover work".into(),
15880            PathBuf::from("/repo"),
15881            crate::queue::Source::Human,
15882        );
15883        let mut history = std::collections::BTreeMap::new();
15884        for index in 0..8 {
15885            let mut run = run_state(RunStatus::Blocked);
15886            run.id = format!("20260101-000000-{index:04}");
15887            run.base_commit = format!("upstream-{index}");
15888            // Seven empty newer attempts must not erase the old recovery owner.
15889            if index > 0 {
15890                run.candidates.clear();
15891            }
15892            task.runs.extend([run.id.clone(), run.id.clone()]);
15893            history.insert(run.id.clone(), run);
15894            task.requeue();
15895        }
15896        let check = |task: &Task, starter: &Starter, limit| {
15897            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
15898        };
15899        assert!(
15900            check(&task, &Starter::Start, 8)
15901                .unwrap()
15902                .contains("8 unretired")
15903        );
15904        assert!(check(&task, &Starter::Start, 9).is_none());
15905        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
15906        task.release_operator("owner", None);
15907        assert_eq!(task.attempts, 0);
15908        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15909        assert!(check(&restored, &Starter::Start, 8).is_some());
15910        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
15911        assert!(check(&restored, &Starter::Start, 0).is_none());
15912    }
15913
15914    #[test]
15915    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
15916        let tmp = tempfile::tempdir().unwrap();
15917        let mut task = Task::new(
15918            "recover selected PR".into(),
15919            "preserve implementation".into(),
15920            tmp.path().join("repo"),
15921            crate::queue::Source::Human,
15922        );
15923        let mut failed = run_state(RunStatus::Failed);
15924        failed.id = "20260101-000000-fail".into();
15925        failed.candidates.clear();
15926        failed.prep_complete = Some(false);
15927        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
15928        failed.startup = Some(crate::run::Startup {
15929            kind: "pr-recovery".into(),
15930            branch: Some("selected-public-head".into()),
15931            stage: "worktree-setup".into(),
15932            complete: false,
15933            failure: Some("setup modified a tracked file and failed".into()),
15934        });
15935        // Setup may fail before a candidate is recorded; its dirty worktree
15936        // still needs protection and consumes the independent retained bound.
15937        let worktree = failed.worktree_root().join("under-review");
15938        std::fs::create_dir_all(&worktree).unwrap();
15939        let retained_edit = worktree.join("implementation");
15940        std::fs::write(&retained_edit, "retained setup edit").unwrap();
15941        task.record_startup_failure(crate::run::StartupFailure {
15942            run: failed.id.clone(),
15943            stage: "worktree-setup".into(),
15944        });
15945        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
15946        assert!(task.runs.is_empty() && task.passes.is_empty());
15947        assert_eq!(task.attempts, 0);
15948        let starter = Starter::Review("selected-public-head".into());
15949        assert!(
15950            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
15951                .unwrap()
15952                .contains("1 unretired")
15953        );
15954        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
15955        assert!(
15956            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
15957                .unwrap()
15958                .contains("Cannot verify")
15959        );
15960        // Older or mixed writers can link the same reservation in both lists.
15961        let mut mixed = task.clone();
15962        mixed.runs.push(failed.id.clone());
15963        mixed
15964            .startup_failures
15965            .push(task.startup_failures[0].clone());
15966        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
15967        failed.retired_to = Some("verified-recovery-owner".into());
15968        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
15969        assert!(
15970            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
15971                panic!("resuming the existing owner must not allocate a new attempt")
15972            })
15973            .is_none()
15974        );
15975        assert_eq!(
15976            std::fs::read_to_string(retained_edit).unwrap(),
15977            "retained setup edit"
15978        );
15979        assert!(task.runs.is_empty() && task.passes.is_empty());
15980        assert_eq!(task.attempts, 0);
15981    }
15982
15983    #[test]
15984    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
15985        let mut task = Task::new(
15986            "recover work".into(),
15987            "recover work".into(),
15988            PathBuf::from("/repo"),
15989            crate::queue::Source::Human,
15990        );
15991        let mut run = run_state(RunStatus::Superseded);
15992        run.candidates.clear();
15993        task.runs.push(run.id.clone());
15994        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
15995        run.retired_to = Some("authority".into());
15996        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
15997        run.retired_to = None;
15998        run.released_to = Some("authority".into());
15999        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
16000        assert!(
16001            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
16002                .unwrap()
16003                .contains("Cannot verify")
16004        );
16005        // Resuming an existing owner needs no new inventory or worktree budget.
16006        assert!(
16007            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
16008                panic!("resume must not load historical attempts")
16009            })
16010            .is_none()
16011        );
16012    }
16013
16014    #[test]
16015    fn retired_resume_requires_a_valid_same_repository_authority() {
16016        let mut source = run_state(RunStatus::Blocked);
16017        let mut empty = run_state(RunStatus::Blocked);
16018        empty.retired_to = Some(source.id.clone());
16019        let runs = vec![source.id.clone(), empty.id.clone()];
16020        let resolve = |source: &RunState, empty: &RunState| {
16021            unfinished_run_with(&runs, "fixture", |id| {
16022                if id == source.id {
16023                    Ok(source.clone())
16024                } else if id == empty.id {
16025                    Ok(empty.clone())
16026                } else {
16027                    bail!("unreadable authority")
16028                }
16029            })
16030        };
16031        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
16032        assert_eq!(
16033            choose_starter(None, false, resolve(&source, &empty).as_deref()),
16034            Starter::Resume(source.id.clone())
16035        );
16036        source.retired_to = Some(empty.id.clone());
16037        assert!(
16038            resolve(&source, &empty).is_none(),
16039            "cycles do not revive obsolete runs"
16040        );
16041        source.retired_to = None;
16042        source.repo = PathBuf::from("/another-repository");
16043        assert!(resolve(&source, &empty).is_none());
16044        source.repo = empty.repo.clone();
16045        source.released_to = Some("later".into());
16046        assert!(resolve(&source, &empty).is_none());
16047        empty.retired_to = Some("unlisted-run".into());
16048        assert!(resolve(&source, &empty).is_none());
16049    }
16050
16051    #[test]
16052    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
16053        // A task whose history holds an *older* run that still looks
16054        // resumable (say, a competition `Runner::review` was started
16055        // alongside after that older run went `Stalled`) and a *newest* run
16056        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
16057        // on this task must mean a fresh competition — falling back to the
16058        // stale, superseded `Stalled` run instead would resurrect history
16059        // nothing asked to revisit and silently defeat the requeue.
16060        let mut older_stalled = RunState::new(
16061            PathBuf::from("/repo"),
16062            "main".to_owned(),
16063            "abc1234def".to_owned(),
16064            "add retries".to_owned(),
16065            Config::default(),
16066        );
16067        older_stalled.status = RunStatus::Stalled;
16068
16069        let mut newest_exhausted = RunState::new(
16070            PathBuf::from("/repo"),
16071            "main".to_owned(),
16072            "abc1234def".to_owned(),
16073            "add retries".to_owned(),
16074            Config::default(),
16075        );
16076        newest_exhausted.status = RunStatus::Blocked;
16077        newest_exhausted.config.graph.review_rounds = 1;
16078        newest_exhausted.reviews = vec![review_round(1)];
16079
16080        assert_eq!(
16081            unfinished_run_with(
16082                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
16083                "t",
16084                |_| Ok(newest_exhausted.clone())
16085            ),
16086            None,
16087            "the newest run is exhausted, so nothing here is worth resuming - \
16088             least of all the older, already-superseded run"
16089        );
16090    }
16091
16092    #[test]
16093    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
16094        assert_eq!(
16095            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
16096                Err(anyhow::anyhow!("fixture is absent"))
16097            }),
16098            None
16099        );
16100    }
16101
16102    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
16103        let mut q = ask::Question::new(
16104            run.to_owned(),
16105            "implement".to_owned(),
16106            "impl-A".to_owned(),
16107            "continue?".to_owned(),
16108            String::new(),
16109            vec!["resume で続行する".to_owned(), "other".to_owned()],
16110        );
16111        q.actions.insert("resume で続行する".to_owned(), action);
16112        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
16113            .unwrap();
16114        q
16115    }
16116
16117    fn held_task_with(run: &str) -> Task {
16118        let mut t = task();
16119        t.runs = vec![run.to_owned()];
16120        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
16121        t
16122    }
16123
16124    fn resume_action(run: &str) -> ask::ChoiceAction {
16125        ask::ChoiceAction::Resume { run: run.into() }
16126    }
16127
16128    #[test]
16129    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
16130        let home = crate::run::test_home();
16131        for parked in [false, true] {
16132            let mut t = task();
16133            t.start("A".into());
16134            t.start("B".into());
16135            assert_eq!(t.runs, vec!["A", "B"]);
16136            t.start("A".into());
16137            let mut resumed = run_state(RunStatus::Blocked);
16138            resumed.id = "A".into();
16139            resumed.parked = parked;
16140            resumed.driver_exited = true;
16141            t.hold_machine(Some("resumed run stopped".into()));
16142            let q = action_question("A", resume_action("A"));
16143            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16144            assert_eq!(
16145                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
16146                    assert_eq!(id, "A");
16147                    Ok(resumed.clone())
16148                }),
16149                ActionDecision::Resume("A".into())
16150            );
16151            assert_eq!(
16152                action_standing(&t, &action_question("B", resume_action("B"))),
16153                ActionStanding::Stale
16154            );
16155            t.release_operator("cli", None);
16156            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
16157                assert_eq!(id, "A");
16158                Ok(resumed.clone())
16159            });
16160            assert_eq!(
16161                choose_starter(None, false, unfinished.as_deref()),
16162                Starter::Resume("A".into())
16163            );
16164            assert_eq!(t.runs, vec!["B", "A"]);
16165        }
16166    }
16167
16168    #[test]
16169    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
16170        let home = crate::run::test_home();
16171        let mut state = crate::land::tests::repair_state(true, true);
16172        state.status = RunStatus::Landing;
16173        state.parked = true;
16174        state.driver_exited = true;
16175        let mut q = ask::Question::new(
16176            state.id.clone(),
16177            land::APPROVAL_NODE.into(),
16178            "land".into(),
16179            "Merge?".into(),
16180            String::new(),
16181            vec![land::APPROVE.into(), land::HOLD.into()],
16182        );
16183        q.id = state.id.clone();
16184        state.land_approval = Some(crate::run::LandApproval {
16185            question: q.id.clone(),
16186            head: "current-head".into(),
16187        });
16188        assert!(land::upgrade_repair_choice(&mut q, &state));
16189        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16190        let mut task = held_task_with(&state.id);
16191        task.status = TaskStatus::Parked;
16192        assert_eq!(
16193            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16194            ActionDecision::Resume(state.id.clone())
16195        );
16196        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16197        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
16198        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
16199        assert_eq!(
16200            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16201            ActionDecision::Resume(state.id.clone()),
16202            "a repair answer newer than the manual hold resumes the existing owner"
16203        );
16204        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16205        for answered_at in [q.answered_at, None] {
16206            let mut older = q.clone();
16207            older.answered_at = answered_at;
16208            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
16209                panic!("a later manual hold must prevent dispatch")
16210            });
16211            let ActionDecision::Refuse(reason) = refused else {
16212                panic!("expected an actionable refusal, got {refused:?}");
16213            };
16214            assert!(reason.contains("later operator decision"));
16215            assert!(reason.contains(&format!("magi task release {}", task.id)));
16216        }
16217        task.operator_decided_at = None;
16218        let mut superseded = state.clone();
16219        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
16220        assert_eq!(
16221            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
16222            ActionDecision::Stale
16223        );
16224        for case in 1..4 {
16225            let mut changed = state.clone();
16226            match case {
16227                1 => changed.status = RunStatus::Blocked,
16228                2 => changed.released_to = Some("new-owner".into()),
16229                _ => changed.land_approval.as_mut().unwrap().head.clear(),
16230            }
16231            assert!(matches!(
16232                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
16233                ActionDecision::Refuse(_)
16234            ));
16235        }
16236        assert!(matches!(
16237            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
16238                "missing owner"
16239            )),
16240            ActionDecision::Refuse(_)
16241        ));
16242        task.runs.push("replacement".into());
16243        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16244        assert_eq!(
16245            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
16246                "old owner must not load"
16247            )),
16248            ActionDecision::Stale
16249        );
16250    }
16251
16252    #[test]
16253    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
16254        let mut state = crate::land::tests::repair_state(true, true);
16255        state.status = RunStatus::Landing;
16256        state.parked = true;
16257        state.driver_exited = true;
16258        let mut q = ask::Question::new(
16259            state.id.clone(),
16260            land::APPROVAL_NODE.into(),
16261            "land".into(),
16262            "Merge?".into(),
16263            String::new(),
16264            vec![land::APPROVE.into(), land::HOLD.into()],
16265        );
16266        q.id = state.id.clone();
16267        state.land_approval = Some(crate::run::LandApproval {
16268            question: q.id.clone(),
16269            head: "current-head".into(),
16270        });
16271        state.save().unwrap();
16272        land::upgrade_repair_choice(&mut q, &state);
16273        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16274        Questions::open().put(&mut q).unwrap();
16275        let tmp = tempfile::tempdir().unwrap();
16276        let queue = Queue::at(tmp.path().join("queue"));
16277        let mut task = held_task_with(&state.id);
16278        task.status = TaskStatus::Parked;
16279        queue.put(&mut task).unwrap();
16280        let empty = Arc::new(tokio::sync::Semaphore::new(0));
16281        let free = Arc::new(tokio::sync::Semaphore::new(1));
16282        assert!(matches!(
16283            claim_dispatch(&queue, &task, false, &empty, &free),
16284            Err(SkipReason::OrdinaryCapacity)
16285        ));
16286        assert!(matches!(
16287            claim_dispatch(&queue, &task, true, &free, &free),
16288            Err(SkipReason::CoolingDown)
16289        ));
16290        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
16291        assert!(claim.permit.is_some());
16292        assert!(matches!(
16293            claim_dispatch(&queue, &task, false, &free, &free),
16294            Err(SkipReason::ClaimUnavailable)
16295        ));
16296        drop(claim);
16297        Questions::open()
16298            .update(&q.id, |q| {
16299                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
16300                Ok(())
16301            })
16302            .unwrap();
16303        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
16304        assert!(claim.permit.is_none());
16305        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
16306    }
16307
16308    #[test]
16309    fn decide_action_resumes_only_the_latest_resumable_run() {
16310        let home = crate::run::test_home();
16311        let t = held_task_with("r1");
16312        let q = action_question("r1", resume_action("r1"));
16313        let load = |s: RunState| move |_: &str| Ok(s);
16314        assert_eq!(
16315            decide_action(
16316                &home,
16317                &t,
16318                &q,
16319                &PHRASES_EN,
16320                load(run_state(RunStatus::Blocked))
16321            ),
16322            ActionDecision::Resume("r1".into())
16323        );
16324        // Not the latest run of the task.
16325        let q_other = action_question("r1", resume_action("r0"));
16326        assert!(matches!(
16327            decide_action(
16328                &home,
16329                &t,
16330                &q_other,
16331                &PHRASES_EN,
16332                load(run_state(RunStatus::Blocked))
16333            ),
16334            ActionDecision::Refuse(_)
16335        ));
16336        // A finished run cannot make progress.
16337        assert!(matches!(
16338            decide_action(
16339                &home,
16340                &t,
16341                &q,
16342                &PHRASES_EN,
16343                load(run_state(RunStatus::Ready))
16344            ),
16345            ActionDecision::Refuse(_)
16346        ));
16347        // A released one either.
16348        let mut released = run_state(RunStatus::Blocked);
16349        released.released_to = Some("elsewhere".into());
16350        assert!(matches!(
16351            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
16352            ActionDecision::Refuse(_)
16353        ));
16354        // Unreadable state is a refusal, never a fresh competition.
16355        assert!(matches!(
16356            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
16357            ActionDecision::Refuse(_)
16358        ));
16359    }
16360
16361    #[test]
16362    fn decide_action_ignores_a_question_about_an_earlier_run() {
16363        let home = crate::run::test_home();
16364        let mut t = held_task_with("r1");
16365        t.runs.push("r2".to_owned());
16366        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16367        assert_eq!(
16368            decide_action(
16369                &home,
16370                &t,
16371                &action_question("r1", ask::ChoiceAction::Done),
16372                &PHRASES_EN,
16373                never
16374            ),
16375            ActionDecision::Stale
16376        );
16377    }
16378
16379    #[test]
16380    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
16381        let home = crate::run::test_home();
16382        let mut t = held_task_with("r1");
16383        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16384        assert_eq!(
16385            decide_action(
16386                &home,
16387                &t,
16388                &action_question("r1", ask::ChoiceAction::Requeue),
16389                &PHRASES_EN,
16390                never
16391            ),
16392            ActionDecision::Requeue
16393        );
16394        let done_q = action_question("r1", ask::ChoiceAction::Done);
16395        assert_eq!(
16396            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16397            ActionDecision::Done
16398        );
16399        t.mark_action_applied(&done_q.id);
16400        assert_eq!(
16401            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16402            ActionDecision::Skip
16403        );
16404
16405        // A plain answer (no action for that label) does nothing.
16406        let mut plain = action_question("r1", ask::ChoiceAction::Done);
16407        plain.actions.clear();
16408        assert_eq!(
16409            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
16410            ActionDecision::Skip
16411        );
16412        // A running task is left alone.
16413        let mut running = held_task_with("r1");
16414        running.status = TaskStatus::Running;
16415        assert_eq!(
16416            decide_action(
16417                &home,
16418                &running,
16419                &action_question("r1", ask::ChoiceAction::Done),
16420                &PHRASES_EN,
16421                never
16422            ),
16423            ActionDecision::Skip
16424        );
16425    }
16426
16427    #[test]
16428    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
16429        crate::run::pin_test_home();
16430        for legacy in [false, true] {
16431            let dir = tempfile::tempdir().unwrap();
16432            let queue = Queue::at(dir.path().join("queue"));
16433            let questions = Questions::at(dir.path().join("questions"));
16434            let run = "20260101-000000-hold";
16435            let mut task = held_task_with(run);
16436            task.status = TaskStatus::Parked;
16437            let mut q = ask::Question::new(
16438                run.into(),
16439                land::APPROVAL_NODE.into(),
16440                "land".into(),
16441                "Repair?".into(),
16442                String::new(),
16443                vec![land::REPAIR.into()],
16444            );
16445            q.actions.insert(land::REPAIR.into(), resume_action(run));
16446            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16447            // Deterministically order the answer before the actual manual hold.
16448            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16449            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
16450            questions.put(&mut q).unwrap();
16451            task.hold_manual(Some("Keep this PR paused".into()));
16452            if legacy {
16453                task.hold_source = None;
16454            }
16455            queue.put(&mut task).unwrap();
16456
16457            apply_task_choice_actions(&queue, &questions, dir.path());
16458            let after = queue.get(&task.id).unwrap();
16459            assert!(after.operator_held());
16460            assert_eq!(after.hold_source, task.hold_source);
16461            assert_eq!(after.operator_decided_at, task.operator_decided_at);
16462            assert_eq!(after.runs, task.runs);
16463            assert_eq!(after.instruction, task.instruction);
16464            assert!(after.resume_override.is_none());
16465            assert!(after.action_applied(&q.id));
16466            let reason = after.hold_reason.as_deref().unwrap();
16467            assert!(reason.starts_with("Keep this PR paused"));
16468            assert!(reason.contains("later operator decision"));
16469            assert!(reason.contains(&format!("magi task release {}", task.id)));
16470
16471            for recovery in [
16472                crate::conduct::Recovery::Review,
16473                crate::conduct::Recovery::Requeue,
16474            ] {
16475                crate::conduct::apply(
16476                    &queue,
16477                    &questions,
16478                    &crate::conduct::Verdict {
16479                        decisions: vec![crate::conduct::Decision {
16480                            id: task.id.clone(),
16481                            recovery: Some(recovery),
16482                            ..Default::default()
16483                        }],
16484                    },
16485                )
16486                .unwrap();
16487            }
16488            // Reconciliation is idempotent, and automatic recovery cannot
16489            // reopen this owner after it observes the rejected repair answer.
16490            apply_task_choice_actions(&queue, &questions, dir.path());
16491            let still_held = queue.get(&task.id).unwrap();
16492            assert!(still_held.operator_held());
16493            assert_eq!(still_held.hold_reason, after.hold_reason);
16494            assert_eq!(still_held.runs, task.runs);
16495            assert!(still_held.review_branch.is_none());
16496            assert!(!still_held.fresh_start);
16497            assert!(queue.next_runnable().is_none());
16498        }
16499    }
16500
16501    #[test]
16502    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
16503        for held in [false, true] {
16504            for retry in [false, true] {
16505                let dir = tempfile::tempdir().unwrap();
16506                let queue = Queue::at(dir.path().join("queue"));
16507                let questions = Questions::at(dir.path().join("questions"));
16508                let home = dir.path().join("home");
16509                let mut t = task();
16510                if held {
16511                    t.hold_machine(Some("driver state unknown".into()));
16512                }
16513                queue.put(&mut t).unwrap();
16514                let verdict = serde_json::from_value(serde_json::json!({
16515                    "decisions": [{
16516                        "id": t.id,
16517                        "question": "Driver state unknown; retry the checks or hold?",
16518                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
16519                        "actions": {
16520                            "daemon: recheck and retry": {"do": "requeue"},
16521                            "daemon: hold the task": {"do": "hold"}
16522                        }
16523                    }]
16524                }))
16525                .unwrap();
16526                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
16527                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16528                let mut q = questions.list().pop().unwrap();
16529                let choice = if retry {
16530                    "daemon: recheck and retry"
16531                } else {
16532                    "daemon: hold the task"
16533                };
16534                assert_eq!(q.actions.len(), 2);
16535                q.answer(ask::Answer::Choice(choice.into())).unwrap();
16536                questions.put(&mut q).unwrap();
16537
16538                // A Web answer does not remove the deputy's fresh lease.
16539                questions.beat(&q.id, ask::WaiterKind::Deputy);
16540                for _ in 0..2 {
16541                    resolve_blockers(&queue, &questions);
16542                    apply_task_choice_actions(&queue, &questions, &home);
16543                    let waiting = queue.get(&t.id).unwrap();
16544                    assert_eq!(waiting.status, TaskStatus::Blocked);
16545                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
16546                    assert!(waiting.answers.is_empty());
16547                    assert!(!waiting.action_applied(&q.id));
16548                    assert!(runnable(&queue).is_empty());
16549                    let free = Arc::new(tokio::sync::Semaphore::new(1));
16550                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
16551                }
16552                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16553
16554                // Releasing the blocker and applying the operation share one save.
16555                resolve_blockers(&queue, &questions);
16556                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16557                apply_task_choice_actions(&queue, &questions, &home);
16558                let after = queue.get(&t.id).unwrap();
16559                assert_eq!(
16560                    after.status,
16561                    if retry {
16562                        TaskStatus::Queued
16563                    } else {
16564                        TaskStatus::Held
16565                    }
16566                );
16567                assert!(after.action_applied(&q.id));
16568                assert_eq!(after.operator_held(), !retry);
16569                assert_eq!(after.answers.len(), 1);
16570
16571                // A later operator decision must not replay this answer.
16572                let mut changed = after;
16573                if retry {
16574                    changed.hold_manual(Some("later hold".into()));
16575                } else {
16576                    changed.release_operator("test", None);
16577                }
16578                let expected = changed.status;
16579                queue.put(&mut changed).unwrap();
16580                apply_task_choice_actions(&queue, &questions, &home);
16581                assert_eq!(queue.get(&t.id).unwrap().status, expected);
16582            }
16583        }
16584    }
16585
16586    #[test]
16587    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
16588        let dir = tempfile::tempdir().unwrap();
16589        let queue = Queue::at(dir.path().join("queue"));
16590        let questions = Questions::at(dir.path().join("questions"));
16591        let home = dir.path().join("home");
16592        let mut state = run_state(RunStatus::Blocked);
16593        state.id = "20260101-000000-act1".to_owned();
16594        state.save_under(&home).unwrap();
16595
16596        let mut t = held_task_with(&state.id);
16597        queue.put(&mut t).unwrap();
16598        let mut q = action_question(&state.id, resume_action(&state.id));
16599        questions.put(&mut q).unwrap();
16600
16601        apply_task_choice_actions(&queue, &questions, &home);
16602        let after = queue.get(&t.id).unwrap();
16603        assert_eq!(after.status, TaskStatus::Queued);
16604        assert!(!after.fresh_start);
16605        assert!(after.action_applied(&q.id));
16606        let pin = after.resume_override.clone().unwrap();
16607        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
16608        assert!(pin.forced);
16609
16610        // Held again later: the same answer does not release it a second time.
16611        let mut again = queue.get(&t.id).unwrap();
16612        again.hold_machine(Some("later".into()));
16613        queue.put(&mut again).unwrap();
16614        apply_task_choice_actions(&queue, &questions, &home);
16615        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16616    }
16617
16618    #[test]
16619    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
16620        let dir = tempfile::tempdir().unwrap();
16621        let home = dir.path();
16622        let queue = Queue::at(home.join("queue"));
16623        let questions = Questions::at(home.join("questions"));
16624        let mut state = run_state(RunStatus::Blocked);
16625        state.save_under(home).unwrap();
16626        let mut task = held_task_with(&state.id);
16627        queue.put(&mut task).unwrap();
16628        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
16629        questions.put(&mut question).unwrap();
16630
16631        apply_task_choice_actions(&queue, &questions, home);
16632
16633        let after = queue.get(&task.id).unwrap();
16634        assert_eq!(after.status, TaskStatus::Held);
16635        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
16636        assert_eq!(after.runs, task.runs);
16637        assert!(after.completion_history.is_empty());
16638        assert!(!after.decision_effects.contains_key(&question.id));
16639        assert_eq!(
16640            RunState::load_under(&state.id, home).unwrap().status,
16641            RunStatus::Blocked
16642        );
16643    }
16644
16645    #[test]
16646    fn a_delivered_answer_is_still_acted_on_exactly_once() {
16647        let dir = tempfile::tempdir().unwrap();
16648        let queue = Queue::at(dir.path().join("queue"));
16649        let questions = Questions::at(dir.path().join("questions"));
16650        let home = dir.path().join("home");
16651        let mut state = run_state(RunStatus::Blocked);
16652        state.id = "20260101-000000-act2".to_owned();
16653        state.save_under(&home).unwrap();
16654
16655        let mut t = held_task_with(&state.id);
16656        queue.put(&mut t).unwrap();
16657        let mut q = action_question(&state.id, resume_action(&state.id));
16658        q.answer_delivered = true;
16659        questions.put(&mut q).unwrap();
16660
16661        // Delivered, and the agent then died: the task is still held, so the
16662        // chosen action applies.
16663        apply_task_choice_actions(&queue, &questions, &home);
16664        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16665        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
16666
16667        // Held again: the same answer does nothing a second time.
16668        let mut again = queue.get(&t.id).unwrap();
16669        again.hold_machine(Some("later".into()));
16670        queue.put(&mut again).unwrap();
16671        apply_task_choice_actions(&queue, &questions, &home);
16672        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16673    }
16674
16675    #[test]
16676    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
16677        let dir = tempfile::tempdir().unwrap();
16678        let queue = Queue::at(dir.path().join("queue"));
16679        let questions = Questions::at(dir.path().join("questions"));
16680        let home = dir.path().join("home");
16681        let mut state = run_state(RunStatus::Blocked);
16682        state.id = "20260101-000000-act3".to_owned();
16683        state.save_under(&home).unwrap();
16684        let mut t = held_task_with(&state.id);
16685        queue.put(&mut t).unwrap();
16686        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
16687        questions.put(&mut q).unwrap();
16688
16689        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
16690        apply_task_choice_actions(&queue, &questions, &home);
16691        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16692
16693        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16694        apply_task_choice_actions(&queue, &questions, &home);
16695        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16696    }
16697
16698    #[test]
16699    fn action_standing_tells_the_reasons_apart() {
16700        let mut t = held_task_with("r1");
16701        let q = action_question("r1", ask::ChoiceAction::Requeue);
16702        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16703        let mut plain = q.clone();
16704        plain.actions.clear();
16705        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
16706
16707        // Applied wins over everything, even a running task.
16708        t.mark_action_applied(&q.id);
16709        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
16710
16711        // A newer attempt running: the old question is Stale, not Busy.
16712        let mut t = held_task_with("r1");
16713        t.start("r2".to_owned());
16714        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
16715        // The same question about the latest run just waits.
16716        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
16717        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16718        t.status = TaskStatus::Blocked;
16719        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16720
16721        // A conductor question is keyed by the task, never stale.
16722        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
16723        c.node = crate::conduct::NODE.to_owned();
16724        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
16725        assert!(!ActionStanding::Busy.daemon_owns());
16726    }
16727
16728    #[test]
16729    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
16730        let dir = tempfile::tempdir().unwrap();
16731        let queue = Queue::at(dir.path().join("queue"));
16732        let questions = Questions::at(dir.path().join("questions"));
16733        let home = dir.path().join("home");
16734        // Execution finished before task settlement; Done is not a discard.
16735        let mut state = run_state(RunStatus::Ready);
16736        state.id = "20260101-000000-act4".to_owned();
16737        state.save_under(&home).unwrap();
16738        let mut t = held_task_with(&state.id);
16739        t.status = TaskStatus::Running;
16740        queue.put(&mut t).unwrap();
16741        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
16742        q.cwd = Some(dir.path().display().to_string());
16743        questions.put(&mut q).unwrap();
16744
16745        // While the task runs the daemon will not act, so the waiter still
16746        // delivers the word to the dead asker's seat ...
16747        let running = queue.get(&t.id).unwrap();
16748        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
16749        assert!(matches!(
16750            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
16751            crate::waiter::Action::Deliver(_)
16752        ));
16753        // ... and the daemon waits while the task runs, then applies once.
16754        apply_task_choice_actions(&queue, &questions, &home);
16755        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
16756        let mut back = queue.get(&t.id).unwrap();
16757        back.hold_machine(Some("later".into()));
16758        queue.put(&mut back).unwrap();
16759        apply_task_choice_actions(&queue, &questions, &home);
16760        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
16761        let mut again = queue.get(&t.id).unwrap();
16762        again.hold_machine(Some("again".into()));
16763        queue.put(&mut again).unwrap();
16764        apply_task_choice_actions(&queue, &questions, &home);
16765        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16766    }
16767
16768    #[test]
16769    fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
16770     {
16771        let dir = tempfile::tempdir().unwrap();
16772        let home = dir.path();
16773        let queue = Queue::at(home.join("queue"));
16774        let mut state = run_state(RunStatus::Blocked);
16775        state.id = "20261125-084544-669a".to_owned();
16776        state.driver_exited = true;
16777        state.driver_pid = None;
16778        state.driver_started_at = None;
16779        state.save_under(home).unwrap();
16780
16781        let mut t = held_task_with(&state.id);
16782        queue.put(&mut t).unwrap();
16783
16784        // Simulate a task worker that finished and was archived to results/,
16785        // while daemon.json still has a fresh heartbeat referencing that worker.
16786        let worker_id = "fc769e65-0000-4000-8000-000000000001";
16787        let retained_dir = home.join("workers").join("results").join(worker_id);
16788        std::fs::create_dir_all(&retained_dir).unwrap();
16789        let finished_job = crate::worker::Job {
16790            id: worker_id.to_owned(),
16791            sequence: 1,
16792            kind: "task".to_owned(),
16793            key: format!("task:{}", t.id),
16794            payload: serde_json::json!({
16795                "queue": home.join("queue"),
16796                "task": t.id,
16797                "opts": Opts::default(),
16798                "standalone": false,
16799            }),
16800            generation: "a".repeat(64),
16801            version: Some("0.260.0".to_owned()),
16802            status: crate::worker::Status::Finished,
16803            result: Some("completed".to_owned()),
16804            pid: Some(37456),
16805            created_at: 1,
16806            finished_at: Some(2),
16807        };
16808        std::fs::write(
16809            retained_dir.join("job.json"),
16810            serde_json::to_vec(&finished_job).unwrap(),
16811        )
16812        .unwrap();
16813
16814        let now = Timestamp::now();
16815        let mut status = Status::new();
16816        status.updated_at = now;
16817        status.current = vec![Current {
16818            worker: Some(worker_id.to_owned()),
16819            task: t.id.clone(),
16820            run: state.id.clone(),
16821        }];
16822        write_status_to(&home.join("daemon.json"), &status).unwrap();
16823
16824        assert!(
16825            claim_for_run(home, &state.id, now).is_none(),
16826            "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
16827        );
16828        assert!(crate::resume::validate(home, &state.id).is_ok());
16829
16830        // Legacy heartbeat without worker id remains protected.
16831        status.current = vec![Current {
16832            worker: None,
16833            task: t.id.clone(),
16834            run: state.id.clone(),
16835        }];
16836        write_status_to(&home.join("daemon.json"), &status).unwrap();
16837        let legacy_err = crate::resume::validate(home, &state.id)
16838            .unwrap_err()
16839            .to_string();
16840        assert!(
16841            legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16842            "{legacy_err}"
16843        );
16844        assert!(legacy_err.contains("worker=none"), "{legacy_err}");
16845
16846        // Heartbeat naming a missing/unreadable worker record remains protected.
16847        let missing_id = "fc769e65-0000-4000-8000-000000000002";
16848        status.current = vec![Current {
16849            worker: Some(missing_id.to_owned()),
16850            task: t.id.clone(),
16851            run: state.id.clone(),
16852        }];
16853        write_status_to(&home.join("daemon.json"), &status).unwrap();
16854        let missing_err = crate::resume::validate(home, &state.id)
16855            .unwrap_err()
16856            .to_string();
16857        assert!(
16858            missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16859            "{missing_err}"
16860        );
16861        assert!(missing_err.contains(missing_id), "{missing_err}");
16862        assert!(missing_err.contains("status=unknown"), "{missing_err}");
16863
16864        // Heartbeat naming a Running (non-terminal) worker whose lease is not held
16865        // still remains protected conservatively until fenced to a terminal status.
16866        let running_id = "fc769e65-0000-4000-8000-000000000003";
16867        let running_dir = home.join("workers").join("jobs").join(running_id);
16868        std::fs::create_dir_all(&running_dir).unwrap();
16869        let running_job = crate::worker::Job {
16870            id: running_id.to_owned(),
16871            status: crate::worker::Status::Running,
16872            pid: Some(42424),
16873            finished_at: None,
16874            result: None,
16875            ..finished_job
16876        };
16877        std::fs::write(
16878            running_dir.join("job.json"),
16879            serde_json::to_vec(&running_job).unwrap(),
16880        )
16881        .unwrap();
16882        std::fs::write(running_dir.join("live.lock"), b"").unwrap();
16883        status.current = vec![Current {
16884            worker: Some(running_id.to_owned()),
16885            task: t.id.clone(),
16886            run: state.id.clone(),
16887        }];
16888        write_status_to(&home.join("daemon.json"), &status).unwrap();
16889        let running_err = crate::resume::validate(home, &state.id)
16890            .unwrap_err()
16891            .to_string();
16892        assert!(
16893            running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
16894            "{running_err}"
16895        );
16896        assert!(running_err.contains(running_id), "{running_err}");
16897        assert!(running_err.contains("pid=42424"), "{running_err}");
16898        assert!(running_err.contains("status=running"), "{running_err}");
16899    }
16900
16901    #[test]
16902    fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
16903        let dir = tempfile::tempdir().unwrap();
16904        let home = dir.path();
16905        let queue = Queue::at(home.join("queue"));
16906        let mut state = run_state(RunStatus::Blocked);
16907        state.id = "20261125-090000-evid".to_owned();
16908        state.driver_exited = true;
16909        state.save_under(home).unwrap();
16910        let mut t = held_task_with(&state.id);
16911        queue.put(&mut t).unwrap();
16912
16913        // 1. Live task worker holding live.lock.
16914        let payload = serde_json::json!({
16915            "queue": home.join("queue"),
16916            "task": t.id,
16917            "opts": Opts::default(),
16918            "standalone": false,
16919        });
16920        let (job, lease) =
16921            crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
16922        let worker_err = crate::resume::validate(home, &state.id)
16923            .unwrap_err()
16924            .to_string();
16925        assert!(
16926            worker_err.starts_with("run already has a live driver: worker claim"),
16927            "{worker_err}"
16928        );
16929        assert!(worker_err.contains(&job.id), "{worker_err}");
16930        assert!(
16931            worker_err.contains(&format!("pid={}", std::process::id())),
16932            "{worker_err}"
16933        );
16934        assert!(worker_err.contains("status=running"), "{worker_err}");
16935        assert!(worker_err.contains("live.lock held"), "{worker_err}");
16936        drop(lease);
16937        std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
16938
16939        // 2. Unfenced Starting worker reservation.
16940        let starting_id = "fc769e65-0000-4000-8000-000000000010";
16941        let starting_dir = home.join("workers").join("jobs").join(starting_id);
16942        std::fs::create_dir_all(&starting_dir).unwrap();
16943        let starting_job = crate::worker::Job {
16944            id: starting_id.to_owned(),
16945            sequence: 2,
16946            kind: "task".to_owned(),
16947            key: format!("task:{}", t.id),
16948            payload: serde_json::json!({
16949                "queue": home.join("queue"),
16950                "task": t.id,
16951                "opts": Opts::default(),
16952                "standalone": false,
16953            }),
16954            generation: "a".repeat(64),
16955            version: None,
16956            status: crate::worker::Status::Starting,
16957            result: None,
16958            pid: None,
16959            created_at: 1,
16960            finished_at: None,
16961        };
16962        std::fs::write(
16963            starting_dir.join("job.json"),
16964            serde_json::to_vec(&starting_job).unwrap(),
16965        )
16966        .unwrap();
16967        let starting_err = crate::resume::validate(home, &state.id)
16968            .unwrap_err()
16969            .to_string();
16970        assert!(
16971            starting_err.starts_with("run already has a live driver: worker claim"),
16972            "{starting_err}"
16973        );
16974        assert!(starting_err.contains(starting_id), "{starting_err}");
16975        assert!(starting_err.contains("status=starting"), "{starting_err}");
16976        assert!(
16977            starting_err.contains("unfenced starting reservation"),
16978            "{starting_err}"
16979        );
16980        std::fs::remove_dir_all(&starting_dir).unwrap();
16981
16982        // 3. Unrelated corrupt worker triggers conservative protection with distinct wording.
16983        let corrupt_id = "bad00000-0000-4000-8000-000000000099";
16984        let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
16985        std::fs::create_dir_all(&corrupt_dir).unwrap();
16986        std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
16987        let store_err = crate::resume::validate(home, &state.id)
16988            .unwrap_err()
16989            .to_string();
16990        assert!(
16991            store_err.starts_with(
16992                "run already has a live driver: worker store observation failed (conservative protection):"
16993            ),
16994            "{store_err}"
16995        );
16996        assert!(store_err.contains(corrupt_id), "{store_err}");
16997        std::fs::remove_dir_all(&corrupt_dir).unwrap();
16998
16999        // 4. Held execution lease (driver.lock path).
17000        state.driver_exited = false;
17001        state.driver_claimed = Some(false);
17002        state.driver_pid = None;
17003        state.driver_started_at = None;
17004        state.save_under(home).unwrap();
17005        let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
17006        let lease_err = crate::resume::validate(home, &state.id)
17007            .unwrap_err()
17008            .to_string();
17009        let lock_path = home.join("runs").join(&state.id).join("driver.lock");
17010        assert!(
17011            lease_err.starts_with("run already has a live driver: execution lease held"),
17012            "{lease_err}"
17013        );
17014        assert!(
17015            lease_err.contains(&lock_path.display().to_string()),
17016            "{lease_err}"
17017        );
17018        drop(exec_lease);
17019
17020        // 5. Live process identity (pid + identity).
17021        let pid = std::process::id();
17022        let identity = crate::proc::process_started_at(pid).expect("current process identity");
17023        state.driver_claimed = None;
17024        state.driver_pid = Some(pid);
17025        state.driver_started_at = Some(identity.clone());
17026        state.save_under(home).unwrap();
17027        let pid_err = crate::resume::validate(home, &state.id)
17028            .unwrap_err()
17029            .to_string();
17030        assert!(
17031            pid_err.starts_with("run already has a live driver: live driver process"),
17032            "{pid_err}"
17033        );
17034        assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
17035        assert!(
17036            pid_err.contains(&format!("identity={identity}")),
17037            "{pid_err}"
17038        );
17039
17040        // decide_action uses the exact same refusal format for process identity too.
17041        let question = action_question(&state.id, resume_action(&state.id));
17042        let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
17043            RunState::load_under(id, home)
17044        });
17045        assert_eq!(decision, ActionDecision::Refuse(pid_err));
17046    }
17047}