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        if (repair || stopping)
1092            && let ask::ChoiceAction::Resume { run } = action
1093            && task.execution_runs().last() == Some(run)
1094            && load(run).is_ok_and(|s| s.approval_revoked_by_revision(&q.id))
1095        {
1096            return ActionDecision::Stale;
1097        }
1098        return if repair || stopping {
1099            ActionDecision::Refuse(format!(
1100                "{} 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 {}`",
1101                if repair { "repair" } else { "stop" },
1102                q.id,
1103                q.run,
1104                task.id
1105            ))
1106        } else {
1107            ActionDecision::Stale
1108        };
1109    }
1110    match action {
1111        a if a.maintenance() => ActionDecision::Skip,
1112        ask::ChoiceAction::RecoverBase { .. }
1113        | ask::ChoiceAction::ResumeRun { .. }
1114        | ask::ChoiceAction::ReleaseTask { .. }
1115        | ask::ChoiceAction::RerunChecks { .. }
1116        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
1117        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
1118        ask::ChoiceAction::Hold => ActionDecision::Hold,
1119        ask::ChoiceAction::Done => ActionDecision::Done,
1120        ask::ChoiceAction::Resume { run } => {
1121            if task.execution_runs().last() != Some(run) {
1122                return ActionDecision::Refuse((p.resume_not_latest)(
1123                    q.short(),
1124                    ask::short_id(run),
1125                ));
1126            }
1127            match load(run) {
1128                // An answer given for an approval that the owner's later
1129                // instruction revision revoked must never resume or merge.
1130                Ok(s) if s.approval_revoked_by_revision(&q.id) => ActionDecision::Stale,
1131                Ok(s) if stopping => {
1132                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1133                        || !s
1134                            .land_approval
1135                            .as_ref()
1136                            .is_some_and(|binding| binding.question == q.id)
1137                    {
1138                        ActionDecision::Stale
1139                    } else if s.liveness_under(home, false) == Liveness::Live {
1140                        ActionDecision::Skip
1141                    } else if s.status == RunStatus::Landing
1142                        && !s.released()
1143                        && s.retired_to.is_none()
1144                    {
1145                        ActionDecision::Resume(run.clone())
1146                    } else {
1147                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1148                    }
1149                }
1150                Ok(s)
1151                    if q.node == land::APPROVAL_NODE
1152                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1153                {
1154                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1155                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1156                    {
1157                        // A live/manual driver already consumed or superseded
1158                        // this answer. Do not hold its fresh approval wait.
1159                        ActionDecision::Stale
1160                    } else if s.liveness_under(home, false) == Liveness::Live {
1161                        ActionDecision::Skip
1162                    } else if s.status != RunStatus::Landing
1163                        || s.released()
1164                        || s.reviews.is_empty()
1165                        || !implementers_match(task, &s)
1166                        || !s
1167                            .land_approval
1168                            .as_ref()
1169                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1170                    {
1171                        ActionDecision::Refuse(format!(
1172                            "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",
1173                            q.id, run, run
1174                        ))
1175                    } else {
1176                        ActionDecision::Resume(run.clone())
1177                    }
1178                }
1179                Ok(s) => {
1180                    let assessment = s.assess_liveness_under(home, None, Timestamp::now());
1181                    if assessment.verdict == Liveness::Live {
1182                        ActionDecision::Refuse(assessment.live_driver_refusal())
1183                    } else {
1184                        match crate::handover::resume_refusal_under(&s, Some(home)) {
1185                            None => ActionDecision::Resume(run.clone()),
1186                            Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1187                                q.short(),
1188                                ask::short_id(run),
1189                                &reason.diagnostic(&s),
1190                            )),
1191                        }
1192                    }
1193                }
1194                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1195                    q.short(),
1196                    ask::short_id(run),
1197                    &format!("{e:#}"),
1198                )),
1199            }
1200        }
1201    }
1202}
1203
1204/// The fixed prose the daemon writes into [`Task::last_error`] and
1205/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1206/// `triage::Wording` and `land::Words`: only English and Japanese are
1207/// translated, anything else falls back to English.
1208///
1209/// Rendered when the reason is *generated*, so a reason keeps the language it
1210/// was written in if the setting changes later. The notification frame
1211/// (`Task <id> is held:`) is not here and stays English.
1212///
1213/// Deliberately **not** translated, because other code reads them back by
1214/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1215/// and `gate red`. IDs, node names, paths and external error text are embedded
1216/// as they are.
1217struct Phrases {
1218    /// `{}` = status label, then the detail.
1219    graph_stopped: fn(&str, &str) -> String,
1220    quorum_lost: &'static str,
1221    /// Followed by the seats' names.
1222    quota_took_out: &'static str,
1223    /// Followed by the status label.
1224    run_ended: &'static str,
1225    /// Followed by the question's short id.
1226    waiting_for_answer: &'static str,
1227    recovered_running: &'static str,
1228    no_run_to_recover: &'static str,
1229    could_not_start: &'static str,
1230    resume_not_latest: fn(&str, &str) -> String,
1231    resume_cannot_progress: fn(&str, &str, &str) -> String,
1232    resume_unreadable: fn(&str, &str, &str) -> String,
1233    /// A takeover refusal: the operator-facing text. English is the error's own
1234    /// `Display`; a translation keeps the machine detail apart in parentheses.
1235    handover_refused: fn(&crate::handover::Refused) -> String,
1236    /// Appended to a refused handover's hold reason (leading space included).
1237    handover_hint: &'static str,
1238    /// (seats that never answered, review rounds) for the review loop's
1239    /// "refusing to call it clean" stop.
1240    reviewers_never_answered: fn(usize, usize) -> String,
1241}
1242
1243const PHRASES_EN: Phrases = Phrases {
1244    graph_stopped: |status, detail| {
1245        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1246    },
1247    quorum_lost: "the judging panel lost its quorum",
1248    quota_took_out: "; quota took out ",
1249    run_ended: "run ended ",
1250    waiting_for_answer: " - waiting for operator answer to question ",
1251    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1252    no_run_to_recover: "task was `running` with no live daemon and no readable \
1253                        run to recover; held for a human to check what happened",
1254    could_not_start: "could not start the run: ",
1255    resume_not_latest: |q, run| {
1256        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1257    },
1258    resume_cannot_progress: |q, run, reason| {
1259        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1260    },
1261    resume_unreadable: |q, run, e| {
1262        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1263    },
1264    handover_refused: |r| r.to_string(),
1265    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1266    reviewers_never_answered: |missing, rounds| {
1267        format!(
1268            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1269             refusing to call it clean"
1270        )
1271    },
1272};
1273
1274const PHRASES_JA: Phrases = Phrases {
1275    graph_stopped: |status, detail| {
1276        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1277    },
1278    quorum_lost: "審査パネルが定足数を失いました",
1279    quota_took_out: "。クォータで脱落: ",
1280    run_ended: "run 終了: ",
1281    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1282    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1283    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1284                        何が起きたか人が確認するため保留にしました",
1285    could_not_start: "run を開始できませんでした: ",
1286    resume_not_latest: |q, run| {
1287        format!(
1288            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1289        )
1290    },
1291    resume_cannot_progress: |q, run, reason| {
1292        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1293    },
1294    resume_unreadable: |q, run, e| {
1295        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1296    },
1297    handover_refused: |r| {
1298        use crate::handover::Refused;
1299        match r {
1300            Refused::Foreign { branch, path, why } => format!(
1301                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1302                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1303                 から、やり直してください(詳細: {why})"
1304            ),
1305            Refused::Unsafe { branch, path, why } => format!(
1306                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1307                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1308                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1309            ),
1310            Refused::ReleaseFailed { branch, path, run } => format!(
1311                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1312                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1313                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1314            ),
1315        }
1316    },
1317    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1318    reviewers_never_answered: |missing, rounds| {
1319        format!(
1320            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1321             クリーンとは認めません"
1322        )
1323    },
1324};
1325
1326fn phrases(language: &str) -> &'static Phrases {
1327    if crate::lang::is_japanese(language) {
1328        &PHRASES_JA
1329    } else {
1330        &PHRASES_EN
1331    }
1332}
1333
1334/// The language of the repository a task belongs to, read best-effort for the
1335/// paths that have no run (and so no config of their own) to ask. An unreadable
1336/// config is English, not an error: a hold reason must still get written.
1337fn language_of(task: &Task, fallback: &Path) -> String {
1338    crate::lang::of_repo(&repo_for(task, fallback))
1339}
1340
1341/// The task an answered question speaks for: the one whose runs include the
1342/// question's run, or - for a conductor question, filed under the task's own
1343/// id - the task with that id.
1344pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1345    if q.node == crate::conduct::NODE {
1346        return tasks.iter().find(|t| t.id == q.run);
1347    }
1348    tasks.iter().find(|t| t.runs.contains(&q.run))
1349}
1350
1351/// Legacy conductor prose never becomes a maintenance command by inference.
1352/// Replace unsupported open labels under the question lock before dispatch.
1353fn repair_choice_offers(questions: &Questions) {
1354    let ownership = crate::task_chat::InquiryOwnership::default();
1355    for q in questions
1356        .list_for_effects_in(&ownership)
1357        .into_iter()
1358        .filter(|q| {
1359            q.status.open()
1360                && q.node == crate::conduct::NODE
1361                && q.choices
1362                    .iter()
1363                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1364        })
1365    {
1366        let _ = questions.update_in(&q.id, &ownership, |current| {
1367            if current.status.open() {
1368                crate::choice_effect::executable_conductor(current);
1369                if let Some(deputy) = &mut current.deputy {
1370                    deputy.brief = crate::deputy::brief(
1371                        &current.run,
1372                        &current.detail,
1373                        &current.choices,
1374                        &current.actions,
1375                    );
1376                }
1377            }
1378            Ok(())
1379        });
1380    }
1381}
1382
1383/// Apply answered typed choices. Only the daemon calls this in production;
1384/// deputies settle the question and never execute its actions.
1385pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1386    apply_maintenance_choices(queue, questions, home).await;
1387    apply_task_choice_actions(queue, questions, home);
1388}
1389
1390/// Apply bounded maintenance effects independently of question ownership: a
1391/// release watcher need not have a queue task, and a predecessor is another run.
1392async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1393    let ownership = crate::task_chat::InquiryOwnership::default();
1394    for q in questions.list_for_effects_in(&ownership) {
1395        // Read again under the same fence used by explicit settlement.
1396        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1397            continue;
1398        };
1399        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1400            continue;
1401        };
1402        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1403            continue;
1404        };
1405        // Receipt paths use question IDs, whose format is independent of run
1406        // IDs. Apply the question store's filename safety rule to both eras.
1407        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1408            continue;
1409        }
1410        if queue.list().iter().any(|task| {
1411            (task.id == q.run
1412                || task.runs.contains(&q.run)
1413                || q.routed_task.as_deref() == Some(&task.id))
1414                && task.stale_question(&q)
1415        }) {
1416            continue;
1417        }
1418        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1419            let tasks = queue.list();
1420            let owner = crate::task_chat::task_of(&q, &tasks);
1421            if let Some(owner) = owner
1422                && q.routed_task
1423                    .as_deref()
1424                    .is_none_or(|routed| routed == owner)
1425            {
1426                let result = crate::base_recovery_control::recover(
1427                    queue,
1428                    home,
1429                    crate::base_recovery_control::Request {
1430                        run: run.clone(),
1431                        head: stop.head.clone(),
1432                        actor: "decisions".into(),
1433                        request: q.id.clone(),
1434                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1435                        expected_stop: Some((stop.clone(), *episode)),
1436                        evidence_digest: None,
1437                    },
1438                )
1439                .await;
1440                if let Err(error) = result {
1441                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1442                    notices::raise_in(home, Notice::warn(
1443                        &format!("base-recovery:{}", q.id),
1444                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1445                    ).link(Link::Run { id: run.clone() }));
1446                }
1447            }
1448            continue;
1449        }
1450        let dir = home.join("choice-actions");
1451        if std::fs::create_dir_all(&dir).is_err() {
1452            continue;
1453        }
1454        let Ok(lock) = std::fs::OpenOptions::new()
1455            .create(true)
1456            .truncate(false)
1457            .write(true)
1458            .open(dir.join(format!("{}.lock", q.id)))
1459        else {
1460            continue;
1461        };
1462        if crate::pr_head::try_lock_file(&lock).is_err() {
1463            continue;
1464        }
1465        let fresh = !home
1466            .join("choice-actions")
1467            .join(format!("{}.json", q.id))
1468            .exists();
1469        let result = async {
1470            let receipt = dir.join(format!("{}.json", q.id));
1471            if receipt.exists() {
1472                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1473                anyhow::ensure!(
1474                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1475                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1476                );
1477                return Ok::<_, anyhow::Error>(());
1478            }
1479            // Never retry an uncertain external effect. The receipt is written
1480            // before calling gh, exactly like release_watch's rerun record.
1481            let record = |status: &str| -> anyhow::Result<()> {
1482                let tmp = receipt.with_extension("tmp");
1483                std::fs::write(
1484                    &tmp,
1485                    serde_json::to_vec(&serde_json::json!({
1486                        "action": action, "status": status,
1487                    }))?,
1488                )?;
1489                std::fs::rename(tmp, &receipt)?;
1490                Ok(())
1491            };
1492            let applied = async {
1493                match action {
1494                    ask::ChoiceAction::ResumeRun { run } => {
1495                        crate::resume::validate(home, run)?;
1496                        record("started")?;
1497                        let decided = q.answered_at.unwrap_or(q.asked_at);
1498                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1499                            crate::resume::validate_unqueued(home, run)?;
1500                            crate::resume::start(home, run.clone()).await?;
1501                        }
1502                    }
1503                    ask::ChoiceAction::ReleaseTask {
1504                        task,
1505                        held_at,
1506                        reason,
1507                    } => {
1508                        anyhow::ensure!(
1509                            queue.resolve_id(task)? == *task,
1510                            "task action requires an exact task ID"
1511                        );
1512                        let _claim = queue.claim(task)?;
1513                        let mut task = queue.get(task)?;
1514                        if task.action_applied(&q.id) {
1515                            return Ok(());
1516                        }
1517                        // Filing this conductor question temporarily wraps the
1518                        // original hold in a Blocked state. Restore only that
1519                        // exact blocker on the local copy before checking the
1520                        // hold binding; unrelated waits never authorize release.
1521                        if q.node == crate::conduct::NODE
1522                            && q.run == task.id
1523                            && task.status == TaskStatus::Blocked
1524                            && task.blocked_from == Some(TaskStatus::Held)
1525                            && task.blocked_by.as_slice() == [q.id.as_str()]
1526                        {
1527                            task.unblock(&q.id);
1528                        }
1529                        anyhow::ensure!(
1530                            task.status == TaskStatus::Held
1531                                && task.held_at == Some(*held_at)
1532                                && task.hold_reason.as_deref() == reason.as_deref()
1533                                && task
1534                                    .operator_decided_at
1535                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1536                            "task no longer has the hold this question names"
1537                        );
1538                        task.release_operator("choice", Some(&q.id));
1539                        task.mark_action_applied(&q.id);
1540                        queue.put(&mut task)?;
1541                    }
1542                    ask::ChoiceAction::AbandonRun { run } => {
1543                        record("started")?;
1544                        crate::driver::abandon_proven_dead(home, run)?;
1545                    }
1546                    ask::ChoiceAction::RerunChecks {
1547                        repo,
1548                        pr,
1549                        head,
1550                        runs,
1551                    } => {
1552                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1553                            .await?;
1554                    }
1555                    _ => unreachable!(),
1556                }
1557                Ok::<_, anyhow::Error>(())
1558            }
1559            .await;
1560            match applied {
1561                Ok(()) => record("applied"),
1562                Err(e) => {
1563                    record(&format!("refused or failed: {e:#}"))?;
1564                    Err(e)
1565                }
1566            }
1567        }
1568        .await;
1569        // Retire the originating blocker as well as the target operation.
1570        // A foreign resume leaves its issuer held instead of competing beside
1571        // the execution just started. Other successful maintenance lets the
1572        // original task retry its normal, guarded path.
1573        if home
1574            .join("choice-actions")
1575            .join(format!("{}.json", q.id))
1576            .exists()
1577            && let Some(listed) = task_of_question(&queue.list(), &q)
1578            && !listed.action_applied(&q.id)
1579            && let Ok(_claim) = queue.claim(&listed.id)
1580            && let Ok(mut origin) = queue.get(&listed.id)
1581        {
1582            if !origin.operator_held()
1583                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1584                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1585            {
1586                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1587                    origin.hold_machine(Some(format!(
1588                        "Maintenance choice {} settled; inspect its target before releasing this task",
1589                        q.id
1590                    )));
1591                } else {
1592                    origin.unblock(&q.id);
1593                }
1594            }
1595            origin.mark_action_applied(&q.id);
1596            let _ = queue.put(&mut origin);
1597        }
1598        if let Err(e) = result
1599            && fresh
1600        {
1601            notices::raise_in(
1602                home,
1603                Notice::warn(
1604                    &format!("action:{}", q.id),
1605                    format!("Choice action {} was not completed: {e:#}", q.id),
1606                )
1607                .link(if q.run_names_task() {
1608                    Link::Task { id: q.run.clone() }
1609                } else {
1610                    Link::Run { id: q.run.clone() }
1611                }),
1612            );
1613        }
1614    }
1615}
1616
1617/// Rerun the named failed workflow runs of a pull request, each at most once
1618/// per `request` (a question id, or a chat operation identity). The head,
1619/// lifecycle and failed state are re-read from the forge first; `started` is
1620/// called once those checks pass and before the first external call, and the
1621/// ledger entry is written before every `gh` call, so an uncertain result is
1622/// never repeated automatically.
1623pub(crate) async fn rerun_checks_once(
1624    home: &Path,
1625    request: &str,
1626    repo: &Path,
1627    pr: &str,
1628    head: &str,
1629    runs: &[String],
1630    started: impl FnOnce() -> anyhow::Result<()>,
1631) -> anyhow::Result<()> {
1632    use crate::release_watch::{GhForge, ReleaseForge};
1633    anyhow::ensure!(
1634        !runs.is_empty()
1635            && runs.len() <= 20
1636            && runs
1637                .iter()
1638                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1639            && !pr.starts_with('-'),
1640        "invalid rerun targets"
1641    );
1642    let snap = GhForge.snapshot(repo, pr).await?;
1643    anyhow::ensure!(
1644        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1645        "pull request head or lifecycle changed"
1646    );
1647    anyhow::ensure!(
1648        runs.iter().all(|r| snap
1649            .checks
1650            .iter()
1651            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1652        "named workflow is no longer failed on this pull request"
1653    );
1654    started()?;
1655    let dir = home.join("choice-actions");
1656    std::fs::create_dir_all(&dir)?;
1657    let rerun_lock = std::fs::OpenOptions::new()
1658        .create(true)
1659        .truncate(false)
1660        .write(true)
1661        .open(dir.join("reruns.lock"))?;
1662    crate::pr_head::try_lock_file(&rerun_lock)?;
1663    let ledger = dir.join("reruns.json");
1664    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1665        serde_json::from_slice(&std::fs::read(&ledger)?)?
1666    } else {
1667        Default::default()
1668    };
1669    for run in runs {
1670        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1671        if !recorded.insert(key) {
1672            continue;
1673        }
1674        let tmp = ledger.with_extension("tmp");
1675        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1676        std::fs::rename(tmp, &ledger)?;
1677        GhForge.rerun(repo, run).await?;
1678    }
1679    Ok(())
1680}
1681
1682/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1683///
1684/// Runs on every poll before the conductor looks at the queue. The task is
1685/// re-read under its claim, so a task somebody completed or held by hand in
1686/// the meantime is judged on what it is now. `Resume` releases the task and
1687/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1688/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1689/// ordinary `unfinished_run` logic resumes that same run.
1690pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1691    let tasks = queue.list();
1692    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1693    for q in questions.list_for_effects_in(&ownership) {
1694        // Read again under the same fence used by explicit settlement.
1695        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1696            continue;
1697        };
1698        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1699            continue;
1700        };
1701        // Dismissal is committed by the question writer, never a resume.
1702        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1703            continue;
1704        }
1705        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1706            continue;
1707        }
1708        let Some(listed) = task_of_question(&tasks, &q) else {
1709            if q.node == land::APPROVAL_NODE
1710                && q.resolution().as_deref().is_some_and(|choice| {
1711                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1712                })
1713            {
1714                notices::raise_in(
1715                    home,
1716                    Notice::warn(
1717                        &format!("repair-owner:{}", q.id),
1718                        format!(
1719                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1720                            q.run, q.run
1721                        ),
1722                    ).link(Link::Run { id: q.run.clone() }),
1723                );
1724            }
1725            continue;
1726        };
1727        if listed.action_applied(&q.id) {
1728            continue;
1729        }
1730        let Ok(_claim) = queue.claim(&listed.id) else {
1731            continue;
1732        };
1733        let Ok(mut task) = queue.get(&listed.id) else {
1734            continue;
1735        };
1736        // Work only on this local copy until the action can be committed.
1737        // In particular, a fresh lease below leaves the persisted task blocked.
1738        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1739            let blockers: Vec<_> = task
1740                .blocked_by
1741                .iter()
1742                .filter(|id| {
1743                    crate::queue::dependency(queue, questions, id)
1744                        == crate::queue::Dependency::Question(q.id.clone())
1745                })
1746                .cloned()
1747                .collect();
1748            if !blockers.is_empty() {
1749                for id in blockers {
1750                    task.unblock(&id);
1751                }
1752                let answer = match &q.answer {
1753                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1754                    None => String::new(),
1755                };
1756                task.record_answer(q.summary.clone(), answer);
1757            }
1758        }
1759        let language = language_of(&task, Path::new("."));
1760        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1761            RunState::load_under(id, home)
1762        });
1763        let completion = if matches!(decision, ActionDecision::Done) {
1764            match crate::task_completion::prepare_close(
1765                &task,
1766                home,
1767                CompletionActor::DaemonSettle,
1768                Some(format!(
1769                    "Question {}: {} — {}",
1770                    q.id,
1771                    q.summary,
1772                    q.resolution().unwrap_or_default()
1773                )),
1774                false,
1775            ) {
1776                Ok(context) => Some(context),
1777                Err(error) => {
1778                    decision = ActionDecision::Refuse(error.to_string());
1779                    None
1780                }
1781            }
1782        } else {
1783            None
1784        };
1785        let ran = matches!(
1786            decision,
1787            ActionDecision::Resume(_)
1788                | ActionDecision::Requeue
1789                | ActionDecision::Hold
1790                | ActionDecision::Done
1791        );
1792        if ran && asker_may_still_read(questions, &q, home) {
1793            // The asking process or its seat can still take the word; act
1794            // once it has gone quiet. Bound on the remaining window: the
1795            // check is not atomic with the write below, so an asker that
1796            // takes the word in between (at most one poll, never more than
1797            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1798            // and `Task::actions_applied` under the claim keeps the action to
1799            // one application. The waiter does not deliver an answer that
1800            // carries an action (`waiter::decide_owned`), so it cannot race.
1801            continue;
1802        }
1803        let done = matches!(decision, ActionDecision::Done);
1804        // Resume owes an execution pass; only these task-local effects finish
1805        // in this write. Stale/refused actions never acquire an effect receipt.
1806        let completed = matches!(
1807            decision,
1808            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1809        );
1810        match decision {
1811            ActionDecision::Skip => continue,
1812            ActionDecision::Resume(run) => {
1813                task.release_operator("choice", Some(&q.id));
1814                task.resume_override = Some(crate::queue::OperatorResume {
1815                    question_id: q.id.clone(),
1816                    at: Timestamp::now(),
1817                    conductor_rehold: None,
1818                    forced: true,
1819                    pinned_run: Some(run),
1820                });
1821            }
1822            ActionDecision::Stale => {}
1823            ActionDecision::Requeue => {
1824                task.release_operator("choice-requeue", Some(&q.id));
1825                task.requeue();
1826            }
1827            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1828            ActionDecision::Done => {
1829                task.succeed(completion.expect("done passed completion admission"));
1830            }
1831            ActionDecision::Refuse(why) => {
1832                let _ =
1833                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1834                if task.operator_held() {
1835                    // A rejected answer does not release the operator's hold
1836                    // or reclassify it as recoverable by the conductor.
1837                    task.hold_reason = Some(match task.hold_reason.take() {
1838                        Some(reason) => format!("{reason}\n\n{why}"),
1839                        None => why,
1840                    });
1841                } else {
1842                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1843                    task.hold_machine(Some(why));
1844                }
1845                notices::raise(
1846                    Notice::warn(
1847                        &format!("action:{}", q.id),
1848                        "An answered task action could not be applied; the task stays held.",
1849                    )
1850                    .link(Link::Task {
1851                        id: task.id.clone(),
1852                    }),
1853                );
1854            }
1855        }
1856        task.mark_action_applied(&q.id);
1857        if completed {
1858            task.decision_effects.insert(
1859                q.id.clone(),
1860                format!("decision: {}", q.resolution().expect("answered action")),
1861            );
1862        }
1863        // The applied id travels with the transition, so a failed save loses
1864        // neither and the answer is acted on at the next poll.
1865        record(queue, &mut task);
1866        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1867            supersede_prior_runs(&task, home);
1868        }
1869        // Delivery is only a note of who has read the answer; the task's own
1870        // mark above is the authority. Best effort.
1871        let _ = questions.update_in(&q.id, &ownership, |r| {
1872            r.answer_delivered = true;
1873            Ok(())
1874        });
1875    }
1876}
1877
1878/// Whether something may still read the answer to `q`: a fresh lease, or the
1879/// asking seat still listed as active in its run (its CLI can outlive the
1880/// `magi ask` that was killed).
1881fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1882    let now = Timestamp::now();
1883    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1884        return true;
1885    }
1886    q.node != crate::conduct::NODE
1887        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1888            s.seats_active()
1889                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1890        })
1891}
1892
1893/// Retire an unanswered conductor question after its task no longer refers to
1894/// it. Conductor questions use the task id in `Question::run`, so run-based
1895/// cleanup cannot observe a manual release or completion.
1896///
1897/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1898/// own question also carries a `run`, and a run id that happens to collide
1899/// with some task's id is not this loop's business — only a conductor
1900/// question actually uses the task id that way. One `Questions::list()` scan
1901/// is taken up front and matched against the in-memory task set, rather than
1902/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1903fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1904    let tasks = queue.list();
1905    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1906    let by_id: std::collections::BTreeMap<&str, &Task> =
1907        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1908    let referenced: Vec<&str> = tasks
1909        .iter()
1910        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1911        .collect();
1912
1913    for mut question in questions.list_for_effects_in(&ownership) {
1914        if !question.status.open()
1915            || question.node != crate::conduct::NODE
1916            || questions.held_reply_in(&question.id, &ownership)
1917        {
1918            continue;
1919        }
1920        // Keep questions a task still names, including when the reference
1921        // moved to a dependent task.
1922        // Preserve even ambiguous references: retiring a possibly referenced
1923        // question is unsafe until the operator disambiguates it.
1924        if referenced
1925            .iter()
1926            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1927        {
1928            continue;
1929        }
1930        let Some(task) = by_id.get(question.run.as_str()) else {
1931            continue;
1932        };
1933        question.abandon(format!(
1934            "task {} no longer waits for this answer",
1935            task.short()
1936        ));
1937        if let Err(e) = questions.put_in(&mut question, &ownership) {
1938            tracing::warn!(
1939                "could not retire question {} for task {}: {e:#}",
1940                question.short(),
1941                task.short()
1942            );
1943        }
1944    }
1945}
1946
1947/// What a finished run tells the queue about the task it came from.
1948///
1949/// A struct rather than a fourth and fifth boolean argument: the two flags
1950/// answer different questions about the same run, and a call site passing
1951/// `(…, true, false)` is one transposition away from refunding attempts
1952/// forever.
1953#[derive(Debug, Clone, Copy)]
1954pub struct Verdict {
1955    /// Where the graph stopped.
1956    pub status: RunStatus,
1957    /// The run opened a pull request.
1958    pub left_pr: bool,
1959    /// At least one seat was lost to a rate limit.
1960    pub quota_hit: bool,
1961    /// The run parked at a node boundary because it was asked to.
1962    pub parked: bool,
1963    /// The run never produced a single candidate a judge could look at.
1964    ///
1965    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1966    /// still have another candidate worth judging, in which case the loss was
1967    /// not the reason nothing came of the run. This is `true` only when the
1968    /// implement wave ended with nothing viable at all.
1969    pub no_viable_candidates: bool,
1970}
1971
1972/// Record a finished run against the task it came from.
1973///
1974/// Kept pure and separate from the loop because this mapping *is* the retry
1975/// policy, and a policy that can only be exercised by spawning a graph is a
1976/// policy nobody checks. The table:
1977///
1978/// | run status                           | task becomes        | attempt spent |
1979/// |---------------------------------------|---------------------|---------------|
1980/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1981/// | `Merged`, `Ready`                      | `Done`               | yes          |
1982/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1983/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1984/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1985/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1986/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1987/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1988/// | `Blocked` with a PR                    | `Held`               | yes          |
1989/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1990/// | `VerifiedNoop`                          | `Held`               | yes          |
1991/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1992///
1993/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1994/// deliberately: every candidate agreeing there is nothing to write is not a
1995/// machine fact about a rate limit, it is an unverified claim about the
1996/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1997/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1998/// claim could be wrong (a misread instruction, a stale check), and closing
1999/// the task automatically on an implementer's say-so would be the exact
2000/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
2001/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
2002/// above, which settles through the same [`Task::handed_off`]: `Held` is not
2003/// `Failed`-and-requeued, so nothing retries this task on the same unverified
2004/// claim regardless of whether the one already-spent attempt is refunded, and
2005/// [`Task::release`] resets the count to zero anyway the moment a human looks
2006/// at the evidence and lets it run again.
2007///
2008/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
2009/// twice, together. A quorum lost to rate limits is a property of the machine
2010/// and not of the task, so the attempt is refunded and a reset quota picks
2011/// the work up where it stopped — and that is just as true when every
2012/// implement seat lost the same race and `after_implement` bails with nothing
2013/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
2014/// machine fact. The `no_viable_candidates` guard is what keeps that row
2015/// narrow: a `Failed` run that produced a real candidate which then lost for
2016/// some other reason still spends the attempt, exactly like the quorum lost
2017/// to judges that answered with the wrong shape is ordinary flakiness, and
2018/// refunding *that* takes the bound off the retry loop entirely: run e633
2019/// stalled with `quota: []` after two judges wrote unusable JSON, was
2020/// refunded, and the next attempt paid for a fresh hour-long implement wave
2021/// before it could fail the same way. `max_attempts` exists precisely so
2022/// that cannot repeat forever.
2023///
2024/// A non-terminal status means `execute` returned while the graph was still
2025/// mid-flight, which is a bug rather than a verdict; it is treated as a
2026/// failure so that a task cannot loop on it either.
2027///
2028/// `left_pr` splits the `Blocked` row, and it is the difference between a run
2029/// that failed and a run that finished into a gate. See [`Task::handed_off`].
2030pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
2031    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
2032}
2033
2034/// [`settle`], with the daemon's own fixed prose in `p`'s language.
2035fn settle_in(
2036    task: &mut Task,
2037    verdict: Verdict,
2038    detail: &str,
2039    max_attempts: usize,
2040    p: &Phrases,
2041    state: Option<&RunState>,
2042) {
2043    // A parked run is the operator's own doing, and its work is intact on
2044    // disk. The task goes back in line with its attempt refunded so the next
2045    // loop resumes the same run - which `one_task` prefers over competing
2046    // again - and so that swapping the binary a few times cannot exhaust a
2047    // budget meant for agents that actually misbehaved.
2048    if verdict.parked {
2049        task.park(detail);
2050        return;
2051    }
2052    let completion = |task: &Task| match state {
2053        Some(state) => CompletionContext::from_run(
2054            CompletionActor::DaemonSettle,
2055            Some(detail.to_owned()),
2056            task,
2057            state,
2058        ),
2059        None => CompletionContext::new(
2060            CompletionActor::DaemonSettle,
2061            Some(detail.to_owned()),
2062            &crate::run::home(),
2063            task,
2064        ),
2065    };
2066    match verdict.status {
2067        RunStatus::Merged | RunStatus::Ready
2068            if task.pr_recovery.as_ref().is_some_and(|s| {
2069                s.disposition != Some(crate::pr_recovery::Disposition::Review)
2070            }) =>
2071        {
2072            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()));
2073        }
2074        RunStatus::Merged => {
2075            if task.investigation && task.current_investigation_result().is_none() {
2076                task.hold_unrequested_retry(Some(
2077                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2078                        .into(),
2079                ));
2080            } else {
2081                task.succeed(completion(task));
2082            }
2083        }
2084        RunStatus::Ready => {
2085            if task.investigation {
2086                if task.current_investigation_result().is_some() {
2087                    task.succeed(completion(task));
2088                } else {
2089                    task.hold_unrequested_retry(Some(
2090                        "Investigation finished without recorded findings; complete it with a nonblank --result."
2091                            .into(),
2092                    ));
2093                }
2094            } else if state.is_some_and(crate::landing::run_landed_for_settle) {
2095                task.succeed(completion(task));
2096            } else {
2097                // `Ready` means mergeable, not merged: `[merge] mode = "none"`,
2098                // an empty winner, or an unmerged PR all stop here. Keep the
2099                // branch and attempt intact without re-competing.
2100                let reason = "Ready but not landed: the run finished without a confirmed merge \
2101                    into the base branch, so the task is not done. Review the retained branch \
2102                    and land it (then `magi task done`), release the task to run it again, or \
2103                    mark it with `magi task investigation` if it was never meant to change the \
2104                    repository."
2105                    .to_owned();
2106                if let Some(run_id) = state
2107                    .map(|s| s.id.clone())
2108                    .or_else(|| task.execution_runs().last().cloned())
2109                {
2110                    task.hold_awaiting_landing(run_id, reason);
2111                } else {
2112                    task.hold_unrequested_retry(Some(reason));
2113                }
2114            }
2115        }
2116        RunStatus::AlreadyInBase => {
2117            if task.investigation && task.current_investigation_result().is_none() {
2118                task.hold_unrequested_retry(Some(
2119                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2120                        .into(),
2121                ));
2122            } else {
2123                task.already_landed(detail, completion(task));
2124            }
2125        }
2126        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
2127        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
2128            task.stall(detail)
2129        }
2130        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
2131        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
2132        RunStatus::Blocked => task.fail(detail, max_attempts),
2133        RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
2134            task.handed_off(detail)
2135        }
2136        RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
2137        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
2138    }
2139}
2140
2141/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
2142/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
2143/// itself has actually finished *and* its own last attempt is provably why:
2144/// this loads that run and requires `Merged`/`Ready` before touching
2145/// anything earlier in `runs`, since `Task::succeed` can also be called
2146/// directly on a task whose last attempt never landed at all.
2147///
2148/// Called right after whatever call set `task.status` to
2149/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
2150/// `reclaim`'s, but also every other place a task can be closed by hand
2151/// without the loop ever settling it itself: `magi task done`
2152/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
2153/// (`web::queue_done`). Closing a task by hand — after confirming a manual
2154/// GitHub merge, say, exactly the workflow this repository's own
2155/// "Landing a run's winner by hand" documents — is just as much "this task's
2156/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
2157/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
2158/// forever, which is the exact backlog this status exists to clear. `pub`
2159/// for those two out-of-module callers; everything else about this stays
2160/// internal bookkeeping.
2161///
2162/// A run something is still actually driving is left alone: a
2163/// task cannot be `Done` while one of its *own* attempts is still in flight,
2164/// so a live one at this point can only be an unrelated process — a manual
2165/// `--resume` of this old, now-moot run — and rewriting under it would just
2166/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
2167/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
2168/// pair `run_report`/`run_detail` use for the same question elsewhere:
2169/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
2170/// --resume` invoked by hand outside it, which `liveness` also checks via
2171/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
2172/// (already terminal in some other way, or itself mid-run) is left untouched
2173/// too.
2174///
2175/// Best-effort, like the rest of this module's bookkeeping: a load or save
2176/// failure here is a `tracing::warn`, not a failed settle, and the next time
2177/// this same task's completion is recorded — or a daemon restart replays
2178/// `reclaim_orphaned_running` — is another chance to catch up. There is no
2179/// separate reconciliation pass; if that gap ever matters in practice, one
2180/// can be added then.
2181///
2182/// `home` is a parameter, not the process-global [`crate::run::home`], for
2183/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2184/// calls this with `ui.home`, which is `crate::run::home()` in a real
2185/// process but a fixture's own directory under test — falling through to
2186/// the global there would read and write through whichever home some other
2187/// test in the same binary happened to pin into that `OnceLock` first, not
2188/// the run this call actually means.
2189pub fn supersede_prior_runs(task: &Task, home: &Path) {
2190    if task
2191        .completion_history
2192        .last()
2193        .is_some_and(|event| event.discard)
2194    {
2195        return;
2196    }
2197    let now = Timestamp::now();
2198    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2199    // right behind a `Merged`/`Ready` verdict) from one set directly by
2200    // `magi task done`/its web equivalent/the conductor on a task whose last
2201    // recorded attempt never actually landed - that requires reading the
2202    // run itself, which is exactly what this does before trusting anything
2203    // in `runs` is safe to relabel.
2204    let last_run_succeeded = task
2205        .runs
2206        .last()
2207        .and_then(|id| RunState::load_under(id, home).ok())
2208        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2209    for id in task.superseded_attempts(last_run_succeeded) {
2210        let mut state = match RunState::load_under(id, home) {
2211            Ok(s) => s,
2212            Err(e) => {
2213                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2214                continue;
2215            }
2216        };
2217        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2218            continue;
2219        }
2220        let daemon_claims = is_working_on(home, id, now);
2221        if state.liveness(daemon_claims) == Liveness::Live {
2222            continue;
2223        }
2224        state.status = RunStatus::Superseded;
2225        if let Err(e) = state.save_under(home) {
2226            tracing::warn!("could not mark run {id} superseded: {e:#}");
2227        }
2228    }
2229}
2230
2231/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2232/// finish the moment it was called, because one of its earlier attempts was
2233/// still live then - a `magi run --resume` invoked by hand on an old run,
2234/// most likely.
2235///
2236/// That skip is correct at the time (rewriting under a run something is
2237/// still actively saving would just be undone), but recording a completion
2238/// does not schedule another settlement, so without this nothing would look at it
2239/// again: if that manual process later ends anywhere other than
2240/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2241/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2242/// backlog this status exists to clear. Called on the same idle-only
2243/// cadence as [`janitor`], next to it rather than folded into it: this
2244/// walks `queue` and `janitor` never otherwise needs one.
2245///
2246/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2247/// more than one attempt, every pass: each call is a handful of local file
2248/// reads bounded by that task's own attempt count, the same order of cost
2249/// [`clean::fold_due`] already pays scanning every run on disk on the same
2250/// cadence, and a task already fully resolved costs one failed liveness
2251/// check turned no-op the moment its lingering attempt is no longer live.
2252fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2253    for task in queue.list() {
2254        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2255            continue;
2256        }
2257        supersede_prior_runs(&task, home);
2258    }
2259}
2260
2261/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2262/// task ends up held.
2263///
2264/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2265/// dead daemon never got back to) share this, so the two cannot drift into
2266/// disagreeing about which held tasks get a diagnostic.
2267fn settle_and_diagnose(
2268    task: &mut Task,
2269    verdict: Verdict,
2270    detail: &str,
2271    max_attempts: usize,
2272    state: &RunState,
2273) {
2274    let mut verdict = verdict;
2275    let mut detail = detail;
2276    if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2277        // Never allow an inconsistent or unsupported `VerifiedNoop` run state
2278        // to bypass settlement into a no-change handoff, and never rewrite the
2279        // historical run record on disk: settle the task as an ordinary failure.
2280        verdict.status = RunStatus::Failed;
2281        verdict.quota_hit = false;
2282        detail = "no-change result lacks verified evidence";
2283    }
2284    let p = phrases(&state.config.graph.language);
2285    // Shared by normal completion and crash recovery, under the task claim.
2286    // No new attempt can own the task until the old driver has exited.
2287    if let Some(d) = &state.merge_decision {
2288        use crate::merge_decision as md;
2289        if task
2290            .execution_runs()
2291            .last()
2292            .is_some_and(|id| id != &state.id)
2293        {
2294            return;
2295        }
2296        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2297            if task.investigation && task.current_investigation_result().is_none() {
2298                task.hold_unrequested_retry(Some(
2299                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2300                        .into(),
2301                ));
2302            } else {
2303                task.succeed(CompletionContext::from_run(
2304                    CompletionActor::DaemonSettle,
2305                    Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2306                    task,
2307                    state,
2308                ));
2309            }
2310        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2311            if state.liveness(false) != Liveness::Dead {
2312                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2313                return;
2314            }
2315            let replacement = md::Replacement {
2316                question: d.question.clone(),
2317                run: state.id.clone(),
2318                pr: d.target.pr.clone(),
2319                agent: agent.to_owned(),
2320                context: format!(
2321                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2322                    d.target.pr,
2323                    state.id,
2324                    serde_json::to_string(&state.reviews).unwrap_or_default()
2325                ),
2326            };
2327            task.requeue();
2328            task.pr_recovery = None;
2329            task.review_of = None;
2330            task.replacement = Some(replacement);
2331        } else {
2332            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2333                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2334            } 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())) }));
2335        }
2336        task.mark_action_applied(&d.question);
2337        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2338            task.decision_effects
2339                .insert(d.question.clone(), format!("decision: {}", d.choice));
2340        }
2341        if let Some(pass) = state.passes.last() {
2342            task.record_pass_at(
2343                &state.id,
2344                pass.index,
2345                Some(pass.started_at),
2346                task.attempts,
2347                None,
2348            );
2349        }
2350        return;
2351    }
2352    if let Some(replacement) = &task.replacement
2353        && !state.parked
2354        && state.resource_block.is_none()
2355        && (state.viable().is_empty()
2356            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2357    {
2358        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)));
2359        return;
2360    }
2361    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2362        let mut agents: Vec<_> = state
2363            .quota
2364            .iter()
2365            .filter(|q| {
2366                q.cause == crate::agent::QuotaCause::Authentication
2367                    && state
2368                        .passes
2369                        .last()
2370                        .is_none_or(|pass| q.at >= pass.started_at)
2371            })
2372            .map(|q| q.agent.as_str())
2373            .collect();
2374        agents.sort_unstable();
2375        agents.dedup();
2376        if !agents.is_empty() {
2377            task.stall(detail);
2378            task.notice_cause("agent-authentication", None, None);
2379            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2380            return;
2381        }
2382    }
2383    let attempts_before = task.attempts;
2384    // A run that stopped because a shared resource stayed busy was never a
2385    // failure of the task or of an agent. Earlier nodes may have run; only
2386    // the blocked operation lacks a result. The attempt is
2387    // refunded and the task is held by the machine, under a reason `triage`
2388    // can re-check, so the same run resumes with the same agents once the
2389    // resource is free. A park request still wins (it is the operator's).
2390    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2391        let disk_checked_at = task.disk_checked_at;
2392        task.notice_cause(
2393            &format!("resource:{}:{}", block.kind, block.node),
2394            None,
2395            None,
2396        );
2397        task.last_error = Some(detail.to_owned());
2398        task.diagnostic = None;
2399        task.attempts = task.attempts.saturating_sub(1);
2400        if block.kind == "agent authentication" {
2401            task.hold_machine(Some(format!(
2402                "[authentication] {}; no attempt was spent",
2403                block.detail
2404            )));
2405        } else if block.kind == "agent usage limit" {
2406            // Usage limits keep the existing cooldown-and-resume policy.
2407            if let Some(agent) = &state.config.graph.selected_implementer {
2408                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.")));
2409            } else {
2410                task.status = TaskStatus::Failed;
2411                task.last_error = Some(block.detail.clone());
2412            }
2413        } else if block.kind == "disk pressure" {
2414            task.hold_machine(Some(format!(
2415                "{}{}",
2416                crate::disk::RUNNING_PRESSURE,
2417                block.detail
2418            )));
2419        } else {
2420            task.hold_machine(Some(format!(
2421                "{}{}; no attempt was spent; resume to retry the affected operation",
2422                crate::cache::RESOURCE_HOLD,
2423                block.description()
2424            )));
2425        }
2426        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2427            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2428        {
2429            task.mark_disk_capacity();
2430            task.disk_checked_at = disk_checked_at;
2431        }
2432        if let Some(pass) = state.passes.last() {
2433            task.record_pass_at(
2434                &state.id,
2435                pass.index,
2436                Some(pass.started_at),
2437                attempts_before,
2438                None,
2439            );
2440        }
2441        return;
2442    }
2443    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2444        state.parked
2445            && state.status == RunStatus::Landing
2446            && state
2447                .pr_pushed_head
2448                .as_ref()
2449                .is_none_or(|h| h == &hold.head)
2450            && task.execution_runs().last() == Some(&state.id)
2451    }) {
2452        // Settlement and crash recovery share this idempotency key. A later
2453        // explicit resume is a new pass and may refund its own attempt once.
2454        let pass = state.passes.last().map_or(0, |p| p.index);
2455        if !task
2456            .passes
2457            .iter()
2458            .any(|p| p.run == state.id && p.pass_index == pass)
2459        {
2460            task.attempts = task.attempts.saturating_sub(1);
2461        }
2462        task.hold_machine(Some(format!(
2463            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2464            hold.question
2465        )));
2466        task.last_error = Some(detail.to_owned());
2467        task.diagnostic = None;
2468        task.record_pass_at(
2469            &state.id,
2470            pass,
2471            state.passes.last().map(|p| p.started_at),
2472            attempts_before,
2473            Some(crate::run::ParkCause::Question),
2474        );
2475        return;
2476    }
2477    let unresolved = task.hold_notice_cause.clone();
2478    let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2479        .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2480    let mut reconsumed_head_e2e = false;
2481    if state.base_sync_blocked() {
2482        // No automatic retry may turn a retained sync stop into a new competition.
2483        task.hold_machine(Some(detail.to_owned()));
2484        task.last_error = Some(detail.to_owned());
2485    } else if state.land_sync_exhausted() {
2486        task.hold_machine(Some(format!("{detail} {}", state.land_sync_next_action())));
2487        task.last_error = Some(detail.to_owned());
2488    } else if !verdict.parked
2489        && task
2490            .pr_recovery
2491            .as_ref()
2492            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2493        && matches!(
2494            verdict.status,
2495            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2496        )
2497    {
2498        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2499            if task.investigation && task.current_investigation_result().is_none() {
2500                task.hold_unrequested_retry(Some(
2501                    "Investigation finished without recorded findings; complete it with a nonblank --result."
2502                        .into(),
2503                ));
2504            } else {
2505                task.succeed(CompletionContext::from_run(
2506                    CompletionActor::DaemonSettle,
2507                    Some(detail.to_owned()),
2508                    task,
2509                    state,
2510                ));
2511            }
2512        } else {
2513            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()));
2514        }
2515    } else if !verdict.parked
2516        && task.pr_recovery.is_some()
2517        && matches!(
2518            verdict.status,
2519            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2520        )
2521        && !verdict.quota_hit
2522    {
2523        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.")));
2524    } else if let Some(stop) = head_e2e_stop.clone() {
2525        // Conclusive current-head E2E red settles directly to one actionable
2526        // machine hold instead of cycling through runnable `Failed` passes.
2527        // Refund only when this pass provably reconsumed an earlier stop with
2528        // no new verification events, idempotently across reclaim/re-settle.
2529        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2530            reconsumed_head_e2e = true;
2531            let pass = state.passes.last().map_or(0, |p| p.index);
2532            if !task
2533                .passes
2534                .iter()
2535                .any(|p| p.run == state.id && p.pass_index == pass)
2536            {
2537                task.attempts = task.attempts.saturating_sub(1);
2538            }
2539        }
2540        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2541        task.hold_head_e2e(stop, reason, detail.to_owned());
2542    } else {
2543        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2544    }
2545    if !verdict.parked
2546        && !verdict.quota_hit
2547        && !reconsumed_head_e2e
2548        && matches!(
2549            verdict.status,
2550            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2551        )
2552    {
2553        task.recovery_failed(state);
2554    }
2555    if state.prep_failure.is_some() {
2556        // Minting a run whose candidates could not be prepared is not work
2557        // on a newly approved attempt. Keep the unresolved outcome anchor.
2558        task.hold_notice_cause = unresolved;
2559        task.startup_notice_cause("startup-candidates");
2560    }
2561    // Written here, where the refund (or not) is decided, so the history is a
2562    // fact and not a later guess from the run's status.
2563    if let Some(pass) = state.passes.last() {
2564        let parked = match &pass.end {
2565            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2566            _ => None,
2567        };
2568        task.record_pass_at(
2569            &state.id,
2570            pass.index,
2571            Some(pass.started_at),
2572            attempts_before,
2573            parked,
2574        );
2575    }
2576    if task.status == TaskStatus::Held {
2577        if state.base_sync_blocked() {
2578            task.base_sync_notice(state);
2579        } else if state.land_sync_exhausted() {
2580            task.land_sync_notice(state);
2581        } else if let Some(stop) = &head_e2e_stop {
2582            task.head_e2e_notice(stop);
2583        } else if task.has_awaiting_landing_cause() {
2584            task.notice_cause(
2585                "awaiting-landing",
2586                Some(&state.id),
2587                state.passes.last().map(|p| p.index),
2588            );
2589        } else if state.prep_failure.is_none() {
2590            task.notice_cause(
2591                label(verdict.status),
2592                Some(&state.id),
2593                state.passes.last().map(|p| p.index),
2594            );
2595        }
2596        if !task.has_awaiting_landing_cause() {
2597            task.diagnostic = diagnostic(state);
2598        }
2599        note_open_question(task, &state.id, p);
2600    }
2601}
2602
2603/// If `task` is held with a `magi ask` question still open on `run`, name the
2604/// question in [`Task::hold_reason`] rather than leaving the hold reading
2605/// only [`describe`]'s run summary.
2606///
2607/// This is the shape task 20260928-191407-05fd left underspecified: an
2608/// implementer settled a verified no-op and filed a question for the
2609/// operator, and the hold that followed said nothing about the question
2610/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2611/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2612/// marker) and must keep seeing it unchanged.
2613///
2614/// Best-effort: an unreadable question store must not stop a run from
2615/// settling, so this is a no-op rather than a propagated error when
2616/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2617fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2618    let Some(home) = crate::run::try_home() else {
2619        return;
2620    };
2621    let open = Questions::at(home.join("questions")).open_for(run);
2622    let Some(q) = open.first() else {
2623        return;
2624    };
2625    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2626    decisions.sort_unstable();
2627    task.notice_cause(
2628        &format!("questions:{}", decisions.join(",")),
2629        Some(run),
2630        None,
2631    );
2632    let base = task.hold_reason.clone().unwrap_or_default();
2633    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2634}
2635
2636/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2637/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2638/// by some other means entirely, like a manual `magi run` resume that
2639/// finishes the graph outside the queue's bookkeeping.
2640///
2641/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2642/// `settle` is separate from `attempt`: a task recovered this way must land
2643/// exactly where a live daemon would have put it — the same policy table,
2644/// not a second one that quietly drifts from it — and that is only checkable
2645/// without spawning a real run.
2646fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2647    if let Some(request) = task.sync_only.clone() {
2648        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2649        return;
2650    }
2651    match last_run {
2652        Some(state) => {
2653            let verdict = Verdict {
2654                status: state.status,
2655                left_pr: state.pr.is_some(),
2656                quota_hit: state.quota.iter().any(|loss| {
2657                    state
2658                        .passes
2659                        .last()
2660                        .is_none_or(|pass| loss.at >= pass.started_at)
2661                }),
2662                parked: state.parked,
2663                no_viable_candidates: state.viable().is_empty(),
2664            };
2665            let detail = format!(
2666                "{}{}",
2667                phrases(&state.config.graph.language).recovered_running,
2668                describe(&state)
2669            );
2670            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2671        }
2672        None => {
2673            // No run, so no config of its own: `language` is the task's
2674            // repository's setting, read by the caller.
2675            let why = phrases(language).no_run_to_recover;
2676            task.last_error = Some(why.to_owned());
2677            // The phone shows `hold_reason`, so a task held by the machine
2678            // says why there too and not only in `last_error`.
2679            task.notice_cause("missing-run", None, None);
2680            task.hold_machine(Some(why.to_owned()));
2681        }
2682    }
2683}
2684
2685/// Find every task left at `running` that no live process is actually
2686/// driving, and settle each one against whatever its last run became.
2687///
2688/// # Why a claim is proof, not a guess
2689///
2690/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2691/// `running`, and the guard is held for the task's whole time in that status:
2692/// `attempt` does not return, and the loop does not move past the scope
2693/// holding the claim, until the run has settled. So a `running` task whose
2694/// lock is gone cannot have a live owner — this process or any other —
2695/// without needing a staleness threshold or a pid check the way
2696/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2697/// task that never got as far as `running` at all. Taking the claim here is
2698/// the whole test: it either fails, because something really does hold it
2699/// and the task is left alone, or it succeeds, which is the proof — and it is
2700/// kept for the rest of the decision so nothing else can start a competing
2701/// run while this one is being written.
2702///
2703/// Called on every poll, not only at startup, for the reason
2704/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2705/// keep noticing this, not only on the one morning it happened to restart.
2706fn reclaim_orphaned_running(
2707    queue: &Queue,
2708    max_attempts: usize,
2709    live_workers: &std::collections::BTreeSet<String>,
2710) -> Vec<String> {
2711    let mut reclaimed = Vec::new();
2712    for listed in queue.list() {
2713        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2714            continue;
2715        }
2716        let Ok(_claim) = queue.claim(&listed.id) else {
2717            continue;
2718        };
2719        // Re-read under the claim: a release or an edit landed by a human
2720        // between the listing above and the claim just taken must not be
2721        // clobbered by a decision based on the stale copy.
2722        let Ok(mut task) = queue.get(&listed.id) else {
2723            continue;
2724        };
2725        if task.status != TaskStatus::Running {
2726            continue;
2727        }
2728        let last_run = task
2729            .execution_runs()
2730            .last()
2731            .and_then(|id| RunState::load(id).ok());
2732        // `execute` normally abandons a run's own open questions the moment
2733        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2734        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2735        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2736        // with the question still `open`, because the process died before
2737        // reaching that call. `reclaim` itself stays pure on purpose (see its
2738        // own doc), so the same cleanup runs here instead, against the run
2739        // this reclaim is already reading. `settle_run` costs nothing when
2740        // `execute` already got there first.
2741        if let Some(state) = &last_run
2742            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2743        {
2744            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2745        }
2746        let language = if last_run.is_none() {
2747            language_of(&task, Path::new("."))
2748        } else {
2749            String::new()
2750        };
2751        reclaim(&mut task, last_run, max_attempts, &language);
2752        if task.status == TaskStatus::Done {
2753            supersede_prior_runs(&task, &crate::run::home());
2754        }
2755        record(queue, &mut task);
2756        reclaimed.push(task.id.clone());
2757    }
2758    reclaimed
2759}
2760
2761/// Find every run whose `run.json` is provably dead — every seat it still
2762/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2763/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2764/// not merely "no daemon claims it" — and fail it, clearing the leftover
2765/// active seats so the run stops reading as `implementing` (or whichever
2766/// node) forever.
2767///
2768/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2769/// `running`, using whatever `run.json` already says — but nothing in that
2770/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2771/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2772/// never got back to sits exactly where it was left: `active` full of seats
2773/// nobody will ever answer for, `status` stuck on whatever node was in
2774/// flight. `magi show` already tells an operator this in prose (`no live
2775/// daemon claims this run right now`); this is what makes that fact durable
2776/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2777/// stay stuck once nothing is driving it.
2778///
2779/// Runs on every poll, not only at startup, for the reason
2780/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2781/// daemon up for days must keep noticing a run some other, now-dead, daemon
2782/// left behind just as readily as one it trips over on the way up.
2783///
2784/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2785/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2786/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2787/// `runs` directory instead: `home` here is a parameter precisely so a test
2788/// can point it away from the operator's real history (see [`drive`]'s own
2789/// doc), and a scan that fell through to the global home anyway would walk
2790/// whichever directory some *other* process or test pinned into that
2791/// `OnceLock` first — mutating runs this call was never handed.
2792fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2793    reclaim_abandoned_runs_with(
2794        home,
2795        now,
2796        crate::proc::pid_status,
2797        crate::proc::process_started_at,
2798    )
2799}
2800
2801/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2802/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2803/// for the identical reason: this sweep's real damage (wiping a run's active
2804/// seats and failing it) has to be provable against an injected answer in a
2805/// test, not just the real process table.
2806fn reclaim_abandoned_runs_with<F, G>(
2807    home: &Path,
2808    now: Timestamp,
2809    query: F,
2810    identity: G,
2811) -> Vec<String>
2812where
2813    F: Fn(u32) -> Option<bool>,
2814    G: Fn(u32) -> Option<String>,
2815{
2816    let mut abandoned = Vec::new();
2817    for entry in std::fs::read_dir(home.join("runs"))
2818        .into_iter()
2819        .flatten()
2820        .flatten()
2821    {
2822        let id = entry.file_name().to_string_lossy().into_owned();
2823        if !crate::run::is_run_id(&id) {
2824            continue;
2825        }
2826        // Serialize the proof and save with claims and takeover: a new
2827        // execution must not be overwritten after the liveness observation.
2828        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2829            continue;
2830        };
2831        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2832        // that module's docs for why a run this cannot parse is left alone
2833        // rather than guessed at. A different schema number is not that: this
2834        // touches only `status` and `active`, never a field whose meaning a
2835        // schema bump changed, so an old record's values serve this exactly
2836        // as well as a current one's (see `clean::read_state`'s own doc for
2837        // the same reasoning applied to folding).
2838        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2839            continue;
2840        };
2841        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2842            continue;
2843        };
2844        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2845            continue;
2846        }
2847        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2848        // it", which is also the normal, healthy shape of a manual `magi
2849        // run` / `magi review` sharing this same home — this scan walks
2850        // every run on disk, not only ones this daemon itself started. Such
2851        // a run's active seats can legitimately sit past their own timeout
2852        // for a little while (the CLI finishing up, its result still being
2853        // collected) without the process driving it having died. `liveness`
2854        // is what actually tells the two apart, by corroborating
2855        // `driver_pid` against the process it names — see its own doc. Only
2856        // its strongest, provable answer licenses wiping this run's active
2857        // seats and failing it out from under whatever is still running it.
2858        let daemon_claims = is_working_on(home, &id, now);
2859        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2860            != crate::run::Liveness::Dead
2861        {
2862            continue;
2863        }
2864        state.abandon("daemon");
2865        if let Err(e) = state.save_under(home) {
2866            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2867            continue;
2868        }
2869        // This run never passes through `Runner::execute` again, so its end
2870        // is announced here.
2871        if let Some(notice) = notices::run_ended(&state) {
2872            notices::raise_in(home, notice);
2873        }
2874        // The seat that asked is gone for good now, exactly like any other
2875        // door `graph::Runner::settle_questions` closes the moment `status`
2876        // lands somewhere non-resumable - see that method's own doc. Nothing
2877        // else reaches this one before the next `janitor()` startup pass
2878        // (`clean::abandon_settled_questions`), and a daemon that stays up
2879        // for days must not leave an open question badging the operator
2880        // until it happens to restart.
2881        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2882            tracing::warn!("abandon questions for {id}: {e:#}");
2883        }
2884        abandoned.push(id);
2885    }
2886    abandoned
2887}
2888
2889#[derive(Debug, Clone, Serialize, Deserialize)]
2890struct TaskWorker {
2891    opts: Opts,
2892    queue: PathBuf,
2893    task: String,
2894    #[serde(default)]
2895    lane: PermitKind,
2896    #[serde(default)]
2897    standalone: bool,
2898}
2899
2900#[doc(hidden)]
2901pub struct TaskWorkerLease {
2902    pub job: crate::worker::Job,
2903    dir: PathBuf,
2904    lease: Option<crate::worker::Lease>,
2905}
2906
2907impl TaskWorkerLease {
2908    pub fn release_lease(&mut self) {
2909        self.lease = None;
2910    }
2911}
2912
2913impl Drop for TaskWorkerLease {
2914    fn drop(&mut self) {
2915        self.release_lease();
2916        let _ = std::fs::remove_dir_all(&self.dir);
2917    }
2918}
2919
2920/// Reserve a task worker without launching a process, for integration tests.
2921#[doc(hidden)]
2922pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2923    let request = TaskWorker {
2924        opts: Opts::default(),
2925        queue: home.join("queue"),
2926        task: task.to_owned(),
2927        lane: PermitKind::default(),
2928        standalone: true,
2929    };
2930    let (job, lease) = crate::worker::running_fixture(
2931        home,
2932        &format!("task:{task}"),
2933        serde_json::to_value(request)?,
2934    )?;
2935    Ok(TaskWorkerLease {
2936        dir: home.join("workers").join("jobs").join(&job.id),
2937        job,
2938        lease: Some(lease),
2939    })
2940}
2941
2942fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2943    Ok(crate::worker::active(home)?
2944        .into_iter()
2945        .filter(|job| job.kind == "task")
2946        .collect())
2947}
2948
2949fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2950    task_jobs(home)?
2951        .into_iter()
2952        .filter_map(
2953            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2954                Ok(request) if !request.standalone => Some(Ok(job)),
2955                Ok(_) => None,
2956                Err(error) => Some(Err(error.into())),
2957            },
2958        )
2959        .collect()
2960}
2961
2962/// Whether an independent scheduler can be controlled without its web parent.
2963#[must_use]
2964pub fn managed(home: &Path) -> bool {
2965    match crate::worker::active(home) {
2966        Err(error) => {
2967            tracing::error!("cannot determine scheduler ownership: {error:#}");
2968            true
2969        }
2970        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2971        Ok(_) => {
2972            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2973                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2974        }
2975    }
2976}
2977
2978/// Start a detached, singleton scheduler using this executable generation.
2979pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2980    anyhow::ensure!(
2981        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2982        "the scheduler is stopping; wait for retirement before starting it again"
2983    );
2984    crate::worker::spawn(
2985        home,
2986        "scheduler",
2987        "scheduler",
2988        serde_json::to_value(opts.absolute()?)?,
2989    )
2990    .await
2991}
2992
2993fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2994    home.join("worker-parks").join(format!("{}.json", job.id))
2995}
2996
2997fn request_task_park(
2998    home: &Path,
2999    job: &crate::worker::Job,
3000    cause: crate::run::ParkCause,
3001) -> Result<()> {
3002    let path = park_request_path(home, job);
3003    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
3004    std::fs::write(path, serde_json::to_vec(&cause)?)?;
3005    crate::worker::request(home, &job.key, crate::worker::Control::Park)
3006}
3007
3008/// Stop dispatch immediately; only an explicit park reaches existing workers.
3009pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
3010    if control == crate::worker::Control::Park {
3011        for job in owned_task_jobs(home)? {
3012            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
3013        }
3014    }
3015    crate::worker::request(home, "scheduler", control)
3016}
3017
3018/// Resolve what a restart would replace without signalling the scheduler.
3019pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
3020    if let Some(job) = crate::worker::active(home)?
3021        .into_iter()
3022        .find(|job| job.kind == "scheduler")
3023    {
3024        return serde_json::from_value(job.payload)
3025            .context("read detached scheduler options")
3026            .map(Some);
3027    }
3028    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
3029        && crate::worker::try_lease(home, "scheduler")?.is_none()
3030    {
3031        let path = home.join("scheduler-options.json");
3032        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
3033        return serde_json::from_slice(&body)
3034            .context("decode detached scheduler options")
3035            .map(Some);
3036    }
3037    Ok(None)
3038}
3039
3040/// Replace the scheduler, leaving all active task and conversation jobs alone.
3041pub async fn restart_detached(home: &Path) -> Result<()> {
3042    let Some(opts) = scheduler_restart_options(home)? else {
3043        return Ok(());
3044    };
3045    request_control(home, crate::worker::Control::Stop)?;
3046    loop {
3047        let reserved = crate::worker::active(home)?
3048            .iter()
3049            .any(|job| job.kind == "scheduler");
3050        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
3051            break;
3052        }
3053        tokio::time::sleep(Duration::from_millis(100)).await;
3054    }
3055    spawn_detached(home, &opts).await?;
3056    Ok(())
3057}
3058
3059/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
3060pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3061    let opts: Opts = serde_json::from_value(payload)?;
3062    let _ = home;
3063    serve_until(opts, Stop::new()).await
3064}
3065
3066/// Execute and settle one task with the queue claim owned by this process.
3067pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
3068    let request: TaskWorker = serde_json::from_value(payload)?;
3069    let queue = Queue::at(request.queue);
3070    let key = format!("task:{}", request.task);
3071    let job = task_jobs(home)?
3072        .into_iter()
3073        .find(|job| job.key == key)
3074        .context("task worker reservation is missing")?;
3075    let park_path = park_request_path(home, &job);
3076    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
3077    // our durable reservation. Never execute before that ownership hand-off.
3078    let _claim = loop {
3079        match queue.claim(&request.task) {
3080            Ok(claim) => break claim,
3081            Err(e) if e.is::<crate::queue::InstructionAdoptionPending>() => return Ok(()),
3082            // Only contention (the claim file exists) is worth waiting out; an
3083            // I/O failure must end this worker instead of pinning its lane.
3084            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
3085                return Err(e.context("claim the task for its worker"));
3086            }
3087            Err(_) => {
3088                sweep_stale_claims(&queue, STALE_CLAIM);
3089                tokio::time::sleep(Duration::from_millis(50)).await;
3090            }
3091        }
3092    };
3093    let mut task = queue.get(&request.task)?;
3094    if !task.status.runnable()
3095        || (!request.standalone
3096            && request.lane
3097                != permit_kind(
3098                    land_resume_state(&task) == LandResume::Ready,
3099                    task.immediate,
3100                    task.urgent,
3101                ))
3102    {
3103        return Ok(());
3104    }
3105    let stop = Stop::new();
3106    let watcher = {
3107        let home = home.to_path_buf();
3108        let stop = stop.clone();
3109        let park_path = park_path.clone();
3110        tokio::spawn(async move {
3111            loop {
3112                if crate::worker::control(&home, &key).ok().flatten().is_some() {
3113                    let cause = std::fs::read(&park_path)
3114                        .ok()
3115                        .and_then(|body| serde_json::from_slice(&body).ok())
3116                        .unwrap_or(crate::run::ParkCause::Operator);
3117                    stop.park(cause);
3118                    // Publication of the control precedes delivery to the
3119                    // pause handle. Record delivery for observers.
3120                    if let Err(error) = std::fs::write(park_path.with_extension("ack"), "") {
3121                        tracing::warn!("could not record park delivery: {error}");
3122                    }
3123                    return;
3124                }
3125                tokio::time::sleep(Duration::from_millis(200)).await;
3126            }
3127        })
3128    };
3129    let quota = if request.standalone {
3130        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3131    } else {
3132        let status = Arc::new(Mutex::new(Status::new()));
3133        Box::pin(attempt(
3134            &request.opts,
3135            &queue,
3136            &status,
3137            &stop,
3138            crate::graph::Pause::new(),
3139            &mut task,
3140        ))
3141        .await
3142    };
3143    watcher.abort();
3144    let _ = watcher.await;
3145    let _ = std::fs::remove_file(park_path.with_extension("ack"));
3146    let _ = std::fs::remove_file(park_path);
3147    persist_cooldown(home, &quota).await?;
3148    Ok(())
3149}
3150
3151/// Launch the standalone task worker with a claim-to-reservation handoff.
3152/// Returns only after the worker owns a durable execution reservation.
3153pub async fn spawn_claimed(
3154    home: &Path,
3155    opts: &Opts,
3156    queue: &Queue,
3157    task: &Task,
3158    claim: crate::queue::Claim,
3159) -> Result<crate::worker::Job> {
3160    let request = TaskWorker {
3161        opts: opts.absolute()?,
3162        queue: std::path::absolute(queue.root())?,
3163        task: task.id.clone(),
3164        lane: permit_kind(
3165            land_resume_state(task) == LandResume::Ready,
3166            task.immediate,
3167            task.urgent,
3168        ),
3169        standalone: true,
3170    };
3171    let job = crate::worker::spawn(
3172        home,
3173        "task",
3174        &format!("task:{}", task.id),
3175        serde_json::to_value(request)?,
3176    )
3177    .await?;
3178    drop(claim);
3179    Ok(job)
3180}
3181
3182/// Transfer a standalone caller's claim only after the detached worker is live,
3183/// then follow that worker to its final (non-automatically-retrying) outcome.
3184pub async fn run_detached_claimed(
3185    opts: &Opts,
3186    queue: &Queue,
3187    task: &mut Task,
3188    claim: crate::queue::Claim,
3189) -> Result<()> {
3190    let home = crate::run::home();
3191    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3192    loop {
3193        // Reconcile execution leases even without a scheduler. A dead worker
3194        // must become a reported failure, never an infinite persisted wait.
3195        crate::worker::active(&home)?;
3196        let current = crate::worker::get(&home, &job.id)?;
3197        if matches!(
3198            current.status,
3199            crate::worker::Status::Finished | crate::worker::Status::Failed
3200        ) {
3201            *task = queue.get(&task.id)?;
3202            anyhow::ensure!(
3203                current.status != crate::worker::Status::Failed,
3204                "task worker failed: {}",
3205                current.result.as_deref().unwrap_or("unknown failure")
3206            );
3207            return Ok(());
3208        }
3209        tokio::time::sleep(Duration::from_millis(200)).await;
3210    }
3211}
3212
3213async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3214    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3215        let _lease = loop {
3216            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3217                break lease;
3218            }
3219            tokio::time::sleep(Duration::from_millis(10)).await;
3220        };
3221        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3222            let path = home.join("task-quota-cooldown.json");
3223            let temporary = path.with_extension("json.tmp");
3224            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3225            std::fs::rename(temporary, path)?;
3226        }
3227    }
3228    Ok(())
3229}
3230
3231fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3232    match std::fs::read(home.join("task-quota-cooldown.json")) {
3233        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3234        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3235        Err(error) => Err(error.into()),
3236    }
3237}
3238
3239/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3240///
3241/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3242/// sets, so there is one loop body rather than two that drift apart the first
3243/// time the retry policy changes on only one of them.
3244pub async fn serve(opts: Opts) -> Result<()> {
3245    tracing::info!(
3246        "automatic update and restart requires magi web; standalone serve does not restart"
3247    );
3248    serve_until(opts, Stop::new()).await
3249}
3250
3251/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3252///
3253/// A stop retires dispatch promptly, including while a worker launch is being
3254/// acknowledged. Already reserved workers own their attempts independently and
3255/// finish with their started executable. Explicit park additionally forwards
3256/// durable park requests; neither scheduler retirement nor update does so.
3257///
3258/// While the queue is empty the stop is honoured within one wakeup rather than
3259/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3260/// caller that taps stop does not sit through the remainder of a sleep.
3261pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3262    let opts = opts.absolute()?;
3263    let home = crate::run::home();
3264    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3265        .context("another scheduler already owns this home")?;
3266    if let Some(reading) = read_status(&home)
3267        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3268    {
3269        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3270    }
3271    if !crate::worker::active(&home)?
3272        .iter()
3273        .any(|job| job.kind == "scheduler")
3274    {
3275        crate::worker::clear_control(&home, "scheduler")?;
3276    }
3277    std::fs::write(
3278        home.join("scheduler-options.json"),
3279        serde_json::to_vec(&opts)?,
3280    )?;
3281    let control = {
3282        let home = home.clone();
3283        let stop = stop.clone();
3284        tokio::spawn(async move {
3285            loop {
3286                match crate::worker::control(&home, "scheduler").ok().flatten() {
3287                    Some(crate::worker::Control::Park) => {
3288                        let _ = request_control(&home, crate::worker::Control::Park);
3289                        stop.park(crate::run::ParkCause::Operator);
3290                        break;
3291                    }
3292                    Some(crate::worker::Control::Stop) => {
3293                        stop.stop();
3294                        break;
3295                    }
3296                    None => {}
3297                }
3298                tokio::time::sleep(Duration::from_millis(100)).await;
3299            }
3300        })
3301    };
3302    let signal = {
3303        let stop = stop.clone();
3304        tokio::spawn(async move {
3305            if tokio::signal::ctrl_c().await.is_ok() {
3306                stop.stop();
3307                tracing::info!("scheduler shutdown requested; independent workers continue");
3308            }
3309        })
3310    };
3311
3312    let worktrees_root = opts
3313        .worktrees_root
3314        .clone()
3315        .unwrap_or_else(crate::run::default_worktree_root);
3316    let outcome = drive(
3317        &opts,
3318        &Queue::open(),
3319        &status_path(),
3320        &crate::run::home(),
3321        &worktrees_root,
3322        &stop,
3323    )
3324    .await;
3325
3326    signal.abort();
3327    control.abort();
3328    outcome
3329}
3330
3331/// The loop proper: setup, poll, teardown, with the queue and the status file
3332/// supplied rather than discovered.
3333///
3334/// All three of `home`, `worktrees_root` and the queue/status paths are
3335/// parameters rather than resolved here, for the same reason:
3336/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3337/// so a unit test that pinned it would fight every other test in the binary,
3338/// and a loop that resolved its own worktree bay could only be exercised
3339/// against the operator's real `~/wt/<repo>` - publishing over a live
3340/// daemon's status file, claiming tasks out of a live backlog, and, since
3341/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3342/// whatever the operator actually has on disk.
3343async fn drive(
3344    opts: &Opts,
3345    queue: &Queue,
3346    status_file: &Path,
3347    home: &Path,
3348    worktrees_root: &Path,
3349    stop: &Stop,
3350) -> Result<()> {
3351    // The status file is a *snapshot*, not a stream of events: a reader only
3352    // ever wants the latest values, and every tick rewrites the whole file
3353    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3354    // while an mpsc channel would force the loop to re-send unchanged fields on
3355    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3356    // for no gain. The lock is only ever held across a field assignment, never
3357    // across an await.
3358    let recovery_cfg = prepare(&opts.repo, opts).ok();
3359    let daemon_cfg = recovery_cfg
3360        .as_ref()
3361        .map(|c| c.daemon.clone())
3362        .unwrap_or_default();
3363    let reconciled = crate::driver::reconcile(home);
3364    if !reconciled.is_empty() {
3365        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3366    }
3367    let mut initial_status = Status::new();
3368    let owned = owned_task_jobs(home)?;
3369    initial_status.current = current_work(home, Timestamp::now())
3370        .into_iter()
3371        .filter(|current| {
3372            owned
3373                .iter()
3374                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3375        })
3376        .collect();
3377    initial_status.idle = initial_status.current.is_empty();
3378    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3379        recovery_cfg.as_ref(),
3380        daemon_cfg.max_deputies,
3381    ));
3382    let status = Arc::new(Mutex::new(initial_status));
3383    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3384    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3385
3386    // Read once at startup, not per task: how many runs this loop drives at
3387    // once is a property of the machine running it, not of whichever
3388    // repository a given task happens to name - see
3389    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3390    // fact in the same sense the agent roster is.
3391    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3392
3393    tracing::info!(
3394        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3395        queue.root().display(),
3396        opts.poll.as_secs(),
3397        opts.max_attempts,
3398        concurrency,
3399        if daemon_cfg.pause_for_interrupts {
3400            ", interrupts enabled"
3401        } else {
3402            ""
3403        }
3404    );
3405
3406    let outcome = tokio::select! {
3407        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3408            max_concurrent: concurrency,
3409            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3410            recovery_cfg,
3411        }) => outcome,
3412        () = async {
3413            while !stop.stopped() {
3414                tokio::time::sleep(Duration::from_millis(25)).await;
3415            }
3416        } => {
3417            if stop.parking() {
3418                request_control(home, crate::worker::Control::Park)?;
3419            }
3420            Ok(())
3421        }
3422    };
3423
3424    stop.busy.store(0, Ordering::SeqCst);
3425    beat.abort();
3426    clear_status_at(status_file);
3427    outcome
3428}
3429
3430/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3431/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3432pub(crate) fn release_watch_settings_from_config(
3433    home: &Path,
3434    repo: &Path,
3435    cfg: &Config,
3436) -> (Vec<PathBuf>, u64) {
3437    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3438        .into_iter()
3439        .map(|r| r.path)
3440        .collect();
3441    // Repositories the daemon has worked in, wherever they live: a task may
3442    // name one outside `[repos] roots`, and its release PR must be watched too.
3443    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3444        .list()
3445        .into_iter()
3446        .map(|t| t.repo)
3447        .collect();
3448    let runs = home.join("runs");
3449    for id in crate::run::list_ids_in(&runs) {
3450        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3451            .ok()
3452            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3453            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3454        known.extend(repo);
3455    }
3456    for k in known {
3457        let k = k.canonicalize().unwrap_or(k);
3458        if k.join(".git").exists() && !paths.contains(&k) {
3459            paths.push(k);
3460        }
3461    }
3462    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3463    if !paths.contains(&own) {
3464        paths.push(own);
3465    }
3466    (paths, cfg.daemon.release_stall_minutes)
3467}
3468
3469/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3470const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3471
3472/// Refresh the status file on a fixed tick.
3473///
3474/// Separate from the loop because a run takes tens of minutes: a status file
3475/// written only between tasks would look stale for the whole of every run, and
3476/// a reader would report the daemon dead exactly while it was busiest.
3477async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3478    loop {
3479        tokio::time::sleep(HEARTBEAT).await;
3480        let snapshot = {
3481            let mut guard = lock(&status);
3482            guard.updated_at = Timestamp::now();
3483            guard.clone()
3484        };
3485        if let Err(e) = write_status_to(&path, &snapshot) {
3486            // A failed heartbeat must not take the daemon down: the loop is the
3487            // product, the status file is only the window onto it.
3488            tracing::warn!("could not refresh the daemon status file: {e:#}");
3489        }
3490    }
3491}
3492
3493/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3494/// if so, whether that wait is over.
3495#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3496enum LandResume {
3497    /// The task's last run is not parked on a land approval; schedule it
3498    /// like any other candidate.
3499    NotLanding,
3500    /// Parked in `land`, waiting on a question nobody has answered yet.
3501    /// Left alone: attempting it now would only re-observe the same pull
3502    /// request and park again, spending a `gh` call on a decision that has
3503    /// not changed since the last time this was checked.
3504    StillWaiting,
3505    /// Parked in `land`, and the question is settled - answered or
3506    /// abandoned. Resuming this is the one kind of candidate that must not
3507    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3508    Ready,
3509}
3510
3511/// Classify a runnable candidate by whether it is parked on a land-merge
3512/// approval. Read-only - no claim taken, nothing written - so it is cheap
3513/// enough to call on every candidate, every poll.
3514fn land_resume_state(task: &Task) -> LandResume {
3515    if task.sync_only.is_some() {
3516        return LandResume::NotLanding;
3517    }
3518    let Some(run_id) = task.execution_runs().last() else {
3519        return LandResume::NotLanding;
3520    };
3521    let Ok(state) = RunState::load(run_id) else {
3522        return LandResume::NotLanding;
3523    };
3524    if !state.parked {
3525        return LandResume::NotLanding;
3526    }
3527    if state.status == RunStatus::Landing
3528        && state.land_approval.as_ref().is_some_and(|binding| {
3529            ask::Questions::open()
3530                .get_for_effects(&binding.question)
3531                .is_ok_and(|q| {
3532                    q.run == state.id
3533                        && q.resolution()
3534                            .as_deref()
3535                            .is_some_and(crate::merge_decision::stops)
3536                })
3537        })
3538    {
3539        return LandResume::Ready;
3540    }
3541    if !implementers_match(task, &state) {
3542        return LandResume::NotLanding;
3543    }
3544    // Parked in `land` on the merge approval, or at `merge` on the owner's
3545    // word about a title/body the posting gate withheld. Told apart by the
3546    // run's own record, not by a status both can share.
3547    let node = if state.status == RunStatus::Landing {
3548        land::APPROVAL_NODE
3549    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3550        crate::github_text::ASK_NODE
3551    } else {
3552        return LandResume::NotLanding;
3553    };
3554    let store = ask::Questions::open();
3555    let waiting = store
3556        .list_for_effects()
3557        .into_iter()
3558        .filter(|q| &q.run == run_id && q.node == node)
3559        .max_by(|a, b| a.id.cmp(&b.id));
3560    let Some(mut q) = waiting else {
3561        return LandResume::Ready;
3562    };
3563    if !q.status.open() {
3564        // Repair spends agent resources and must obey concurrency and quota
3565        // waits; only a merge/hold decision may use the decision-only lane.
3566        if q.resolution().as_deref() == Some(land::REPAIR) {
3567            return if state.liveness(false) == Liveness::Live {
3568                LandResume::StillWaiting
3569            } else {
3570                LandResume::NotLanding
3571            };
3572        }
3573        return LandResume::Ready;
3574    }
3575    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3576    // nobody ever answered; land's approval bypasses that wait entirely (see
3577    // `land::approval_gate`), so the same deadline has to be enforced here
3578    // instead, or `graph.answer_timeout` silently stops meaning anything for
3579    // a land approval and a run can sit `StillWaiting` forever with nobody
3580    // told to look at it.
3581    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3582    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3583    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3584        q.abandon(format!(
3585            "no answer within {}s of asking",
3586            timeout.as_secs().max(1)
3587        ));
3588        // If this can't be persisted, do not treat the wait as settled on a
3589        // guess: fall through and try again next poll.
3590        if store.put(&mut q).is_ok() {
3591            return LandResume::Ready;
3592        }
3593    }
3594    LandResume::StillWaiting
3595}
3596
3597/// How often the loop rechecks for new work while something it already
3598/// started is still running, rather than sleeping out the whole
3599/// [`Opts::poll`] interval.
3600///
3601/// Short on purpose: this is what lets a land-merge approval that comes back
3602/// while another task is mid-competition be noticed and resumed within a
3603/// fraction of a second, not within the next multi-second poll.
3604const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3605
3606/// How often [`poll`] rechecks the shared build cache against its cap at a
3607/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3608/// waiting for the queue to run dry.
3609///
3610/// A queue that never empties means the `janitor` call at the bottom of this
3611/// loop's fully-idle branch can go unreached for as long as the backlog
3612/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3613/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3614/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3615/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3616/// backlog of short tasks does not pay for that walk on every poll.
3617const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3618
3619/// State of [`poll`]'s own interrupt-scheduling sequence - see
3620/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3621/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3622/// both kept free of `Task`'s non-identity fields on purpose: every decision
3623/// here turns only on task ids and which ones are in flight, so the "never
3624/// more than one run at once" and "exactly one resume" invariants can be
3625/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3626/// queue - which is exactly the coverage this feature's first two attempts
3627/// were missing.
3628///
3629/// Persisted after every transition, so scheduler replacement preserves the
3630/// interrupt's exclusive turn and the interrupted task's priority resume.
3631#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3632enum Interrupt {
3633    /// No interrupt sequence in progress. Ordinary dispatch applies.
3634    Idle,
3635    /// `interrupt_task` is runnable and exactly one other run is in flight;
3636    /// `parked` names that one task's id. Dispatch is withheld from
3637    /// everyone, including `interrupt_task` itself, until it has left
3638    /// flight - only then is `interrupt_task` let through.
3639    ///
3640    /// `parked` is a `Vec` rather than a bare id for symmetry with
3641    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3642    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3643    /// when exactly one run is in flight, so it is guaranteed to hold
3644    /// exactly one entry in practice - see that branch's own doc for why
3645    /// more than one is deliberately never attempted.
3646    Parking {
3647        parked: Vec<String>,
3648        interrupt_task: String,
3649    },
3650    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3651    /// withheld from everyone until it leaves flight - merged, failed, held,
3652    /// it makes no difference - at which point the sequence moves to
3653    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3654    /// going straight to `Idle` would hand `parked` back to ordinary
3655    /// priority-order dispatch, where a higher-priority task filed in the
3656    /// meantime could start ahead of it.
3657    Running {
3658        parked: Vec<String>,
3659        interrupt_task: String,
3660    },
3661    /// `interrupt_task` left flight; `parked` still names the one run this
3662    /// sequence owes a resume. Dispatch is withheld from everyone except
3663    /// that task - see [`interrupt_gate`] - so the resume this feature
3664    /// promises is never raced by, or run alongside, an unrelated candidate.
3665    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3666    /// own doc on abandonment - the moment it is no longer runnable at all.
3667    Resuming { parked: Vec<String> },
3668}
3669
3670/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3671/// and `runnable` are read-only snapshots of this tick's reality, and the
3672/// only side effect the caller still owes the world is asking whichever
3673/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3674/// site.
3675///
3676/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3677/// accepted rather than a narrower type because that is what [`poll`] already
3678/// has on hand from [`runnable`], and building a second, smaller list on
3679/// every tick just to satisfy this signature would cost more than it proves.
3680///
3681/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3682/// back to a task they are waiting on no longer being [`runnable`] - held,
3683/// blocked, deleted, or finished by some other means entirely, all of which
3684/// an operator can do to a task sitting in the queue with no claim on it at
3685/// all, at any moment, interrupt sequence or not. Without this check the
3686/// sequence would wait forever for a dispatch that can never come, and
3687/// `interrupt_gate` would withhold every other task in the queue right along
3688/// with it - a single `magi task hold` on the wrong id turning into a
3689/// daemon that never dispatches anything again.
3690fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3691    match state {
3692        Interrupt::Idle => {
3693            // Not just "something to interrupt": exactly one thing. More
3694            // than one run in flight only happens above the default
3695            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3696            // one resume, never run alongside anything else" only because
3697            // it is only ever seeded with exactly one id - see
3698            // `Interrupt::Resuming`'s own doc on why releasing more than one
3699            // parked id back to ordinary dispatch cannot be made safe
3700            // against that same setting's own extra concurrency slots.
3701            // Waiting here for the herd to settle to one is the
3702            // simplification this feature's own constraints ask for rather
3703            // than a second concurrency model to reconcile with the first.
3704            if in_flight.len() != 1 {
3705                return Interrupt::Idle;
3706            }
3707            match runnable.iter().find(|t| t.interrupt) {
3708                Some(t) => Interrupt::Parking {
3709                    parked: in_flight.to_vec(),
3710                    interrupt_task: t.id.clone(),
3711                },
3712                None => Interrupt::Idle,
3713            }
3714        }
3715        Interrupt::Parking {
3716            parked,
3717            interrupt_task,
3718        } => {
3719            if in_flight.iter().any(|id| parked.contains(id)) {
3720                // Still waiting for what was in flight to actually stop.
3721                Interrupt::Parking {
3722                    parked,
3723                    interrupt_task,
3724                }
3725            } else if in_flight.contains(&interrupt_task) {
3726                Interrupt::Running {
3727                    parked,
3728                    interrupt_task,
3729                }
3730            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3731                // The parked run(s) are gone, but the interrupt task has not
3732                // been dispatched yet on this tick - `interrupt_gate` is
3733                // what lets it through next.
3734                Interrupt::Parking {
3735                    parked,
3736                    interrupt_task,
3737                }
3738            } else {
3739                // The interrupt task itself is no longer runnable - see this
3740                // function's own doc on abandonment. The parked run(s) still
3741                // get their guaranteed resume; there is simply no interrupt
3742                // to run ahead of them any longer.
3743                Interrupt::Resuming { parked }
3744            }
3745        }
3746        Interrupt::Running {
3747            parked,
3748            interrupt_task,
3749        } => {
3750            if in_flight.contains(&interrupt_task) {
3751                Interrupt::Running {
3752                    parked,
3753                    interrupt_task,
3754                }
3755            } else {
3756                // The interrupt task's own run reached a terminal status,
3757                // whichever one - this is the *only* trigger that moves the
3758                // sequence on, driven straight off the same in-flight
3759                // bookkeeping `poll` already reaps every tick, not a second,
3760                // independent poll of anything.
3761                Interrupt::Resuming { parked }
3762            }
3763        }
3764        Interrupt::Resuming { parked } => {
3765            if in_flight.iter().any(|id| parked.contains(id)) {
3766                // One of the parked runs has been dispatched - the resume
3767                // this sequence owed is fulfilled. Whatever else is left in
3768                // `parked` (ordinarily nothing, at the default concurrency
3769                // of one) rejoins ordinary priority-order dispatch, same as
3770                // any other runnable task.
3771                Interrupt::Idle
3772            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3773                Interrupt::Resuming { parked }
3774            } else {
3775                // Abandonment (see this function's own doc): nothing left in
3776                // `parked` is even runnable any longer.
3777                Interrupt::Idle
3778            }
3779        }
3780    }
3781}
3782
3783/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3784/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3785/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3786/// indistinguishable from any other runnable task - exactly the "off does
3787/// nothing" this feature promises.
3788fn advance_interrupt_tick(
3789    enabled: bool,
3790    state: Interrupt,
3791    in_flight: &[String],
3792    runnable: &[Task],
3793) -> Interrupt {
3794    if !enabled {
3795        return Interrupt::Idle;
3796    }
3797    advance_interrupt(state, in_flight, runnable)
3798}
3799
3800/// Which of this tick's runnable candidates the interrupt sequence actually
3801/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3802/// each half is assertable on its own: this is the half that keeps a
3803/// competition and an interrupt from ever running at the same moment.
3804fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3805    match state {
3806        Interrupt::Idle => candidates,
3807        Interrupt::Parking {
3808            parked,
3809            interrupt_task,
3810        } => {
3811            if in_flight.iter().any(|id| parked.contains(id)) {
3812                Vec::new()
3813            } else {
3814                candidates
3815                    .into_iter()
3816                    .filter(|t| &t.id == interrupt_task)
3817                    .collect()
3818            }
3819        }
3820        Interrupt::Running { .. } => Vec::new(),
3821        // At most one: even if `parked` names more than one id (more than
3822        // one run was in flight when the sequence began, only possible
3823        // above the default `max_concurrent_runs = 1`), only the first match
3824        // is offered. Capping this to a single candidate - not merely to
3825        // `parked`'s own ids - is what makes "exactly one resume, never two
3826        // dispatched together" true regardless of how many ordinary slots
3827        // happen to be free this tick.
3828        Interrupt::Resuming { parked } => candidates
3829            .into_iter()
3830            .find(|t| parked.contains(&t.id))
3831            .into_iter()
3832            .collect(),
3833    }
3834}
3835
3836/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3837/// bundled into one parameter so `poll`'s own signature stays readable -
3838/// see [`drive`]'s call site for where these are actually read.
3839struct DispatchLimits {
3840    /// How many *ordinary* candidates run at once. See
3841    /// [`crate::config::Daemon::max_concurrent_runs`].
3842    max_concurrent: usize,
3843    /// See [`crate::config::Daemon::pause_for_interrupts`].
3844    pause_for_interrupts: bool,
3845    recovery_cfg: Option<Config>,
3846}
3847
3848/// Which semaphore, if any, dispatching a candidate should draw its permit
3849/// from.
3850///
3851/// Pure and separate from [`poll`]'s loop body for the same reason
3852/// [`advance_interrupt`] is: the choice between "decision-only land resume",
3853/// "owner-selected immediate lane", "spend the one urgent slot" and "spend an
3854/// ordinary slot" is explicit and directly unit-testable.
3855#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3856pub(crate) enum PermitKind {
3857    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3858    /// Checked first - a task can be both a land resume and marked
3859    /// [`Task::immediate`] or [`Task::urgent`], and the resume's own
3860    /// decision-only lane takes precedence.
3861    None,
3862    /// [`Task::immediate`]: owner-selected immediate execution lane.
3863    /// Consumes no semaphore permit and does not count against ordinary or
3864    /// urgent capacity, allowing multiple immediate tasks to dispatch even
3865    /// when both ordinary and urgent lanes are full. Kept distinct from
3866    /// [`PermitKind::None`] so decision-only resumes and immediate runs stay
3867    /// separable in persisted worker reservations and diagnostics.
3868    Immediate,
3869    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3870    /// (never in addition to trying) the ordinary pool. This is what lets
3871    /// an urgent task dispatch while every ordinary slot is already checked
3872    /// out, and what stops a second urgent task from opening a third run: it
3873    /// waits on this same one-slot semaphore rather than falling through to
3874    /// the ordinary one.
3875    Urgent,
3876    /// The ordinary `max_concurrent_runs` pool - unaffected by any of the
3877    /// above.
3878    #[default]
3879    Ordinary,
3880}
3881
3882impl PermitKind {
3883    pub(crate) fn label(self) -> &'static str {
3884        match self {
3885            Self::None => "decision",
3886            Self::Immediate => "immediate",
3887            Self::Urgent => "urgent",
3888            Self::Ordinary => "ordinary",
3889        }
3890    }
3891}
3892
3893/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3894/// own boolean, already computed by the caller from [`land_resume_state`].
3895/// Precedence: decision resume (`None`) > `Immediate` > `Urgent` > `Ordinary`.
3896fn permit_kind(priority: bool, immediate: bool, urgent: bool) -> PermitKind {
3897    if priority {
3898        PermitKind::None
3899    } else if immediate {
3900        PermitKind::Immediate
3901    } else if urgent {
3902        PermitKind::Urgent
3903    } else {
3904        PermitKind::Ordinary
3905    }
3906}
3907
3908fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3909    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3910        (0usize, 0usize),
3911        |(ordinary, urgent), request| match request.lane {
3912            PermitKind::Ordinary => (ordinary + 1, urgent),
3913            PermitKind::Urgent => (ordinary, urgent + 1),
3914            PermitKind::Immediate | PermitKind::None => (ordinary, urgent),
3915        },
3916    );
3917    (
3918        limit.saturating_sub(ordinary),
3919        1usize.saturating_sub(urgent),
3920    )
3921}
3922
3923/// Why a runnable candidate was not dispatched. This does not alter policy.
3924#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3925enum SkipReason {
3926    ClaimUnavailable,
3927    RereadFailed,
3928    NoLongerRunnable,
3929    WaitingOnLanding,
3930    CoolingDown,
3931    OrdinaryCapacity,
3932    UrgentCapacity,
3933    InterruptGate,
3934}
3935
3936impl SkipReason {
3937    fn key(self) -> &'static str {
3938        match self {
3939            Self::ClaimUnavailable => "claim_unavailable",
3940            Self::RereadFailed => "reread_failed",
3941            Self::NoLongerRunnable => "no_longer_runnable",
3942            Self::WaitingOnLanding => "waiting_on_landing",
3943            Self::CoolingDown => "cooling_down",
3944            Self::OrdinaryCapacity => "ordinary_capacity",
3945            Self::UrgentCapacity => "urgent_capacity",
3946            Self::InterruptGate => "interrupt_gate",
3947        }
3948    }
3949
3950    fn describe(self) -> &'static str {
3951        match self {
3952            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3953            Self::RereadFailed => "could not re-read it",
3954            Self::NoLongerRunnable => "no longer runnable",
3955            Self::WaitingOnLanding => "waiting on landing",
3956            Self::CoolingDown => "quota cooldown",
3957            Self::OrdinaryCapacity => "no free ordinary slot",
3958            Self::UrgentCapacity => "urgent slot busy",
3959            Self::InterruptGate => "withheld by the interrupt sequence",
3960        }
3961    }
3962}
3963
3964/// A reason count from a completed dispatch scan.
3965#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3966pub struct DispatchReasonCount {
3967    /// Stable string key, so readers can preserve future reasons.
3968    pub reason: String,
3969    /// Candidates skipped for this reason.
3970    pub count: usize,
3971}
3972
3973/// Observations from a completed scan, not a fresh queue estimate.
3974#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3975pub struct DispatchWait {
3976    /// Runnable candidates before the interrupt gate.
3977    pub runnable: usize,
3978    /// Counts in descending order, with stable reason order for ties.
3979    pub reasons: Vec<DispatchReasonCount>,
3980}
3981
3982type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3983
3984fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3985    if runnable == 0 {
3986        return None;
3987    }
3988    let mut counts = std::collections::BTreeMap::new();
3989    for (_, reason) in skips {
3990        *counts.entry(*reason).or_insert(0usize) += 1;
3991    }
3992    let mut counts: Vec<_> = counts.into_iter().collect();
3993    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3994    Some(DispatchWait {
3995        runnable,
3996        reasons: counts
3997            .into_iter()
3998            .map(|(reason, count)| DispatchReasonCount {
3999                reason: reason.key().to_owned(),
4000                count,
4001            })
4002            .collect(),
4003    })
4004}
4005
4006fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
4007    before
4008        .iter()
4009        .filter(|id| !after.iter().any(|task| &task.id == *id))
4010        .map(|id| (id.clone(), SkipReason::InterruptGate))
4011        .collect()
4012}
4013
4014fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
4015    if *previous == current {
4016        return false;
4017    }
4018    *previous = current;
4019    true
4020}
4021
4022/// Read-only task-level admission view shared by CLI (`magi task list` / `show`)
4023/// and Web (`TaskView`). Distinguishes configured mode, active persisted
4024/// reservation lane, and concrete blockers without ever mutating state.
4025#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
4026pub struct TaskAdmission {
4027    /// Configured dispatch mode from the task record (`"immediate"`, `"urgent"`, `"ordinary"`).
4028    pub mode: &'static str,
4029    /// Persisted active worker reservation lane, if currently reserved/running
4030    /// (`"decision"`, `"immediate"`, `"urgent"`, `"ordinary"`).
4031    #[serde(default, skip_serializing_if = "Option::is_none")]
4032    pub reservation_lane: Option<&'static str>,
4033    /// True when the active worker reservation is standalone (`magi run`/`review`).
4034    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
4035    pub standalone: bool,
4036    /// Admission state: `"next_poll"`, `"waiting"`, `"running"`, `"completed"`, `"unknown"`.
4037    pub state: &'static str,
4038    /// Human-readable admission status label (e.g. `"Immediate: next poll"`,
4039    /// `"Immediate: waiting — ..."`).
4040    pub label: String,
4041    /// Concrete blocker or unconfirmed-state diagnostic when waiting/unknown/resource-blocked.
4042    #[serde(default, skip_serializing_if = "Option::is_none")]
4043    pub blocker: Option<String>,
4044}
4045
4046/// One read-only snapshot of scheduler, worker, cooldown, and interrupt state
4047/// captured once per list or detail request.
4048#[derive(Debug, Clone)]
4049pub struct AdmissionSnapshot {
4050    now: Timestamp,
4051    daemon: std::result::Result<Option<Reading>, String>,
4052    scheduler_running: bool,
4053    active_workers:
4054        std::result::Result<std::collections::BTreeMap<String, (PermitKind, bool)>, String>,
4055    owned_in_flight: Vec<String>,
4056    owned_ordinary_count: usize,
4057    urgent_busy: bool,
4058    cache_service_active: bool,
4059    cooldown_until: std::result::Result<Option<Timestamp>, String>,
4060    interrupt: std::result::Result<Interrupt, String>,
4061}
4062
4063fn read_status_checked(home: &Path) -> std::result::Result<Option<Reading>, String> {
4064    let path = home.join("daemon.json");
4065    match std::fs::read_to_string(&path) {
4066        Ok(body) => serde_json::from_str(&body)
4067            .map(Some)
4068            .map_err(|e| format!("parse {}: {e}", path.display())),
4069        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
4070        Err(e) => Err(format!("read {}: {e}", path.display())),
4071    }
4072}
4073
4074fn read_interrupt_checked(home: &Path) -> std::result::Result<Interrupt, String> {
4075    let path = home.join("scheduler-interrupt.json");
4076    match std::fs::read(&path) {
4077        Ok(body) => {
4078            serde_json::from_slice(&body).map_err(|e| format!("parse {}: {e}", path.display()))
4079        }
4080        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Interrupt::Idle),
4081        Err(e) => Err(format!("read {}: {e}", path.display())),
4082    }
4083}
4084
4085fn skip_reason_label(key: &str) -> String {
4086    match key {
4087        "claim_unavailable" => "claimed by another process".to_owned(),
4088        "reread_failed" => "could not re-read task".to_owned(),
4089        "no_longer_runnable" => "no longer runnable".to_owned(),
4090        "waiting_on_landing" => "waiting on merge/posting approval".to_owned(),
4091        "cooling_down" => "quota cooldown".to_owned(),
4092        "ordinary_capacity" => "no free ordinary slot".to_owned(),
4093        "urgent_capacity" => "urgent slot busy".to_owned(),
4094        "interrupt_gate" => "withheld by active interrupt sequence".to_owned(),
4095        other => other.replace('_', " "),
4096    }
4097}
4098
4099/// Pure read-only companion to [`land_resume_state`]: reads `home` explicitly
4100/// and never abandons or writes any question file.
4101fn land_resume_state_readonly(task: &Task, home: &Path, now: Timestamp) -> LandResume {
4102    if task.sync_only.is_some() {
4103        return LandResume::NotLanding;
4104    }
4105    let Some(run_id) = task.execution_runs().last() else {
4106        return LandResume::NotLanding;
4107    };
4108    let Ok(state) = RunState::load_under(run_id, home) else {
4109        return LandResume::NotLanding;
4110    };
4111    if !state.parked {
4112        return LandResume::NotLanding;
4113    }
4114    let store = ask::Questions::at(home.join("questions"));
4115    if state.status == RunStatus::Landing
4116        && state.land_approval.as_ref().is_some_and(|binding| {
4117            store.get_for_effects(&binding.question).is_ok_and(|q| {
4118                q.run == state.id
4119                    && q.resolution()
4120                        .as_deref()
4121                        .is_some_and(crate::merge_decision::stops)
4122            })
4123        })
4124    {
4125        return LandResume::Ready;
4126    }
4127    if !implementers_match(task, &state) {
4128        return LandResume::NotLanding;
4129    }
4130    let node = if state.status == RunStatus::Landing {
4131        land::APPROVAL_NODE
4132    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
4133        crate::github_text::ASK_NODE
4134    } else {
4135        return LandResume::NotLanding;
4136    };
4137    let waiting = store
4138        .list_for_effects()
4139        .into_iter()
4140        .filter(|q| &q.run == run_id && q.node == node)
4141        .max_by(|a, b| a.id.cmp(&b.id));
4142    let Some(q) = waiting else {
4143        return LandResume::Ready;
4144    };
4145    if !q.status.open() {
4146        if q.resolution().as_deref() == Some(land::REPAIR) {
4147            return if is_working_on(home, &state.id, now) {
4148                LandResume::StillWaiting
4149            } else {
4150                LandResume::NotLanding
4151            };
4152        }
4153        return LandResume::Ready;
4154    }
4155    LandResume::StillWaiting
4156}
4157
4158impl AdmissionSnapshot {
4159    /// Capture scheduler, worker, cooldown, and interrupt state once, read-only.
4160    #[must_use]
4161    pub fn capture(home: &Path, now: Timestamp) -> Self {
4162        let daemon = read_status_checked(home);
4163        let scheduler_running = daemon
4164            .as_ref()
4165            .ok()
4166            .and_then(Option::as_ref)
4167            .is_some_and(|reading| reading.running(now));
4168        let mut cache_service_active = false;
4169        let mut owned_in_flight = Vec::new();
4170        let mut owned_ordinary_count = 0usize;
4171        let mut urgent_busy = false;
4172        let active_workers = match crate::worker::observe_active_detailed(home) {
4173            Ok(entries) => {
4174                let mut map = std::collections::BTreeMap::new();
4175                let mut parse_err = None;
4176                for entry in entries {
4177                    if entry.job.key == "service:daemon-cache" {
4178                        cache_service_active = true;
4179                        continue;
4180                    }
4181                    if entry.job.kind != "task" {
4182                        continue;
4183                    }
4184                    match serde_json::from_value::<TaskWorker>(entry.job.payload) {
4185                        Ok(request) => {
4186                            if !request.standalone {
4187                                owned_in_flight.push(request.task.clone());
4188                                match request.lane {
4189                                    PermitKind::Ordinary => owned_ordinary_count += 1,
4190                                    PermitKind::Urgent => urgent_busy = true,
4191                                    PermitKind::Immediate | PermitKind::None => {}
4192                                }
4193                            }
4194                            map.entry(request.task)
4195                                .and_modify(|existing: &mut (PermitKind, bool)| {
4196                                    if existing.1 && !request.standalone {
4197                                        *existing = (request.lane, request.standalone);
4198                                    }
4199                                })
4200                                .or_insert((request.lane, request.standalone));
4201                        }
4202                        Err(e) => {
4203                            parse_err = Some(format!(
4204                                "invalid task worker payload for {}: {e}",
4205                                entry.job.id
4206                            ));
4207                            break;
4208                        }
4209                    }
4210                }
4211                match parse_err {
4212                    Some(err) => Err(err),
4213                    None => Ok(map),
4214                }
4215            }
4216            Err(e) => Err(format!("{e:#}")),
4217        };
4218        let cooldown_until = read_cooldown(home).map_err(|e| format!("{e:#}"));
4219        let interrupt = read_interrupt_checked(home);
4220        Self {
4221            now,
4222            daemon,
4223            scheduler_running,
4224            active_workers,
4225            owned_in_flight,
4226            owned_ordinary_count,
4227            urgent_busy,
4228            cache_service_active,
4229            cooldown_until,
4230            interrupt,
4231        }
4232    }
4233
4234    fn format_waiting(task: &Task, reason: &str) -> String {
4235        if task.immediate {
4236            format!("Immediate: waiting — {reason}")
4237        } else if task.urgent {
4238            format!("Urgent: waiting — {reason}")
4239        } else {
4240            format!("Waiting — {reason}")
4241        }
4242    }
4243
4244    /// Evaluate admission for `task` using this pre-captured snapshot.
4245    /// Read-only: never mutates queue, run, worker, or question files.
4246    #[must_use]
4247    pub fn evaluate(
4248        &self,
4249        task: &Task,
4250        queue: &Queue,
4251        inv: Option<&crate::blockers::Inventory>,
4252        home: &Path,
4253    ) -> TaskAdmission {
4254        let mode = if task.immediate {
4255            "immediate"
4256        } else if task.urgent {
4257            "urgent"
4258        } else {
4259            "ordinary"
4260        };
4261
4262        if task.status == TaskStatus::Done {
4263            return TaskAdmission {
4264                mode,
4265                reservation_lane: None,
4266                standalone: false,
4267                state: "completed",
4268                label: "Completed".to_owned(),
4269                blocker: None,
4270            };
4271        }
4272
4273        if let Ok(workers) = &self.active_workers
4274            && let Some(&(lane, standalone)) = workers.get(&task.id)
4275        {
4276            let lane_label = lane.label();
4277            let base = if standalone {
4278                format!("Running (standalone, {lane_label} lane)")
4279            } else {
4280                format!("Running ({lane_label} lane)")
4281            };
4282            let resource_blocker = task
4283                .execution_runs()
4284                .last()
4285                .and_then(|run_id| RunState::load_under(run_id, home).ok())
4286                .and_then(|state| state.resource_wait)
4287                .map(|wait| {
4288                    if wait.holder.trim().is_empty() {
4289                        format!("waiting for {}", wait.kind)
4290                    } else {
4291                        format!("waiting for {} ({})", wait.kind, wait.holder)
4292                    }
4293                });
4294            let label = match &resource_blocker {
4295                Some(reason) => format!("{base} — {reason}"),
4296                None => base,
4297            };
4298            return TaskAdmission {
4299                mode,
4300                reservation_lane: Some(lane_label),
4301                standalone,
4302                state: "running",
4303                label,
4304                blocker: resource_blocker,
4305            };
4306        }
4307
4308        if task.status == TaskStatus::Running {
4309            if self.active_workers.is_err() {
4310                let reason = "worker state unreadable".to_owned();
4311                return TaskAdmission {
4312                    mode,
4313                    reservation_lane: None,
4314                    standalone: false,
4315                    state: "unknown",
4316                    label: Self::format_waiting(task, &reason),
4317                    blocker: Some(reason),
4318                };
4319            }
4320            return TaskAdmission {
4321                mode,
4322                reservation_lane: None,
4323                standalone: false,
4324                state: "running",
4325                label: "Running".to_owned(),
4326                blocker: None,
4327            };
4328        }
4329
4330        if task.status == TaskStatus::Blocked {
4331            let waits = inv.map(|i| i.waits_on(task)).unwrap_or_default();
4332            let reason = if !waits.is_empty() {
4333                format!("waiting on dependencies ({})", waits.join(", "))
4334            } else if let Some(block_reason) = &task.block_reason {
4335                format!("blocked ({block_reason})")
4336            } else if !task.blocked_by.is_empty() {
4337                let ids: Vec<_> = task
4338                    .blocked_by
4339                    .iter()
4340                    .map(|id| crate::run::short_of(id))
4341                    .collect();
4342                format!("waiting on dependencies ({})", ids.join(", "))
4343            } else {
4344                "blocked on unresolved dependencies".to_owned()
4345            };
4346            return TaskAdmission {
4347                mode,
4348                reservation_lane: None,
4349                standalone: false,
4350                state: "waiting",
4351                label: Self::format_waiting(task, &reason),
4352                blocker: Some(reason),
4353            };
4354        }
4355
4356        if task.status == TaskStatus::Held {
4357            let reason = match &task.machine_hold_cause {
4358                Some(crate::queue::MachineHoldCause::DiskCapacity { reason, .. }) => {
4359                    format!("disk admission ({reason})")
4360                }
4361                Some(crate::queue::MachineHoldCause::HeadE2e { .. }) => {
4362                    let detail = task
4363                        .hold_reason
4364                        .as_deref()
4365                        .unwrap_or("current head verify.e2e failed");
4366                    format!("head e2e hold ({detail})")
4367                }
4368                Some(crate::queue::MachineHoldCause::AwaitingLanding { reason, .. }) => {
4369                    format!("awaiting landing ({reason})")
4370                }
4371                None if task.hold_source == Some(crate::queue::HoldSource::Machine) => {
4372                    let detail = task.hold_reason.as_deref().unwrap_or("held by daemon");
4373                    if let Some(rest) = detail.strip_prefix("[resource] ") {
4374                        format!("resource hold ({rest})")
4375                    } else if let Some(rest) = detail.strip_prefix("[config] ") {
4376                        format!("config hold ({rest})")
4377                    } else {
4378                        format!("machine hold ({detail})")
4379                    }
4380                }
4381                None => match task.hold_reason.as_deref() {
4382                    Some(reason) if !reason.trim().is_empty() => format!("held ({reason})"),
4383                    _ => "held (release required)".to_owned(),
4384                },
4385            };
4386            return TaskAdmission {
4387                mode,
4388                reservation_lane: None,
4389                standalone: false,
4390                state: "waiting",
4391                label: Self::format_waiting(task, &reason),
4392                blocker: Some(reason),
4393            };
4394        }
4395
4396        // Runnable (`Queued` | `Failed` | `Parked`): evaluate non-concurrency
4397        // gates first, never claiming dispatchability on unconfirmed state and
4398        // never attributing ordinary/urgent capacity waits to immediate tasks.
4399        if self.active_workers.is_err() {
4400            let reason = "worker state unreadable".to_owned();
4401            return TaskAdmission {
4402                mode,
4403                reservation_lane: None,
4404                standalone: false,
4405                state: "unknown",
4406                label: Self::format_waiting(task, &reason),
4407                blocker: Some(reason),
4408            };
4409        }
4410
4411        if queue.is_claimed(&task.id) {
4412            let reason = "claimed by another process".to_owned();
4413            return TaskAdmission {
4414                mode,
4415                reservation_lane: None,
4416                standalone: false,
4417                state: "waiting",
4418                label: Self::format_waiting(task, &reason),
4419                blocker: Some(reason),
4420            };
4421        }
4422
4423        if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, task) {
4424            let reason = format!("head e2e stop ({})", hold.reason);
4425            return TaskAdmission {
4426                mode,
4427                reservation_lane: None,
4428                standalone: false,
4429                state: "waiting",
4430                label: Self::format_waiting(task, &reason),
4431                blocker: Some(reason),
4432            };
4433        }
4434
4435        let resume = land_resume_state_readonly(task, home, self.now);
4436        if resume == LandResume::StillWaiting {
4437            let reason = "waiting on merge/posting approval".to_owned();
4438            return TaskAdmission {
4439                mode,
4440                reservation_lane: None,
4441                standalone: false,
4442                state: "waiting",
4443                label: Self::format_waiting(task, &reason),
4444                blocker: Some(reason),
4445            };
4446        }
4447        let priority = resume == LandResume::Ready;
4448        let effective_lane = permit_kind(priority, task.immediate, task.urgent);
4449
4450        match &self.interrupt {
4451            Err(_) => {
4452                let reason = "interrupt state unreadable".to_owned();
4453                return TaskAdmission {
4454                    mode,
4455                    reservation_lane: None,
4456                    standalone: false,
4457                    state: "unknown",
4458                    label: Self::format_waiting(task, &reason),
4459                    blocker: Some(reason),
4460                };
4461            }
4462            Ok(interrupt)
4463                if *interrupt != Interrupt::Idle
4464                    && interrupt_gate(interrupt, &self.owned_in_flight, vec![task.clone()])
4465                        .is_empty() =>
4466            {
4467                let reason = "withheld by active interrupt sequence".to_owned();
4468                return TaskAdmission {
4469                    mode,
4470                    reservation_lane: None,
4471                    standalone: false,
4472                    state: "waiting",
4473                    label: Self::format_waiting(task, &reason),
4474                    blocker: Some(reason),
4475                };
4476            }
4477            Ok(_) => {}
4478        }
4479
4480        if effective_lane != PermitKind::None {
4481            match &self.cooldown_until {
4482                Err(_) => {
4483                    let reason = "quota cooldown state unreadable".to_owned();
4484                    return TaskAdmission {
4485                        mode,
4486                        reservation_lane: None,
4487                        standalone: false,
4488                        state: "unknown",
4489                        label: Self::format_waiting(task, &reason),
4490                        blocker: Some(reason),
4491                    };
4492                }
4493                Ok(Some(until)) if self.now < *until => {
4494                    let secs = (until.as_second() - self.now.as_second()).max(1);
4495                    let reason = format!("quota cooldown ({secs}s remaining)");
4496                    return TaskAdmission {
4497                        mode,
4498                        reservation_lane: None,
4499                        standalone: false,
4500                        state: "waiting",
4501                        label: Self::format_waiting(task, &reason),
4502                        blocker: Some(reason),
4503                    };
4504                }
4505                Ok(_) => {}
4506            }
4507        }
4508
4509        if self.cache_service_active {
4510            let reason = "waiting for cache maintenance service".to_owned();
4511            return TaskAdmission {
4512                mode,
4513                reservation_lane: None,
4514                standalone: false,
4515                state: "waiting",
4516                label: Self::format_waiting(task, &reason),
4517                blocker: Some(reason),
4518            };
4519        }
4520
4521        if self.daemon.is_err() {
4522            let reason = "scheduler status unreadable".to_owned();
4523            return TaskAdmission {
4524                mode,
4525                reservation_lane: None,
4526                standalone: false,
4527                state: "unknown",
4528                label: Self::format_waiting(task, &reason),
4529                blocker: Some(reason),
4530            };
4531        }
4532
4533        if self.scheduler_running
4534            && let Ok(Some(reading)) = &self.daemon
4535            && let Some(skip_key) = reading.dispatch_skips.get(&task.id)
4536        {
4537            let stale_capacity_skip = match effective_lane {
4538                PermitKind::None | PermitKind::Immediate => {
4539                    matches!(skip_key.as_str(), "ordinary_capacity" | "urgent_capacity")
4540                }
4541                PermitKind::Urgent => skip_key == "ordinary_capacity",
4542                PermitKind::Ordinary => skip_key == "urgent_capacity",
4543            };
4544            if !stale_capacity_skip {
4545                let reason = skip_reason_label(skip_key);
4546                return TaskAdmission {
4547                    mode,
4548                    reservation_lane: None,
4549                    standalone: false,
4550                    state: "waiting",
4551                    label: Self::format_waiting(task, &reason),
4552                    blocker: Some(reason),
4553                };
4554            }
4555        }
4556
4557        if !self.scheduler_running {
4558            let reason = "scheduler not running".to_owned();
4559            return TaskAdmission {
4560                mode,
4561                reservation_lane: None,
4562                standalone: false,
4563                state: "waiting",
4564                label: Self::format_waiting(task, &reason),
4565                blocker: Some(reason),
4566            };
4567        }
4568
4569        match effective_lane {
4570            PermitKind::Immediate => TaskAdmission {
4571                mode,
4572                reservation_lane: None,
4573                standalone: false,
4574                state: "next_poll",
4575                label: "Immediate: next poll".to_owned(),
4576                blocker: None,
4577            },
4578            PermitKind::None => TaskAdmission {
4579                mode,
4580                reservation_lane: None,
4581                standalone: false,
4582                state: "next_poll",
4583                label: if task.immediate {
4584                    "Immediate: next poll".to_owned()
4585                } else {
4586                    "Decision resume: next poll".to_owned()
4587                },
4588                blocker: None,
4589            },
4590            PermitKind::Urgent => {
4591                if self.urgent_busy {
4592                    let reason = "urgent slot busy".to_owned();
4593                    TaskAdmission {
4594                        mode,
4595                        reservation_lane: None,
4596                        standalone: false,
4597                        state: "waiting",
4598                        label: Self::format_waiting(task, &reason),
4599                        blocker: Some(reason),
4600                    }
4601                } else {
4602                    TaskAdmission {
4603                        mode,
4604                        reservation_lane: None,
4605                        standalone: false,
4606                        state: "next_poll",
4607                        label: "Urgent: next poll".to_owned(),
4608                        blocker: None,
4609                    }
4610                }
4611            }
4612            PermitKind::Ordinary => {
4613                if self.owned_ordinary_count == 0 {
4614                    TaskAdmission {
4615                        mode,
4616                        reservation_lane: None,
4617                        standalone: false,
4618                        state: "next_poll",
4619                        label: "Ordinary: next poll".to_owned(),
4620                        blocker: None,
4621                    }
4622                } else {
4623                    TaskAdmission {
4624                        mode,
4625                        reservation_lane: None,
4626                        standalone: false,
4627                        state: "waiting",
4628                        label: "Queued (ordinary lane)".to_owned(),
4629                        blocker: None,
4630                    }
4631                }
4632            }
4633        }
4634    }
4635}
4636
4637struct DispatchClaim {
4638    task: Task,
4639    claim: crate::queue::Claim,
4640    lane: PermitKind,
4641    permit: Option<tokio::sync::OwnedSemaphorePermit>,
4642}
4643
4644/// Claim and re-read before choosing a lane: a queue listing may predate an
4645/// immediate or urgent toggle. All unsuccessful paths release the claim
4646/// without an attempt.
4647fn claim_dispatch(
4648    queue: &Queue,
4649    candidate: &Task,
4650    cooling_down: bool,
4651    ordinary: &Arc<tokio::sync::Semaphore>,
4652    urgent: &Arc<tokio::sync::Semaphore>,
4653) -> std::result::Result<DispatchClaim, SkipReason> {
4654    let claim = queue
4655        .claim(&candidate.id)
4656        .map_err(|_| SkipReason::ClaimUnavailable)?;
4657    let task = match queue.get(&candidate.id) {
4658        Ok(t) if t.status.runnable() => t,
4659        Ok(_) => return Err(SkipReason::NoLongerRunnable),
4660        Err(e) => {
4661            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
4662            return Err(SkipReason::RereadFailed);
4663        }
4664    };
4665    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
4666        let mut held = task;
4667        hold.apply(&mut held);
4668        record(queue, &mut held);
4669        return Err(SkipReason::NoLongerRunnable);
4670    }
4671    let resume = land_resume_state(&task);
4672    if resume == LandResume::StillWaiting {
4673        return Err(SkipReason::WaitingOnLanding);
4674    }
4675    let priority = resume == LandResume::Ready;
4676    if !priority && cooling_down {
4677        return Err(SkipReason::CoolingDown);
4678    }
4679    // Never borrow an ordinary slot when the single urgent slot is busy.
4680    // Immediate tasks consume neither ordinary nor urgent permits.
4681    // Keep scanning other candidates when either pool has no free slot.
4682    let lane = permit_kind(priority, task.immediate, task.urgent);
4683    let permit = match lane {
4684        PermitKind::None | PermitKind::Immediate => None,
4685        PermitKind::Urgent => Some(
4686            Arc::clone(urgent)
4687                .try_acquire_owned()
4688                .map_err(|_| SkipReason::UrgentCapacity)?,
4689        ),
4690        PermitKind::Ordinary => Some(
4691            Arc::clone(ordinary)
4692                .try_acquire_owned()
4693                .map_err(|_| SkipReason::OrdinaryCapacity)?,
4694        ),
4695    };
4696    // Persist the dispatch order under the claim, before config discovery or
4697    // coordination waits can reorder concurrent starts.
4698    let stamp = Timestamp::now();
4699    let mut task = task;
4700    task.dispatched_at = Some(stamp);
4701    if let Err(e) = queue.modify(&task.id, |t| {
4702        t.dispatched_at = Some(stamp);
4703        true
4704    }) {
4705        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
4706    }
4707    Ok(DispatchClaim {
4708        task,
4709        claim,
4710        lane,
4711        permit,
4712    })
4713}
4714
4715/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
4716/// teardown and cannot skip the teardown on an early return.
4717///
4718/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
4719/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
4720/// land approval that has since been answered is dispatched outside that
4721/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
4722/// the whole point of parking there is that it must not queue behind
4723/// whatever else the loop happens to be running, even at the default of one.
4724/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
4725/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
4726/// these exemptions is still subject to the interrupt gate below, urgent
4727/// included: a land-resume or urgent candidate is exactly as much "something
4728/// else running" as an ordinary one from the interrupt sequence's point of
4729/// view, and letting either slip through while a run is being parked, or
4730/// while the interrupt task itself has the floor, is precisely the second
4731/// run 75dd's own "at most one run, ever, at once" guarantee must never
4732/// allow - see [`Interrupt`]'s own doc.
4733#[derive(Serialize, Deserialize)]
4734struct ServiceWorker {
4735    opts: Opts,
4736    queue: PathBuf,
4737    worktrees_root: PathBuf,
4738    operation: String,
4739}
4740
4741fn load_conductor(home: &Path) -> Result<Conductor> {
4742    match std::fs::read(home.join("conductor-state.json")) {
4743        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
4744        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
4745        Err(error) => Err(error.into()),
4746    }
4747}
4748
4749fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
4750    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
4751        .into_iter()
4752        .map(|c| c.task)
4753        .collect();
4754    let stalled = stalled_tasks(queue, home, Timestamp::now());
4755    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4756    let finished = finished_tasks(queue)
4757        .into_iter()
4758        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4759        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4760        .filter(|t| !t.has_awaiting_landing_cause())
4761        .collect();
4762    let queued = queued_tasks(queue)
4763        .into_iter()
4764        .filter(|t| !live.contains(&t.id))
4765        .collect();
4766    (queued, stalled, finished)
4767}
4768
4769// Separate latest dispatch and worker receipts expose version handoff and skips
4770// without erasing the last completed scan or treating observations as authority.
4771fn retention_service_receipt(
4772    home: &Path,
4773    operation: &str,
4774    phase: &str,
4775    outcome: &str,
4776    detail: &str,
4777    cfg: Option<&Config>,
4778) {
4779    retention_service_receipt_with(
4780        home,
4781        operation,
4782        phase,
4783        outcome,
4784        detail,
4785        cfg,
4786        serde_json::Value::Null,
4787    );
4788}
4789
4790/// [`retention_service_receipt`] plus `extra`: an object whose fields (the
4791/// fold turn's per-outcome counts and cursor, a retention pass's failures) are
4792/// added to the same receipt file rather than to a store of their own.
4793fn retention_service_receipt_with(
4794    home: &Path,
4795    operation: &str,
4796    phase: &str,
4797    outcome: &str,
4798    detail: &str,
4799    cfg: Option<&Config>,
4800    extra: serde_json::Value,
4801) {
4802    if !matches!(operation, "housekeeping" | "disk-pressure" | "fold") {
4803        return;
4804    }
4805    let mut receipt = serde_json::json!({"checked_at": Timestamp::now(),
4806        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4807        "operation": operation, "outcome": outcome, "detail": detail,
4808        "auto_fold": cfg.map(|c| c.disk.auto_fold),
4809        "reclaim_free_bytes": cfg.map(|c| c.disk.reclaim_threshold()),
4810        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4811    if let (Some(receipt), serde_json::Value::Object(extra)) = (receipt.as_object_mut(), extra) {
4812        receipt.extend(extra);
4813    }
4814    if let Err(error) = crate::fold_evidence::atomic_write(
4815        &home.join(format!("source-eviction-{operation}-{phase}.json")),
4816        &serde_json::to_vec(&receipt).expect("service receipt"),
4817    ) {
4818        tracing::warn!("retention service receipt failed: {error:#}");
4819    }
4820}
4821
4822/// What a retention pass reported, for the service receipt: the same report
4823/// `retention.json` holds, reduced to what says whether the pass ran. On a
4824/// platform without process containment this carries the refusal.
4825fn retention_summary(report: &crate::retention::Report) -> serde_json::Value {
4826    let clip = |text: &String| text.chars().take(300).collect::<String>();
4827    serde_json::json!({"retention": {
4828        "checked_at": report.checked_at,
4829        "freed_bytes": report.freed_bytes,
4830        "retired": report.retired,
4831        "retained": report.retained.len(),
4832        "failure_count": report.failures.len(),
4833        "failures": report.failures.iter().take(8).map(clip).collect::<Vec<_>>(),
4834    }})
4835}
4836
4837/// Why the finished-run folding turn exists, and what keeps it safe.
4838///
4839/// `housekeeping` (which folds finished runs through `clean::fold_due`) has
4840/// only ever been admitted on a fully idle machine: it was written as "the
4841/// janitor, called when a task just ended" (e2c10827, "the disk is quiet ...
4842/// folding worktrees and pruning a cache mid-build would race the very compile
4843/// the prune exists to keep"), and the idle gate survived when the loop was
4844/// split into services. Nothing in that reasoning is about folding: it is
4845/// about the shared cache prune, `fold_orphaned_worktrees` (a run that has no
4846/// `run.json` yet is indistinguishable from an orphan) and `worktree_prune`,
4847/// which stay idle-only. Folding a *finished* run is already done beside live
4848/// runs of the same repository by `Runner::fold_losers`, `magi fold` and the
4849/// phone's fold route, because `graph::fold_run_when` takes the run's owner lock
4850/// and execution lease, a per-worktree output lease and the repository
4851/// coordination lease itself, acts on the run record it reloads once it holds
4852/// them (a handover in between cannot be undone), and `clean::eligibility`
4853/// refuses anything a live claim holds. So a queue that is never empty must not
4854/// mean runs are never folded (issue 1275): this turn is admitted exactly where
4855/// housekeeping is not, in bounded passes (`clean::BUSY_FOLD_BOUNDS`).
4856const FOLD_TURN_INTERVAL_SECS: u64 = 120;
4857
4858/// Idle housekeeping: no worker busy and nothing runnable.
4859fn housekeeping_eligible(busy: bool, runnable: bool) -> bool {
4860    !busy && !runnable
4861}
4862
4863/// Exactly the machines [`housekeeping_eligible`] never reaches (see
4864/// [`FOLD_TURN_INTERVAL_SECS`] for why folding may run beside live work),
4865/// and only with a startup configuration that has `auto_fold` on (like the
4866/// cache and fetch services, an unreadable one means no service).
4867fn fold_turn_eligible(busy: bool, runnable: bool, cfg: Option<&Config>) -> bool {
4868    !housekeeping_eligible(busy, runnable) && cfg.is_some_and(|cfg| cfg.disk.auto_fold)
4869}
4870
4871async fn start_service(
4872    home: &Path,
4873    opts: &Opts,
4874    queue: &Queue,
4875    worktrees_root: &Path,
4876    operation: &str,
4877    cfg: Option<&Config>,
4878    busy: bool,
4879) -> Result<()> {
4880    // Fetch policy is live configuration, unlike question recovery capacity.
4881    // Reload before both cadence and eligibility, including disabled -> enabled.
4882    let fetch_cfg = if operation == "fetch" {
4883        match prepare(&opts.repo, opts) {
4884            Ok(cfg) => Some(cfg),
4885            Err(error) => {
4886                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4887                return Ok(());
4888            }
4889        }
4890    } else {
4891        None
4892    };
4893    let cfg = fetch_cfg.as_ref().or(cfg);
4894    let ticks = home.join("service-ticks");
4895    std::fs::create_dir_all(&ticks)?;
4896    let receipt = ticks.join(format!("daemon-{operation}"));
4897    let last = std::fs::read(&receipt)
4898        .ok()
4899        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4900    let interval = match operation {
4901        "disk-pressure" => 30,
4902        "fold" => FOLD_TURN_INTERVAL_SECS,
4903        "chat-goals" | "decisions" => 60,
4904        "cache" => CACHE_CHECK_INTERVAL_SECS,
4905        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4906        _ => opts.poll.as_secs().max(1),
4907    };
4908    let now = Timestamp::now();
4909    if !cache_check_due(last, now, interval) {
4910        retention_service_receipt(
4911            home,
4912            operation,
4913            "dispatch",
4914            "skipped",
4915            "cadence not due",
4916            cfg,
4917        );
4918        return Ok(());
4919    }
4920    let key = format!("service:daemon-{operation}");
4921    let active = crate::worker::active(home)?;
4922    if active.iter().any(|job| job.key == key) {
4923        retention_service_receipt(
4924            home,
4925            operation,
4926            "dispatch",
4927            "skipped",
4928            "service worker already active",
4929            cfg,
4930        );
4931        return Ok(());
4932    }
4933    // Both fold the same runs; the run's owner lock already makes a collision
4934    // harmless, but one of them at a time keeps the receipts unambiguous.
4935    let sibling = match operation {
4936        "housekeeping" => Some("service:daemon-fold"),
4937        "fold" => Some("service:daemon-housekeeping"),
4938        _ => None,
4939    };
4940    if sibling.is_some_and(|sibling| active.iter().any(|job| job.key == sibling)) {
4941        retention_service_receipt(
4942            home,
4943            operation,
4944            "dispatch",
4945            "skipped",
4946            "another finished-run folding service is active",
4947            cfg,
4948        );
4949        return Ok(());
4950    }
4951    let eligible = match operation {
4952        "conductor" => {
4953            let (queued, stalled, finished) = conductor_work(queue, home);
4954            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4955                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4956        }
4957        "maintenance" => {
4958            queue.list().iter().any(|task| {
4959                crate::triage::disk_wait_eligible(task)
4960                    && task
4961                        .disk_checked_at
4962                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4963            }) || Questions::at(home.join("questions"))
4964                .list_for_effects()
4965                .iter()
4966                .any(|q| {
4967                    q.chosen_action().is_some_and(|action| action.maintenance())
4968                        && !home
4969                            .join("choice-actions")
4970                            .join(format!("{}.json", q.id))
4971                            .exists()
4972                })
4973        }
4974        "housekeeping" => housekeeping_eligible(busy, !runnable(queue).is_empty()),
4975        "fold" => fold_turn_eligible(busy, !runnable(queue).is_empty(), cfg),
4976        "cache" => {
4977            !busy
4978                && !runnable(queue).is_empty()
4979                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4980        }
4981        "disk-pressure" => busy,
4982        "fetch" => {
4983            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4984        }
4985        "decisions" => home.join("notifications/task-inquiries").is_dir(),
4986        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4987            .list()
4988            .iter()
4989            .any(|talk| {
4990                talk.status.open()
4991                    && talk.pending.is_empty()
4992                    && talk.pending_attachments.is_empty()
4993                    && talk.goals.iter().any(|goal| goal.active())
4994            }),
4995        _ => false,
4996    };
4997    if !eligible {
4998        retention_service_receipt(
4999            home,
5000            operation,
5001            "dispatch",
5002            "skipped",
5003            match operation {
5004                "housekeeping" => "active work or runnable task queue",
5005                "fold" if cfg.is_none() => "startup configuration unavailable",
5006                "fold" if cfg.is_some_and(|cfg| !cfg.disk.auto_fold) => "auto_fold disabled",
5007                "fold" => "idle machine; housekeeping owns finished-run folding",
5008                _ => "no active work; idle housekeeping owns scan",
5009            },
5010            cfg,
5011        );
5012        return Ok(());
5013    }
5014    retention_service_receipt(
5015        home,
5016        operation,
5017        "dispatch",
5018        "launching",
5019        "eligible and cadence due",
5020        cfg,
5021    );
5022    let request = ServiceWorker {
5023        opts: opts.absolute()?,
5024        queue: std::path::absolute(queue.root())?,
5025        worktrees_root: std::path::absolute(worktrees_root)?,
5026        operation: operation.to_owned(),
5027    };
5028    if let Err(error) = launch_service(home, &key, request).await {
5029        retention_service_receipt(
5030            home,
5031            operation,
5032            "dispatch",
5033            "error",
5034            &format!("worker launch: {error:#}"),
5035            cfg,
5036        );
5037        tracing::warn!(operation, "could not launch daemon service: {error:#}");
5038    }
5039    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
5040    Ok(())
5041}
5042
5043/// Hand `request` to a detached `daemon-service` worker reservation.
5044///
5045/// Unit tests have no `magi` executable to pin and exec as a worker, so they
5046/// may run the very same [`run_service_worker`] inline instead (and nothing
5047/// else differs: admission, cadence and receipts above are the production path).
5048async fn launch_service(home: &Path, key: &str, request: ServiceWorker) -> Result<()> {
5049    #[cfg(test)]
5050    if INLINE_SERVICES.with(std::cell::Cell::get) {
5051        return run_service_worker(home, serde_json::to_value(request)?).await;
5052    }
5053    crate::worker::spawn(home, "daemon-service", key, serde_json::to_value(request)?).await?;
5054    Ok(())
5055}
5056
5057#[cfg(test)]
5058thread_local! {
5059    static INLINE_SERVICES: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
5060}
5061
5062/// One bounded pass of finished-run folding (`clean::fold_turn`) with its
5063/// per-outcome counts and cursor in the service receipt. It reserves no agent
5064/// seat and takes only the locks `graph::fold_run` takes for one run at a time.
5065async fn fold_service_turn(home: &Path, opts: &Opts) {
5066    let worker = |outcome: &str, detail: &str, cfg: Option<&Config>, extra| {
5067        retention_service_receipt_with(home, "fold", "worker", outcome, detail, cfg, extra);
5068    };
5069    let cfg = match prepare(&opts.repo, opts) {
5070        Ok(cfg) => cfg,
5071        Err(error) => {
5072            worker(
5073                "error",
5074                &format!("configuration: {error:#}"),
5075                None,
5076                serde_json::Value::Null,
5077            );
5078            return;
5079        }
5080    };
5081    if !cfg.disk.auto_fold {
5082        worker(
5083            "skipped",
5084            "auto_fold disabled",
5085            Some(&cfg),
5086            serde_json::Value::Null,
5087        );
5088        return;
5089    }
5090    worker(
5091        "running",
5092        "finished-run fold turn",
5093        Some(&cfg),
5094        serde_json::Value::Null,
5095    );
5096    let turn = clean::fold_turn(
5097        &home.join("runs"),
5098        home,
5099        &cfg.disk,
5100        Timestamp::now(),
5101        clean::BUSY_FOLD_BOUNDS,
5102    )
5103    .await;
5104    if turn.folded > 0 || turn.failed > 0 || turn.unreadable > 0 {
5105        tracing::info!(
5106            folded = turn.folded,
5107            failed = turn.failed,
5108            unreadable = turn.unreadable,
5109            "housekeep: finished-run fold turn"
5110        );
5111    }
5112    worker(
5113        "completed",
5114        "finished-run fold turn",
5115        Some(&cfg),
5116        serde_json::json!({ "fold": turn }),
5117    );
5118}
5119
5120/// Finite maintenance jobs survive scheduler replacement without duplicating
5121/// agent calls or cancelling an operation between its effect and receipt.
5122pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
5123    let request: ServiceWorker = serde_json::from_value(payload)?;
5124    let opts = &request.opts;
5125    let queue = Queue::at(request.queue);
5126    let questions = Questions::at(home.join("questions"));
5127    match request.operation.as_str() {
5128        "decisions" => crate::chat_control::retire_obsolete_decisions(&queue, home).await?,
5129        "chat-goals" => {
5130            let talks = crate::talk::Talks::at(home.join("talks"));
5131            crate::chat_goal_runtime::sweep(&talks, false).await;
5132        }
5133        "maintenance" => {
5134            apply_maintenance_choices(&queue, &questions, home).await;
5135            triage::monitor_disk_waits(
5136                &queue,
5137                &questions,
5138                opts.config.as_deref(),
5139                Timestamp::now(),
5140            );
5141        }
5142        "conductor" => {
5143            let path = home.join("conductor-state.json");
5144            let mut conductor = load_conductor(home)?;
5145            let (queued, stalled, finished) = conductor_work(&queue, home);
5146            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
5147                && conductor.worth_a_look(&queue, &stalled, &finished)
5148            {
5149                let cfg = prepare(&opts.repo, opts)?;
5150                conductor
5151                    .maybe_run(
5152                        &cfg,
5153                        &opts.repo,
5154                        &queue,
5155                        &questions,
5156                        home,
5157                        &queued,
5158                        &stalled,
5159                        &finished,
5160                        opts.max_attempts,
5161                    )
5162                    .await;
5163                let temporary = path.with_extension("json.tmp");
5164                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
5165                std::fs::rename(temporary, path)?;
5166            }
5167        }
5168        "fetch" => {
5169            let cfg = prepare(&opts.repo, opts)?;
5170            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
5171                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
5172                tracing::debug!("fetch origins: {outcome:?}");
5173            }
5174        }
5175        "cache" => {
5176            if task_jobs(home)?.is_empty() {
5177                let mut checked = None;
5178                maybe_prune_cache_between_runs(
5179                    &opts.repo,
5180                    opts,
5181                    home,
5182                    &Stop::new(),
5183                    &mut checked,
5184                    Timestamp::now(),
5185                )
5186                .await;
5187            }
5188        }
5189        "disk-pressure" => {
5190            if let Ok(cfg) = prepare(&opts.repo, opts) {
5191                retention_service_receipt(
5192                    home,
5193                    "disk-pressure",
5194                    "worker",
5195                    "running",
5196                    "retention sweep",
5197                    Some(&cfg),
5198                );
5199                let report = crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5200                retention_service_receipt_with(
5201                    home,
5202                    "disk-pressure",
5203                    "worker",
5204                    "retention swept",
5205                    "retention sweep finished; cache cleanup follows",
5206                    Some(&cfg),
5207                    retention_summary(&report),
5208                );
5209                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
5210                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
5211                }
5212                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
5213                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
5214                }
5215                for current in current_work(home, Timestamp::now()) {
5216                    if let Ok(state) = RunState::load_under(&current.run, home)
5217                        && let Some(reason) = disk_gate(&state.repo, &state.config)
5218                    {
5219                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
5220                            job.key.strip_prefix("task:") == Some(current.task.as_str())
5221                        }) {
5222                            request_task_park(
5223                                home,
5224                                &job,
5225                                crate::run::ParkCause::Interrupt {
5226                                    reason: reason.clone(),
5227                                },
5228                            )?;
5229                        }
5230                        notices::raise_in(
5231                            home,
5232                            Notice::warn(
5233                                "disk:pressure",
5234                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
5235                            ),
5236                        );
5237                    }
5238                }
5239            } else {
5240                retention_service_receipt(
5241                    home,
5242                    "disk-pressure",
5243                    "worker",
5244                    "error",
5245                    "configuration could not be loaded",
5246                    None,
5247                );
5248            }
5249        }
5250        "fold" => fold_service_turn(home, opts).await,
5251        "housekeeping" => {
5252            if task_jobs(home)?.is_empty() {
5253                match prepare(&opts.repo, opts) {
5254                    Ok(cfg) => {
5255                        retention_service_receipt(
5256                            home,
5257                            "housekeeping",
5258                            "worker",
5259                            "running",
5260                            "retention sweep",
5261                            Some(&cfg),
5262                        );
5263                        let report =
5264                            crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
5265                        retention_service_receipt_with(
5266                            home,
5267                            "housekeeping",
5268                            "worker",
5269                            "retention swept",
5270                            "retention sweep finished; janitor follows",
5271                            Some(&cfg),
5272                            retention_summary(&report),
5273                        );
5274                    }
5275                    Err(error) => retention_service_receipt(
5276                        home,
5277                        "housekeeping",
5278                        "worker",
5279                        "error",
5280                        &format!("configuration: {error:#}"),
5281                        None,
5282                    ),
5283                }
5284                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
5285                resweep_superseded_attempts(&queue, home);
5286                triage_held(&queue, home, opts).await;
5287            } else {
5288                retention_service_receipt(
5289                    home,
5290                    "housekeeping",
5291                    "worker",
5292                    "skipped",
5293                    "task worker became active",
5294                    None,
5295                );
5296            }
5297        }
5298        operation => bail!("unknown daemon service {operation}"),
5299    }
5300    Ok(())
5301}
5302
5303/// Only a different request under the same key is a dispatch handoff race.
5304/// Our own unacknowledged reservation is a startup failure, not competing work:
5305/// stop dispatch without fencing it, so an already detached child may still run.
5306fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
5307    let key = format!("task:{}", request.task);
5308    let payload = serde_json::to_value(request)?;
5309    if crate::worker::active(home)?
5310        .iter()
5311        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
5312    {
5313        tracing::warn!(
5314            "task {} acquired a competing worker reservation: {error:#}",
5315            crate::run::short_of(&request.task)
5316        );
5317        return Ok(());
5318    }
5319    tracing::error!("task worker startup stopped dispatch: {error:#}");
5320    notices::raise_in(
5321        home,
5322        Notice::error(
5323            "loop:worker-startup",
5324            // Startup diagnostics may contain private child-process details;
5325            // keep them in the local error/log rather than the chat or notifier.
5326            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),
5327        ).link(Link::Task { id: request.task.clone() }),
5328    );
5329    Err(error).with_context(|| {
5330        format!(
5331            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
5332            crate::run::short_of(&request.task)
5333        )
5334    })
5335}
5336
5337fn once_queue_service(job: &crate::worker::Job) -> bool {
5338    job.kind == "daemon-service"
5339        && matches!(
5340            job.key.as_str(),
5341            "service:daemon-housekeeping"
5342                | "service:daemon-conductor"
5343                | "service:daemon-maintenance"
5344                | "service:daemon-decisions"
5345        )
5346}
5347
5348async fn poll(
5349    opts: &Opts,
5350    queue: &Queue,
5351    status: &Arc<Mutex<Status>>,
5352    home: &Path,
5353    worktrees_root: &Path,
5354    stop: &Stop,
5355    limits: DispatchLimits,
5356) -> Result<()> {
5357    let mut attempted = Vec::new();
5358    let mut settling_once_services = false;
5359    let interrupt_path = home.join("scheduler-interrupt.json");
5360    let mut interrupt = match std::fs::read(&interrupt_path) {
5361        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
5362        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
5363        Err(error) => return Err(error.into()),
5364    };
5365    let mut previous = std::collections::BTreeSet::<String>::new();
5366    let mut previous_skips = DispatchSkips::new();
5367    while !stop.stopped() {
5368        let active = crate::worker::active(home)?;
5369        let settling_queue_service = opts.once && active.iter().any(once_queue_service);
5370        let jobs: Vec<_> = active
5371            .into_iter()
5372            .filter(|job| job.kind == "task")
5373            .collect();
5374        let requests: Vec<_> = jobs
5375            .iter()
5376            .map(|job| {
5377                serde_json::from_value::<TaskWorker>(job.payload.clone())
5378                    .with_context(|| format!("read live task worker {}", job.id))
5379            })
5380            .collect::<Result<_>>()?;
5381        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
5382        let owned: std::collections::BTreeSet<_> = requests
5383            .iter()
5384            .filter(|r| !r.standalone)
5385            .map(|r| r.task.clone())
5386            .collect();
5387        let current: Vec<_> = requests
5388            .iter()
5389            .zip(&jobs)
5390            .filter(|(request, _)| !request.standalone)
5391            .map(|(request, job)| Current {
5392                worker: Some(job.id.clone()),
5393                task: request.task.clone(),
5394                run: queue
5395                    .get(&request.task)
5396                    .ok()
5397                    .and_then(|task| task.execution_runs().last().cloned())
5398                    .unwrap_or_default(),
5399            })
5400            .collect();
5401        {
5402            let mut snapshot = lock(status);
5403            snapshot.polls += 1;
5404            snapshot.completed += previous.difference(&owned).count();
5405            snapshot.current = current;
5406            snapshot.idle = owned.is_empty();
5407            snapshot.dispatch_wait = None;
5408        }
5409        previous = owned.clone();
5410        stop.busy.store(owned.len(), Ordering::SeqCst);
5411
5412        // Slots are reconstructed from durable reservations and OS-held worker
5413        // leases, not this scheduler's lifetime or mutable task urgency.
5414        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
5415        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
5416        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
5417        let mut permits = Vec::new();
5418        sweep_stale_claims(queue, STALE_CLAIM);
5419        reclaim_orphaned_running(queue, opts.max_attempts, &live);
5420        reclaim_abandoned_runs(home, Timestamp::now());
5421        let questions = Questions::at(home.join("questions"));
5422
5423        // Deterministic: no model, run before the conductor sees anything so
5424        // its input reflects the queue's current, already-resolved state.
5425        crate::task_chat::sweep(
5426            queue,
5427            &crate::talk::Talks::at(home.join("talks")),
5428            &questions,
5429            home,
5430        );
5431        if let Err(error) = crate::task_inquiry::Outbox::at(home)
5432            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
5433        {
5434            tracing::warn!("task inquiry delivery remains pending: {error:#}");
5435        }
5436        repair_choice_offers(&questions);
5437        resolve_blockers(queue, &questions);
5438        apply_task_choice_actions(queue, &questions, home);
5439        triage::apply_answers(queue, &questions);
5440        reconcile_task_questions(queue, &questions);
5441        let talks = crate::talk::Talks::at(home.join("talks"));
5442        crate::chat_notify::sweep(queue, &talks, home, opts.config.as_deref());
5443        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
5444        crate::chat_watch::sweep(home, &talks);
5445        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
5446            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
5447        }
5448        let mut turns = tokio::task::JoinSet::new();
5449        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
5450        // start_turns dispatches detached turns; no paid work lives in this set.
5451        while turns.join_next().await.is_some() {}
5452
5453        crate::consult::start_services(
5454            home,
5455            &opts.repo,
5456            limits.recovery_cfg.as_ref(),
5457            opts.config.as_deref(),
5458        )
5459        .await?;
5460        for operation in [
5461            "conductor",
5462            "maintenance",
5463            "housekeeping",
5464            "disk-pressure",
5465            "fold",
5466            "cache",
5467            "fetch",
5468            "chat-goals",
5469            "decisions",
5470        ] {
5471            // Once an idle --once drain starts settling services, subsequent
5472            // scans only consume their effects. An expired cadence receipt
5473            // must not start another service and keep the drain alive.
5474            if settling_once_services {
5475                break;
5476            }
5477            if operation == "chat-goals" && stop.parking() {
5478                continue;
5479            }
5480            start_service(
5481                home,
5482                opts,
5483                queue,
5484                worktrees_root,
5485                operation,
5486                limits.recovery_cfg.as_ref(),
5487                !live.is_empty(),
5488            )
5489            .await?;
5490        }
5491        let latest = crate::worker::active(home)?;
5492        if latest.iter().any(|job| job.key == "service:daemon-cache")
5493            || latest
5494                .iter()
5495                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
5496        {
5497            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5498            continue;
5499        }
5500        let candidates: Vec<Task> = runnable(queue)
5501            .into_iter()
5502            .filter(|task| !live.contains(&task.id))
5503            .filter(|task| !opts.once || !attempted.contains(&task.id))
5504            .collect();
5505        let in_flight: Vec<_> = owned.iter().cloned().collect();
5506        let prior_interrupt = std::mem::discriminant(&interrupt);
5507        interrupt = advance_interrupt_tick(
5508            limits.pause_for_interrupts,
5509            interrupt,
5510            &in_flight,
5511            &candidates,
5512        );
5513        // Same-variant transitions preserve their identities. Only an actual
5514        // transition needs a durable write, atomically before sending controls.
5515        if prior_interrupt != std::mem::discriminant(&interrupt) {
5516            let temporary = interrupt_path.with_extension("json.tmp");
5517            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
5518            std::fs::rename(temporary, &interrupt_path)?;
5519        }
5520        if let Interrupt::Parking {
5521            parked,
5522            interrupt_task,
5523        } = &interrupt
5524        {
5525            for job in jobs.iter().filter(|job| {
5526                parked
5527                    .iter()
5528                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
5529            }) {
5530                if crate::worker::control(home, &job.key)?.is_none() {
5531                    request_task_park(
5532                        home,
5533                        job,
5534                        crate::run::ParkCause::Interrupt {
5535                            reason: format!(
5536                                "task {} asked to run first",
5537                                crate::run::short_of(interrupt_task)
5538                            ),
5539                        },
5540                    )?;
5541                }
5542            }
5543        }
5544        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
5545        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
5546        let mut skips = interrupt_skips(&candidate_ids, &candidates);
5547        // Stable-partition immediate candidates ahead of non-immediate ones
5548        // for this poll scan only; shared `dispatch_order` stays unchanged so
5549        // upgrade-resume and ordinary priority ordering are preserved.
5550        let (mut immediate_candidates, other_candidates): (Vec<Task>, Vec<Task>) =
5551            candidates.into_iter().partition(|task| task.immediate);
5552        immediate_candidates.extend(other_candidates);
5553        let candidates = immediate_candidates;
5554        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
5555        let mut known_jobs: std::collections::BTreeSet<String> =
5556            jobs.iter().map(|job| job.id.clone()).collect();
5557        let mut started = false;
5558        let mut resync = false;
5559        for candidate in candidates {
5560            if stop.stopped() {
5561                break;
5562            }
5563            let DispatchClaim {
5564                task,
5565                claim,
5566                lane,
5567                permit,
5568            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
5569                Ok(claim) => claim,
5570                Err(reason) => {
5571                    skips.insert((candidate.id, reason));
5572                    continue;
5573                }
5574            };
5575            if crate::worker::active(home)?
5576                .iter()
5577                .any(|job| job.kind == "task" && !known_jobs.contains(&job.id))
5578            {
5579                drop(claim);
5580                resync = true;
5581                break;
5582            }
5583            let request = TaskWorker {
5584                opts: opts.absolute()?,
5585                queue: std::path::absolute(queue.root())?,
5586                task: task.id.clone(),
5587                lane,
5588                standalone: false,
5589            };
5590            // Keep the claim until spawn acknowledges the worker's durable
5591            // reservation. The worker then claims and re-reads before attempt.
5592            let job = match crate::worker::spawn(
5593                home,
5594                "task",
5595                &format!("task:{}", task.id),
5596                serde_json::to_value(&request)?,
5597            )
5598            .await
5599            {
5600                Ok(job) => job,
5601                Err(error) => {
5602                    task_worker_spawn_error(home, &request, error)?;
5603                    drop(claim);
5604                    resync = true;
5605                    break;
5606                }
5607            };
5608            known_jobs.insert(job.id);
5609            drop(claim);
5610            permits.extend(permit);
5611            attempted.push(task.id);
5612            started = true;
5613            // Interrupt transitions depend on the exact in-flight set (in
5614            // particular the transition from zero to one worker). Re-scan
5615            // before admitting another task, as for ordinary dispatch.
5616            if limits.pause_for_interrupts || lane != PermitKind::Immediate {
5617                break;
5618            }
5619        }
5620        if !resync && !stop.stopped() {
5621            let per_task_skips: std::collections::BTreeMap<String, String> = skips
5622                .iter()
5623                .map(|(id, reason)| (id.clone(), reason.key().to_owned()))
5624                .collect();
5625            {
5626                let mut snapshot = lock(status);
5627                snapshot.dispatch_skips = per_task_skips;
5628                if !started {
5629                    snapshot.dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
5630                }
5631            }
5632            if changed_dispatch_skips(&mut previous_skips, skips) {
5633                if previous_skips.is_empty() {
5634                    tracing::info!("dispatch skips cleared");
5635                }
5636                for (task, reason) in &previous_skips {
5637                    tracing::info!(
5638                        task,
5639                        reason = reason.key(),
5640                        "task {} skipped: {}",
5641                        crate::run::short_of(task),
5642                        reason.describe()
5643                    );
5644                }
5645            }
5646        }
5647        if started || resync {
5648            continue;
5649        }
5650        if owned.is_empty() && opts.once {
5651            let first_settlement = !settling_once_services;
5652            settling_once_services = true;
5653            // A service may release its claim after the dispatch scan but
5654            // before the final liveness check. Scan again without launching
5655            // new periodic services even if it has already finished.
5656            if crate::worker::active(home)?.iter().any(once_queue_service) {
5657                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
5658                continue;
5659            }
5660            if first_settlement || settling_queue_service {
5661                continue;
5662            }
5663            break;
5664        }
5665        stop.idle(if live.is_empty() {
5666            opts.poll
5667        } else {
5668            RECHECK_WHILE_BUSY.min(opts.poll)
5669        })
5670        .await;
5671    }
5672    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
5673    // every queue claim and Runner driver lease through outcome settlement.
5674    stop.busy.store(0, Ordering::SeqCst);
5675    {
5676        let mut snapshot = lock(status);
5677        snapshot.dispatch_wait = None;
5678        snapshot.dispatch_skips.clear();
5679    }
5680    Ok(())
5681}
5682
5683/// A maintenance pass may briefly own the same record while a worker starts.
5684/// Wait without blocking the executor or charging an agent attempt, then read
5685/// ownership again under the acquired lock. Other I/O failures still fail closed.
5686async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
5687    let busy = |error: &anyhow::Error| {
5688        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
5689            error.kind() == std::io::ErrorKind::WouldBlock
5690                || cfg!(windows) && error.raw_os_error() == Some(33)
5691        })
5692    };
5693    match crate::pr_head::owner_lock(home, id) {
5694        Ok(lock) => return Ok(lock),
5695        Err(error) if busy(&error) => {}
5696        Err(error) => return Err(error),
5697    }
5698    let wait = RunState::load_under(id, home)?
5699        .config
5700        .graph
5701        .timeout_resource_wait;
5702    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
5703}
5704
5705fn run_directory_present(dir: &Path) -> Result<bool> {
5706    match std::fs::symlink_metadata(dir) {
5707        Ok(_) => Ok(true),
5708        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(false),
5709        Err(error) => {
5710            Err(error).with_context(|| format!("inspect run directory {}", dir.display()))
5711        }
5712    }
5713}
5714
5715/// Historical successors do not revoke a still-resumable public owner. Scan
5716/// under the same lock as publication/driver claims, and fail closed on unknown
5717/// history before spending another attempt.
5718pub(crate) async fn public_resume_owner(
5719    home: &Path,
5720    runs: &[String],
5721    repo: &Path,
5722) -> Result<Option<RunState>> {
5723    let mut owner = None;
5724    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
5725        let dir = home.join("runs").join(id);
5726        if !run_directory_present(&dir)? {
5727            tracing::info!(run = id, path = %dir.display(), "skipping missing run directory in public ownership scan");
5728            continue;
5729        }
5730        let _lock = resume_owner_lock(home, id).await?;
5731        let state = RunState::load_under(id, home)?;
5732        if state.released()
5733            || state.retired_to.is_some()
5734            || state.pr_taken_over_by.is_some()
5735            || !crate::handover::landing_checkpoint(&state)
5736        {
5737            continue;
5738        }
5739        anyhow::ensure!(
5740            crate::git::toplevel(&state.repo).await?.canonicalize()?
5741                == crate::git::toplevel(repo).await?.canonicalize()?,
5742            "public owner repository differs; inspect run lineage"
5743        );
5744        anyhow::ensure!(
5745            owner.is_none(),
5746            "multiple retained public owners; inspect run lineage"
5747        );
5748        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
5749            anyhow::bail!(reason.diagnostic(&state));
5750        }
5751        let claimed = is_working_on_other(home, id, Timestamp::now())?;
5752        anyhow::ensure!(
5753            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
5754            "public owner's driver is live or unknown; wait before retrying"
5755        );
5756        owner = Some(state);
5757    }
5758    Ok(owner)
5759}
5760
5761/// Run one claimed task to a terminal status and record the outcome.
5762///
5763/// Every transition is flushed to the queue as it happens, so the state on disk
5764/// is what actually occurred rather than what this process still intends to
5765/// write.
5766async fn attempt(
5767    opts: &Opts,
5768    queue: &Queue,
5769    status: &Arc<Mutex<Status>>,
5770    stop: &Stop,
5771    interrupt_pause: crate::graph::Pause,
5772    task: &mut Task,
5773) -> Vec<QuotaLoss> {
5774    if let Some(request) = task.sync_only.clone() {
5775        Box::pin(attempt_sync_only(
5776            queue,
5777            status,
5778            stop,
5779            interrupt_pause,
5780            task,
5781            request,
5782        ))
5783        .await;
5784        return Vec::new();
5785    }
5786    let repo = repo_for(task, &opts.repo);
5787    tracing::info!(
5788        "task {} — {} (repo {})",
5789        task.short(),
5790        task.title,
5791        repo.display()
5792    );
5793
5794    let home = crate::run::home();
5795    let public_owner = match public_resume_owner(&home, &task.runs, &repo).await {
5796        Ok(owner) => owner,
5797        Err(e) => {
5798            task.hold_machine(Some(format!(
5799                "Cannot verify existing public owner: {e:#}; no attempt started."
5800            )));
5801            record(queue, task);
5802            return Vec::new();
5803        }
5804    };
5805    let resume_runs = public_owner
5806        .as_ref()
5807        .map(|s| vec![s.id.clone()])
5808        .unwrap_or_else(|| task.execution_runs().to_vec());
5809
5810    // A stop spends no agent resources and uses the saved landing owner.
5811    // Current roster edits, missing attachments or a failed config fetch must
5812    // never turn it into a new implementation, or prevent a PR from closing.
5813    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
5814        && previous
5815            .merge_decision
5816            .as_ref()
5817            .is_some_and(|decision| !decision.closed)
5818        && previous.status != RunStatus::Landing
5819        && !crate::merge_decision::resumable_hold(&previous)
5820    {
5821        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)));
5822        record(queue, task);
5823        return Vec::new();
5824    }
5825    let stop_owner = resume_runs
5826        .last()
5827        .and_then(|id| RunState::load(id).ok())
5828        .filter(|state| {
5829            crate::merge_decision::resumable_hold(state)
5830                || state.status == RunStatus::Landing
5831                    && state.land_approval.as_ref().is_some_and(|binding| {
5832                        Questions::open()
5833                            .get_for_effects(&binding.question)
5834                            .is_ok_and(|q| {
5835                                q.run == state.id
5836                                    && q.resolution()
5837                                        .as_deref()
5838                                        .is_some_and(crate::merge_decision::stops)
5839                            })
5840                    })
5841        });
5842    if let Some(owner) = stop_owner {
5843        let mut runner = match Runner::resume(&owner.id) {
5844            Ok(runner) => runner,
5845            Err(e) => {
5846                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
5847                record(queue, task);
5848                return Vec::new();
5849            }
5850        };
5851        runner.on_pause(stop.pause());
5852        runner.watch_interrupt(interrupt_pause);
5853        let quota_before = runner.state.quota.clone();
5854        let before_start = task.clone();
5855        task.start(owner.id.clone());
5856        if let Err(error) = queue.put(task) {
5857            *task = before_start;
5858            let error = runner.fail_startup("task-start", error);
5859            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5860                task.record_startup_failure(failure.clone());
5861            }
5862            task.hold_manual(Some(format!(
5863                "Could not persist task start; no agents dispatched: {error:#}"
5864            )));
5865            record(queue, task);
5866            return Vec::new();
5867        }
5868        lock(status).current.push(Current {
5869            worker: None,
5870            task: task.id.clone(),
5871            run: owner.id,
5872        });
5873        runner.state.carry_dispatched_resumes(task);
5874        runner.state.next_pass_task_entry = true;
5875        let result = runner.execute().await;
5876        return finish_attempt(
5877            opts.max_attempts,
5878            queue,
5879            task,
5880            &runner.state,
5881            &quota_before,
5882            result,
5883        );
5884    }
5885
5886    if let Some(owner) = &public_owner
5887        && (task.fresh_start || !may_resume_run(owner, task))
5888    {
5889        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)));
5890        record(queue, task);
5891        return Vec::new();
5892    }
5893
5894    if let Some(state) = task
5895        .execution_runs()
5896        .last()
5897        .and_then(|id| RunState::load(id).ok())
5898        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
5899    {
5900        task.hold_machine(Some(reason));
5901        record(queue, task);
5902        return Vec::new();
5903    }
5904
5905    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
5906        && !task.fresh_start
5907        && task.pr_recovery.is_none()
5908    {
5909        // A pinned infrastructure resume continues the saved reservation;
5910        // it does not authorize another base-sync interval.
5911        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
5912            && task.review_branch.is_none()
5913            && task.assignment_accepts(&held)
5914            && compatible_run_instruction(&held, task)
5915            && task
5916                .resume_override
5917                .as_ref()
5918                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
5919        // Exhaustion authorization still takes the owner lock and execution
5920        // lease and rechecks liveness, retained HEAD and ownership.
5921        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
5922        {
5923            true
5924        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
5925            let home = queue.root().parent().expect("queue has a home");
5926            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
5927                Ok(()) => true,
5928                Err(error) => {
5929                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
5930                    false
5931                }
5932            }
5933        } else {
5934            false
5935        };
5936        if !authorized {
5937            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())));
5938            // Retain the existing stop identity when an old release reached the queue.
5939            task.base_sync_notice(&held);
5940            task.resume_override = None;
5941            record(queue, task);
5942            return Vec::new();
5943        }
5944    }
5945    if !task.fresh_start && task.pr_recovery.is_none() {
5946        let home = queue.root().parent().expect("queue has a home");
5947        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
5948            crate::land_sync_recovery::dispatch_check(queue, home, task).await
5949        {
5950            task.hold_machine(Some(reason));
5951            task.land_sync_notice(state.as_ref());
5952            task.resume_override = None;
5953            record(queue, task);
5954            return Vec::new();
5955        }
5956    }
5957    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
5958        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
5959            hold.apply(task);
5960            record(queue, task);
5961            return Vec::new();
5962        }
5963        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
5964            run,
5965            stop_id,
5966            generation,
5967            approval_at,
5968        }) => Some((run, stop_id, generation, approval_at)),
5969        None => None,
5970    };
5971    let unfinished = (!task.fresh_start)
5972        .then(|| unfinished_run(&resume_runs, task.short()))
5973        .flatten()
5974        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
5975    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
5976    if task.repair_grants.last().is_some_and(|receipt| {
5977        task.execution_runs().last() == Some(&receipt.request.run)
5978            && task.operator_decided_at == receipt.decision
5979            && previous
5980                .as_ref()
5981                .is_none_or(|run| run.id != receipt.request.run)
5982    }) {
5983        task.hold_unrequested_retry(Some(
5984            "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(),
5985        ));
5986        record(queue, task);
5987        return Vec::new();
5988    }
5989    if let Some(id) = &task.disk_resume_run
5990        && unfinished.as_ref() != Some(id)
5991    {
5992        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()));
5993        record(queue, task);
5994        return Vec::new();
5995    }
5996
5997    if !task.fresh_start
5998        && task.pr_recovery.is_none()
5999        && task.review_branch.is_none()
6000        && task.resume_override.is_none()
6001        && previous
6002            .as_ref()
6003            .is_some_and(|run| run.retired_to.is_some())
6004        && unfinished.is_none()
6005    {
6006        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()));
6007        record(queue, task);
6008        return Vec::new();
6009    }
6010
6011    let saved_recovery = previous.as_ref().filter(|run| {
6012        task.replacement.is_none()
6013            && task.pr_recovery.as_ref().is_some_and(|selected| {
6014                selected
6015                    .check_retained_task(task, &crate::run::home())
6016                    .is_ok()
6017                    && selected_starter(selected, Some(run), unfinished.as_deref())
6018                        == Starter::Resume(run.id.clone())
6019            })
6020    });
6021
6022    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
6023    // failure here is the network's or the operator's, not the task's: hold
6024    // without spending an attempt, never fall back to a possibly stale copy.
6025    let explicit = match &task.overrides {
6026        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6027        Some(_) => opts.config.as_deref(),
6028        None => opts.config.as_deref(),
6029    };
6030    let (mut config, layers) = if let Some(run) = saved_recovery {
6031        // A matching resume owns its resolved configuration and evidence;
6032        // current layers and inherited overrides only configure new work.
6033        let mut saved = run.clone();
6034        if let Err(e) = saved.configure_recovery_resume() {
6035            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
6036            record(queue, task);
6037            return Vec::new();
6038        }
6039        (saved.config, Vec::new())
6040    } else {
6041        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
6042            Ok(loaded) => loaded,
6043            Err(e) => {
6044                let reason = format!("[config] {e:#}");
6045                record_config_failure(task, &e);
6046                task.last_error = Some(reason.clone());
6047                task.hold_machine(Some(reason));
6048                record(queue, task);
6049                return Vec::new();
6050            }
6051        };
6052        if let Err(e) = apply_options(&mut config, opts, task) {
6053            task.hold_manual(Some(format!(
6054                "[config] {e:#}; correct the merge override before releasing the task"
6055            )));
6056            record(queue, task);
6057            return Vec::new();
6058        }
6059        if let Some(selected) = &task.pr_recovery
6060            && let Err(e) = selected.configure(&mut config)
6061        {
6062            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
6063            record(queue, task);
6064            return Vec::new();
6065        }
6066        (config, layers)
6067    };
6068    let config_evidence = crate::pr_recovery::ConfigEvidence {
6069        layers,
6070        overrides: task.overrides.clone(),
6071        daemon_merge: task
6072            .overrides
6073            .as_ref()
6074            .is_none_or(|o| o.inherit_daemon_options)
6075            .then(|| opts.merge.clone())
6076            .flatten(),
6077    };
6078    apply_task_implementers(&mut config, task);
6079    if let Some(replacement) = &task.replacement {
6080        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
6081            old.liveness(false) == Liveness::Dead
6082                && old.merge_decision.as_ref().is_some_and(|d| {
6083                    d.closed
6084                        && d.question == replacement.question
6085                        && d.replacement_run.as_ref().is_none_or(|run| {
6086                            task.execution_runs().last() == Some(run)
6087                                && RunState::load(run).is_ok_and(|current| {
6088                                    current.replaces.as_ref().is_some_and(|pin| {
6089                                        pin.question == replacement.question
6090                                            && pin.agent == replacement.agent
6091                                    })
6092                                })
6093                        })
6094                })
6095        });
6096        if !safe {
6097            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()));
6098            record(queue, task);
6099            return Vec::new();
6100        }
6101        match config.agent(&replacement.agent) {
6102            Ok(agent) if crate::agent::installed(agent) => {}
6103            _ => {
6104                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)));
6105                record(queue, task);
6106                return Vec::new();
6107            }
6108        }
6109        config.graph.implementers = 1;
6110        config.graph.land_approval = true;
6111        config.merge.mode = MergeMode::Pr;
6112        config.graph.selected_implementer = Some(replacement.agent.clone());
6113    }
6114    let p = phrases(&config.graph.language);
6115    let start_failed = p.could_not_start;
6116    // Resolve once for both admission and settlement. The inputs are the
6117    // task's explicit sources (never prose), plus an explicit review source's
6118    // current head; review-only runs may rebase later, and neither fact can
6119    // refund a failed automatic generation.
6120    if let Ok(base) =
6121        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
6122            .await
6123        && let Ok(head) =
6124            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
6125    {
6126        let mut inputs = crate::queue::recovery_inputs(&task.sources);
6127        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
6128            let source = crate::git::rev_parse(&repo, branch)
6129                .await
6130                .unwrap_or_default();
6131            inputs.push_str(&format!(";review:{branch}:{source}"));
6132        }
6133        if let Some(reason) = task
6134            .recovery_exhausted(
6135                &head,
6136                &inputs,
6137                task.attempt_limit
6138                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
6139            )
6140            .filter(|_| {
6141                !task.repair_grants.last().is_some_and(|receipt| {
6142                    RunState::load(&receipt.request.run)
6143                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
6144                })
6145            })
6146        {
6147            task.hold_recovery_budget(
6148                reason,
6149                crate::queue::RecoveryAdmission { base: head, inputs },
6150            );
6151            record(queue, task);
6152            return Vec::new();
6153        }
6154        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
6155    }
6156
6157    // A resumable run of this task is carried on, never re-competed. The
6158    // candidates are built and paid for, and a fresh competition races a
6159    // second implementation against them.
6160    //
6161    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
6162    // started 3cbf on the same task a moment later, duplicating two and a
6163    // half hours of agent work. Then b25f stalled on a judge that timed out
6164    // and one that answered with no JSON - `quota: 0`, so nothing the machine
6165    // was to blame for - and 4043 started **one second** later, buying three
6166    // fresh implementations to reach the same panel. `RunStatus::resumable`
6167    // rather than `!done()` is what catches the second case: a stall is
6168    // terminal, and its cheap recovery re-asks only the absent seats.
6169    //
6170    // A load failure is warned about rather than silently read as "not
6171    // resumable": the alternative is exactly what let a schema mismatch on
6172    // run `eba2` fall through to a full re-competition with nobody told why.
6173    // `crate::conduct` is what actually offers a better answer than
6174    // `Runner::start` here (see `Recovery::Review`), once this task's next
6175    // failure shows it up as `held`/`failed` with the run state unreadable.
6176    // Keep a retained review selection intact until disk admission succeeds.
6177    let consume_review = !previous
6178        .as_ref()
6179        .is_some_and(|state| crate::repair_budget::pending(task, state));
6180    let review_branch = consume_review
6181        .then(|| review_branch_for(task, previous.as_ref()))
6182        .flatten();
6183    let branch_exists = match review_branch {
6184        Some(branch) => crate::git::branch_exists(&repo, branch)
6185            .await
6186            .unwrap_or(false),
6187        None => false,
6188    };
6189    // An explicit `magi review <branch>` is reviewed whatever happens to the
6190    // branch unless an explicit implementer change requires fresh work. An
6191    // unfinished run of the same task still wins, so a retry resumes.
6192    let proposed = review_retry_starter(
6193        task,
6194        previous.as_ref(),
6195        review_branch,
6196        branch_exists,
6197        unfinished.as_deref(),
6198    );
6199    let retry_selected = task.replacement.is_some()
6200        && task.resumption.is_some()
6201        && !task.fresh_start
6202        && previous.as_ref().is_some_and(|run| {
6203            run.replaces.is_some()
6204                && ((run.status == RunStatus::Failed && run.viable().is_empty())
6205                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
6206        });
6207    let stop_pin = task
6208        .resume_override
6209        .as_ref()
6210        .filter(|pin| {
6211            Questions::open()
6212                .get_for_effects(&pin.question_id)
6213                .is_ok_and(|q| {
6214                    q.node == land::APPROVAL_NODE
6215                        && q.resolution()
6216                            .as_deref()
6217                            .is_some_and(crate::merge_decision::stops)
6218                })
6219        })
6220        .and_then(|pin| pin.pinned_run.clone());
6221    let granted_run = task.repair_grants.last().and_then(|receipt| {
6222        let state = RunState::load(&receipt.request.run).ok()?;
6223        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
6224    });
6225    let starter = if let Some(run) = granted_run {
6226        Starter::Resume(run)
6227    } else if let Some(owner) = &public_owner {
6228        Starter::Resume(owner.id.clone())
6229    } else if let Some(run) = stop_pin {
6230        // Stop actions resume their exact owner even after seat-count edits;
6231        // they must never fall through to implementation or a takeover.
6232        Starter::Resume(run)
6233    } else if retry_selected {
6234        Starter::Resume(previous.as_ref().unwrap().id.clone())
6235    } else if let Some(selected) = &task.pr_recovery {
6236        if selected
6237            .check_retained_task(task, &crate::run::home())
6238            .is_ok()
6239        {
6240            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
6241        } else {
6242            Starter::Review(selected.branch.clone())
6243        }
6244    } else {
6245        starter_with_implementers(task, previous.as_ref(), proposed)
6246    };
6247    // A retained execution still writes to its saved output volume. A newer
6248    // repository policy only selects the volume for a fresh run.
6249    let disk_reason = match &starter {
6250        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
6251            || {
6252                RunState::load(id)
6253                    .ok()
6254                    .and_then(|run| disk_gate(&run.repo, &run.config))
6255            },
6256            |run| disk_gate(&run.repo, &run.config),
6257        ),
6258        _ => disk_gate(&repo, &config),
6259    };
6260    if let Some(reason) = disk_reason {
6261        task.notice_cause("disk-space", None, None);
6262        task.last_error = Some(reason.clone());
6263        let disk_checked_at = task.disk_checked_at;
6264        task.hold_machine(Some(reason.clone()));
6265        if matches!(starter, Starter::Resume(_)) {
6266            task.mark_disk_capacity();
6267        } else {
6268            task.mark_startup_disk_capacity();
6269        }
6270        task.disk_checked_at = disk_checked_at;
6271        record(queue, task);
6272        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
6273        notices::raise(
6274            Notice::warn(
6275                &format!("disk:{}", repo.display()),
6276                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
6277            )
6278            .link(Link::Task {
6279                id: task.id.clone(),
6280            }),
6281        );
6282        return Vec::new();
6283    }
6284    let review_branch = if consume_review {
6285        let valid = review_branch.is_some();
6286        task.review_instruction = None;
6287        task.review_branch.take().filter(|_| valid)
6288    } else {
6289        None
6290    };
6291    // An explicit resume pin must never degrade into a new competition or
6292    // takeover, including when its run stops being eligible after the answer.
6293    if let Some(pin) = &task.resume_override
6294        && let Some(run) = &pin.pinned_run
6295        && starter != Starter::Resume(run.clone())
6296    {
6297        let run = run.clone();
6298        task.notice_cause("resume-owner", Some(&run), None);
6299        task.hold_machine(Some(format!(
6300            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
6301            task.id
6302        )));
6303        record(queue, task);
6304        return Vec::new();
6305    }
6306    // Automatic disk recovery resumes its retained run or stops: a changed
6307    // seat count or review branch must not turn it into a new competition.
6308    // No attempt is spent here.
6309    if let Some(run) = &task.disk_resume_run
6310        && starter != Starter::Resume(run.clone())
6311    {
6312        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()));
6313        record(queue, task);
6314        return Vec::new();
6315    }
6316    if task.replacement.is_some()
6317        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
6318        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
6319    {
6320        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()));
6321        record(queue, task);
6322        return Vec::new();
6323    }
6324    if let Some((ref run, ..)) = head_e2e_approval
6325        && starter != Starter::Resume(run.clone())
6326    {
6327        task.hold_machine(Some(format!(
6328            "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."
6329        )));
6330        record(queue, task);
6331        return Vec::new();
6332    }
6333    if let Some(reason) =
6334        retained_attempt_hold(task, &starter, config.disk.retained_attempt_limit, |id| {
6335            load_retained_attempt(&home, id)
6336        })
6337    {
6338        // The review choice was consumed above. Preserve it across this hold
6339        // so a later release cannot silently become a fresh implementation.
6340        if let Starter::Review(branch) = &starter {
6341            task.review_branch = Some(branch.clone());
6342        }
6343        task.hold_unrequested_retry(Some(reason));
6344        record(queue, task);
6345        return Vec::new();
6346    }
6347    // Absolute paths of the files the task was filed with, re-read from the
6348    // task now so a file attached while it was held reaches a resumed run
6349    // too. A stored name whose file has gone is an error before any agent is
6350    // paid for, never a silent omission the implementer cannot notice.
6351    let attachments = match task_attachments(queue, task) {
6352        Ok(a) => a,
6353        Err(e) => {
6354            task.attempts += 1;
6355            task.fail_startup_target(
6356                "startup-attachments",
6357                e.name.clone(),
6358                format!("{start_failed}{e:#}"),
6359                opts.max_attempts,
6360            );
6361            record(queue, task);
6362            return Vec::new();
6363        }
6364    };
6365    let startup_pause = stop.pause();
6366    let startup_interrupt = interrupt_pause.clone();
6367    let wait = crate::repo_lock::WaitPolicy::new(
6368        Duration::from_secs(config.graph.timeout_resource_wait),
6369        move || startup_pause.parked() || startup_interrupt.parked(),
6370    );
6371    // Startup includes review takeover and recovery. Do not embed its large
6372    // future in both the wait scope and the surrounding attempt stack frame.
6373    let started = wait.scope(Box::pin(async { match &starter {
6374        Starter::Review(_) if task.pr_recovery.is_some() => {
6375            let selected = task.pr_recovery.clone().expect("selected recovery");
6376            match selected.check_retained_task(task, &crate::run::home()) {
6377                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
6378                    .await
6379                    .map(|mut r| {
6380                        r.state.attachments = attachments.clone();
6381                        r
6382                    }),
6383                Err(e) => Err(e),
6384            }
6385        }
6386        Starter::Review(branch) => {
6387            tracing::info!(
6388                "task {} reopens `{branch}` as a review-only pass",
6389                task.short()
6390            );
6391            // Every earlier attempt is superseded by the one being minted
6392            // now, so a branch one of them still holds may be taken over.
6393            let takeover = crate::handover::Takeover {
6394                earlier: task.earlier_attempts().to_vec(),
6395                home: crate::run::home(),
6396                choice: take_divergence_answer(branch, &config.merge.remote, task),
6397                task_instruction: Some(instruction_for(task)),
6398            };
6399            Runner::review_taking_over(
6400                &repo,
6401                branch,
6402                config,
6403                Some(takeover),
6404                crate::run::Origin::queue(&task.id),
6405            )
6406            .await
6407        }
6408        Starter::Resume(id) => {
6409            tracing::info!("resuming run {id} rather than competing again");
6410            Runner::resume(id).and_then(|mut r| {
6411                if retry_selected {
6412                    // The explicit queue release retries this same pinned
6413                    // implementation, preserving the attempt and worktrees.
6414                    for candidate in &mut r.state.candidates {
6415                        candidate.failed = None;
6416                        candidate.empty = false;
6417                        candidate.commits = 0;
6418                    }
6419                    r.state.status = RunStatus::Implementing;
6420                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
6421                }
6422                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
6423                    r.state.sources = task.sources.clone();
6424                }
6425                if r.state.prep_failure.is_some() {
6426                    let approval = task
6427                        .resumption
6428                        .as_ref()
6429                        .context("preparation retry requires an explicit task release")?;
6430                    r.retry_preparation(approval.at)?;
6431                }
6432                if let Some(instruction) =
6433                    prepare_instruction(&starter, Some(&r.state.instruction), task)
6434                {
6435                    r.state.instruction = instruction;
6436                }
6437                r.state.attachments = attachments.clone();
6438                if task.replacement.is_some() {
6439                    r.state.config.merge.mode = MergeMode::Pr;
6440                    r.state.config.graph.land_approval = true;
6441                }
6442                // Replacements publish a new PR and ask again. Selected PR
6443                // recoveries keep their saved disposition; ordinary runs can
6444                // retain the task's merge override.
6445                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
6446                    .overrides
6447                    .as_ref()
6448                    .and_then(|o| o.merge.as_deref())
6449                    .and_then(|m| merge_mode(m).ok())
6450                {
6451                    r.state.config.merge.mode = mode;
6452                }
6453                Ok(r)
6454            })
6455        }
6456        Starter::Start => {
6457            if let Some(branch) = &review_branch {
6458                tracing::warn!(
6459                    "conductor chose review for task {} but branch `{branch}` no longer \
6460                     exists; requeuing as a fresh competition instead",
6461                    task.short()
6462                );
6463            }
6464            let instruction = prepare_instruction(&starter, None, task)
6465                .unwrap_or_else(|| task.instruction.clone());
6466            Runner::start_naming(
6467                &repo,
6468                instruction,
6469                &task.title,
6470                config,
6471                crate::run::Origin::queue(&task.id),
6472            )
6473            .await
6474            .map(|mut r| {
6475                r.state.attachments = attachments.clone();
6476                r.state.sources = task.sources.clone();
6477                r
6478            })
6479        }
6480    }})).await;
6481    if let Err(error) = &started
6482        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
6483    {
6484        task.record_startup_failure(failure.clone());
6485    }
6486    let mut runner = match started {
6487        Ok(r) => r,
6488        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
6489            let detail = format!("{e:#}");
6490            task.last_error = Some(detail.clone());
6491            if e.is::<crate::build_target::AdmissionDiskWait>()
6492                && let Starter::Review(branch) = &starter
6493                && review_branch.is_some()
6494            {
6495                task.review_branch = Some(branch.clone());
6496                task.review_instruction = Some(task.instruction.clone());
6497            }
6498            if stop.parking() || interrupt_pause.parked() {
6499                let attempts = task.attempts;
6500                task.park(e.to_string());
6501                // Startup has not spent an attempt to refund.
6502                task.attempts = attempts;
6503            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
6504                let disk_checked_at = task.disk_checked_at;
6505                task.hold_machine(Some(detail));
6506                task.mark_startup_disk_capacity();
6507                task.disk_checked_at = disk_checked_at;
6508            } else {
6509                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
6510            }
6511            record(queue, task);
6512            return Vec::new();
6513        }
6514        // A branch an earlier attempt still holds and magi will not release
6515        // by itself is the operator's call, not a failed attempt: hold the
6516        // task with the reason, spend nothing, and say so on the bell.
6517        Err(e) if task.pr_recovery.is_some() => {
6518            task.startup_notice_cause("startup-public-head");
6519            task.attempts += 1;
6520            task.last_error = Some(format!("{start_failed}{e:#}"));
6521            task.hold_unrequested_retry(Some(format!(
6522                "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."
6523            )));
6524            record(queue, task);
6525            return Vec::new();
6526        }
6527        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
6528            let detail = match e.downcast_ref::<crate::handover::Refused>() {
6529                Some(r) => (p.handover_refused)(r),
6530                None => format!("{e:#}"),
6531            };
6532            task.startup_notice_cause("startup-handover");
6533            let reason = format!("{start_failed}{detail}");
6534            task.last_error = Some(reason.clone());
6535            // Consumed above by `take`; keep it so the released task retries
6536            // as a review of this same branch.
6537            let branch = match &starter {
6538                Starter::Review(branch) => Some(branch.clone()),
6539                _ => None,
6540            };
6541            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
6542            // one page; the guidance rides in the reason, fixed per state so a
6543            // re-put never changes the wording and relights it.
6544            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
6545            record(queue, task);
6546            tracing::warn!(
6547                "holding {} for a branch it cannot take over: {e:#}",
6548                task.short()
6549            );
6550            return Vec::new();
6551        }
6552        // A branch that differs between here and the remote in ways magi
6553        // cannot prove are the same change is a decision for the owner, not a
6554        // failed attempt: ask with both sides laid out, spend no attempt, and
6555        // let the answer requeue the task.
6556        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
6557            let d = e
6558                .downcast_ref::<crate::reconcile::Diverged>()
6559                .expect("checked by the guard");
6560            let mut q = ask::Question::new(
6561                task.id.clone(),
6562                crate::reconcile::NODE.to_owned(),
6563                crate::reconcile::SEAT.to_owned(),
6564                d.summary(),
6565                d.detail(),
6566                d.choices(),
6567            );
6568            match Questions::open().put(&mut q) {
6569                Ok(()) => {
6570                    task.last_error = Some(format!("{e:#}"));
6571                    // Consumed above by `take`; the answer has to reach a review
6572                    // of this same branch, so keep pointing the task at it.
6573                    task.review_branch = Some(d.branch.clone());
6574                    task.review_instruction = Some(task.instruction.clone());
6575                    task.block(vec![q.id.clone()], Some(d.summary()));
6576                }
6577                Err(put) => {
6578                    tracing::warn!("could not file the divergence question: {put:#}");
6579                    task.attempts += 1;
6580                    task.fail_startup(
6581                        "startup-question-store",
6582                        format!("{start_failed}{e:#}"),
6583                        opts.max_attempts,
6584                    );
6585                }
6586            }
6587            record(queue, task);
6588            return Vec::new();
6589        }
6590        Err(e) => {
6591            // The answer was stale and nothing was applied: keep pointing at
6592            // the branch so the next attempt asks again against its new tips.
6593            // Nothing went wrong with the task, so no attempt is spent: a
6594            // budget one short of its limit must not hold it instead of
6595            // letting the question be asked again.
6596            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
6597                && let Starter::Review(branch) = &starter
6598            {
6599                task.review_branch = Some(branch.clone());
6600                task.review_instruction = Some(task.instruction.clone());
6601                task.last_error = Some(format!("{start_failed}{e:#}"));
6602                task.status = crate::queue::TaskStatus::Failed;
6603                record(queue, task);
6604                return Vec::new();
6605            }
6606            task.attempts += 1;
6607            task.last_error = Some(format!("{start_failed}{e:#}"));
6608            task.startup_notice_cause("startup-source");
6609            task.hold_unrequested_retry(Some(format!(
6610                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
6611            )));
6612            record(queue, task);
6613            return Vec::new();
6614        }
6615    };
6616    if !matches!(starter, Starter::Resume(_))
6617        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
6618    {
6619        runner
6620            .state
6621            .event("build-cache", format!("{mode} selected by {source}"));
6622    }
6623    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
6624        runner.state.recovery_config = Some(config_evidence);
6625    }
6626    if let Some(replacement) = &task.replacement {
6627        if matches!(starter, Starter::Start) {
6628            runner.state.instruction.push_str(&format!(
6629                "\n\n# Replacement review context\n{}",
6630                replacement.context
6631            ));
6632        }
6633        runner.state.replaces = Some(replacement.clone());
6634        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
6635        if let Ok(mut old) = RunState::load(&replacement.run)
6636            && let Some(d) = &mut old.merge_decision
6637        {
6638            d.replacement_run = Some(runner.state.id.clone());
6639            old.event(
6640                "replacement",
6641                format!(
6642                    "replacement run {} owns the next attempt; old PR remains closed",
6643                    runner.state.id
6644                ),
6645            );
6646            if let Err(e) = old.save() {
6647                let error = runner.fail_startup("replacement-history", e);
6648                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6649                    task.record_startup_failure(failure.clone());
6650                }
6651                task.hold_manual(Some(format!(
6652                    "Could not link replacement history: {error:#}; no agents dispatched"
6653                )));
6654                record(queue, task);
6655                return Vec::new();
6656            }
6657        }
6658    }
6659    runner.state.task_instruction = Some(task.instruction.clone());
6660    runner.state.task_instruction_rev = Some(task.instruction_rev);
6661    // The follow-up depth is fixed now, while the task certainly exists:
6662    // deleting it later must not reset the cap (`crate::followup`).
6663    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
6664    if runner.state.origin_chat.is_none() {
6665        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
6666    }
6667    // A stop that means "park" reaches the graph through this handle.
6668    runner.on_pause(stop.pause());
6669    // `poll`'s interrupt scheduler reaches this one run - and no other -
6670    // through this handle. See `Pause`'s own doc for why these are never
6671    // the same one.
6672    runner.watch_interrupt(interrupt_pause);
6673
6674    // `start` has minted the run, so the task can now point at it. Persisting
6675    // `Running` before `execute` is what makes a crash mid-run legible.
6676    let run = runner.state.id.clone();
6677    let before_start = task.clone();
6678    task.start(run.clone());
6679    if let Err(error) = queue.put(task) {
6680        *task = before_start;
6681        let error = runner.fail_startup("task-start", error);
6682        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
6683            task.record_startup_failure(failure.clone());
6684        }
6685        task.hold_manual(Some(format!(
6686            "Could not persist task start; no agents dispatched: {error:#}"
6687        )));
6688        record(queue, task);
6689        return Vec::new();
6690    }
6691    if task.status != TaskStatus::Running {
6692        // Queue::put kept a newer hold or continuation instead of this start.
6693        return Vec::new();
6694    }
6695    lock(status).current.push(Current {
6696        worker: None,
6697        task: task.id.clone(),
6698        run,
6699    });
6700
6701    // `RunState::quota` is the run's whole history across every resume, so
6702    // only what this execution added may arm the cooldown or earn a refund.
6703    let quota_before = runner.state.quota.clone();
6704    runner.state.carry_dispatched_resumes(task);
6705    runner.state.entry_resumption_generation =
6706        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
6707    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
6708        && runner.state.id == run
6709    {
6710        crate::head_e2e_stop::record_consumed_approval(
6711            &mut runner.state,
6712            &task.id,
6713            &stop_id,
6714            generation,
6715            approval_at,
6716        );
6717    }
6718    runner.state.next_pass_task_entry = true;
6719    let result = runner.execute().await;
6720    finish_attempt(
6721        opts.max_attempts,
6722        queue,
6723        task,
6724        &runner.state,
6725        &quota_before,
6726        result,
6727    )
6728}
6729
6730async fn attempt_sync_only(
6731    queue: &Queue,
6732    status: &Arc<Mutex<Status>>,
6733    stop: &Stop,
6734    interrupt: crate::graph::Pause,
6735    task: &mut Task,
6736    request: crate::base_sync_only::Request,
6737) {
6738    let result = async {
6739        anyhow::ensure!(
6740            task.status == TaskStatus::Queued
6741                && task.execution_runs().last() == Some(&request.run)
6742                && task.resume_override.as_ref().is_some_and(
6743                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
6744                ),
6745            "sync-base-only request no longer owns the exact queued run"
6746        );
6747        let mut runner = Runner::resume(&request.run)?;
6748        anyhow::ensure!(
6749            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
6750                .await?
6751                .is_none(),
6752            "the task still has a public execution owner"
6753        );
6754        anyhow::ensure!(
6755            !stop.parking() && !interrupt.parked(),
6756            "paused before base synchronization"
6757        );
6758        let original = task.clone();
6759        task.start(request.run.clone());
6760        task.attempts = original.attempts;
6761        if let Err(error) = queue.put(task) {
6762            *task = original;
6763            return Err(error);
6764        }
6765        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
6766            return Ok(());
6767        }
6768        lock(status).current.push(Current {
6769            worker: None,
6770            task: task.id.clone(),
6771            run: request.run.clone(),
6772        });
6773        runner.on_pause(stop.pause());
6774        runner.watch_interrupt(interrupt);
6775        runner.execute_sync_only(request.clone()).await
6776    }
6777    .await;
6778    if task.sync_only.as_ref() == Some(&request) {
6779        let saved = RunState::load(&request.run).ok();
6780        let detail = result.err().map(|error| {
6781            format!("Base synchronization only: {error:#}; verification was not allowed")
6782        });
6783        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
6784        record(queue, task);
6785    }
6786}
6787
6788/// Settle `task` after its run executed: the verdict, the diagnosis, the
6789/// supersession of earlier attempts and the save. Shared by the loop and by
6790/// `magi run --resume`, so an attempt is counted one way wherever it ran.
6791/// Returns the quota losses this execution added to the run.
6792pub fn finish_attempt(
6793    max_attempts: usize,
6794    queue: &Queue,
6795    task: &mut Task,
6796    state: &RunState,
6797    quota_before: &[QuotaLoss],
6798    result: Result<()>,
6799) -> Vec<QuotaLoss> {
6800    let detail = match result {
6801        Ok(()) => describe(state),
6802        Err(e) => format!("{e:#}"),
6803    };
6804    let fresh = losses_this_attempt(quota_before, &state.quota);
6805    let verdict = Verdict {
6806        status: state.status,
6807        // A run that opened a pull request handed its work over, whatever the
6808        // gate then decided about merging it.
6809        left_pr: state.pr.is_some(),
6810        // Only a rate limit earns the task its attempt back - and only one
6811        // suffered now: a refund justified by a previous session's loss is
6812        // the same mistake as re-arming the cooldown from it. A stalled run
6813        // resumed without hitting quota again therefore spends its attempt,
6814        // like any other failure of the task's own.
6815        quota_hit: !fresh.is_empty(),
6816        // A run that parked was asked to stop; that is not a failure and must
6817        // not spend an attempt, or replacing the binary a few times would
6818        // exhaust a task's budget without an agent ever misbehaving.
6819        parked: state.parked,
6820        // A quota loss that left nothing viable is the same machine fact as a
6821        // `Stalled` quota loss; see `settle`'s doc table.
6822        no_viable_candidates: state.viable().is_empty(),
6823    };
6824    if let Some(replacement) = &state.replaces
6825        && let Some(pr) = &state.pr
6826        && let Ok(mut old) = RunState::load(&replacement.run)
6827        && let Some(d) = &mut old.merge_decision
6828    {
6829        d.replacement_pr = Some(pr.url.clone());
6830        let _ = old.save();
6831    }
6832    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
6833    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
6834        task.hold_unrequested_retry(Some(format!(
6835            "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.",
6836            task.short()
6837        )));
6838    }
6839    if task.status == TaskStatus::Done {
6840        supersede_prior_runs(task, &crate::run::home());
6841    }
6842    record(queue, task);
6843    tracing::info!(
6844        "task {} is {} after run {} ({})",
6845        task.short(),
6846        task.status.as_str(),
6847        state.short(),
6848        label(state.status)
6849    );
6850    fresh
6851}
6852
6853/// A task a hand-started run leaves runnable (failed with attempts to spare,
6854/// or requeued) is **held**: nobody asked for a retry, and a loop starting
6855/// later must not spend agent calls on it. `magi task release` retries.
6856pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
6857    // Parked work (including legacy Failed records with a parked run) is a
6858    // checkpoint or owner handoff, not an unrequested retry.
6859    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
6860        && !awaiting_resume_with(task, RunState::load)
6861        // A run parked on the owner's word about a withheld PR title/body
6862        // resumes via `land_resume_state`, including review-only tasks that
6863        // `awaiting_resume_with` does not consider.
6864        && withheld_text_wait(task).is_none()
6865        && !(task.fresh_start && task.replacement.is_some())
6866    {
6867        let why = task.last_error.clone().map_or_else(
6868            || "the run did not finish".to_owned(),
6869            |e| format!("the run did not finish: {e}"),
6870        );
6871        task.hold_unrequested_retry(Some(format!(
6872            "{why}. It was started by hand, so it is not retried \
6873             automatically; `magi task release` retries it."
6874        )));
6875        record(queue, task);
6876    }
6877}
6878
6879/// Whether an attempt at a task whose newest run is `run` would resume that
6880/// run rather than start a fresh competition. `magi run --resume` hands a run
6881/// to a live loop only when this holds.
6882#[must_use]
6883pub fn loop_would_resume(run: &str) -> bool {
6884    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
6885}
6886
6887/// A loop in another process that is alive right now: a fresh heartbeat in
6888/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
6889/// carries the pid it published (`None` inside when it published none - a
6890/// fresh heartbeat is still evidence of a live loop).
6891///
6892/// The one judgement of "is somebody else serving this queue", shared by the
6893/// web UI's refusal to start a second loop and by `magi run` / `magi review`
6894/// deciding whether to hand a task to the loop. A claim file proves nothing
6895/// here: whether a claim succeeds says nothing about whether its owner lives.
6896#[must_use]
6897pub fn foreign_loop(
6898    reading: Option<&Reading>,
6899    now: Timestamp,
6900    own_pid: u32,
6901) -> Option<Option<u32>> {
6902    let reading = reading.filter(|r| r.running(now))?;
6903    match reading.pid {
6904        Some(pid) if pid == own_pid => None,
6905        pid => Some(pid),
6906    }
6907}
6908
6909fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
6910    reading.worker_protocol != Some(1)
6911        && (foreign_loop(Some(reading), now, own_pid).is_some()
6912            || reading
6913                .pid
6914                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
6915}
6916
6917/// Low-level claimed-task execution shared by the detached standalone worker
6918/// and focused lifecycle fixtures. The caller must retain the queue claim for
6919/// this entire call. CLI callers transfer ownership through
6920/// [`run_detached_claimed`] instead of executing inside their own runtime.
6921///
6922/// The one deliberate difference from the loop: a task the attempt leaves
6923/// runnable (failed with attempts to spare, or requeued) is **held** instead.
6924/// Nobody asked for a retry, and a daemon starting later must not spend agent
6925/// calls re-running a hand-started task behind the operator's back;
6926/// `magi task release` is the explicit retry.
6927pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
6928    run_claimed_until(opts, queue, task, &Stop::new()).await;
6929}
6930
6931async fn run_claimed_until(
6932    opts: &Opts,
6933    queue: &Queue,
6934    task: &mut Task,
6935    stop: &Stop,
6936) -> Vec<QuotaLoss> {
6937    let status = Arc::new(Mutex::new(Status::new()));
6938    // An attempt embeds startup and graph futures. Keep it off the standalone
6939    // caller's stack, on both the initial execution and withheld-text resume.
6940    let mut quota = Box::pin(attempt(
6941        opts,
6942        queue,
6943        &status,
6944        stop,
6945        crate::graph::Pause::new(),
6946        task,
6947    ))
6948    .await;
6949    // A run parked on the owner's word about a withheld PR title/body has no
6950    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
6951    // here with the claim still held, and resume once the question is settled
6952    // (answered, or abandoned at its deadline -> the neutral text).
6953    // A rejected reply files one more question (the gate asks at most twice),
6954    // so after a resume the run may be waiting again: keep going, with a fresh
6955    // limit for the new question. `resumes` bounds it even if a resume parks
6956    // without asking anything new.
6957    let mut resumes = 0;
6958    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
6959        let Some(timeout) = withheld_text_wait(task) else {
6960            break;
6961        };
6962        eprintln!(
6963            "waiting for the owner's answer on a withheld pull request text \
6964             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
6965        );
6966        // The deadline abandons the question itself; the extra margin only
6967        // covers an abandon that could not be saved.
6968        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
6969        let ready = loop {
6970            match land_resume_state(task) {
6971                LandResume::StillWaiting
6972                    if !stop.parking() && std::time::Instant::now() < limit =>
6973                {
6974                    tokio::time::sleep(WITHHELD_POLL).await;
6975                }
6976                LandResume::Ready => break true,
6977                _ => break false,
6978            }
6979        };
6980        if !ready || stop.parking() {
6981            break;
6982        }
6983        resumes += 1;
6984        quota.extend(
6985            Box::pin(attempt(
6986                opts,
6987                queue,
6988                &status,
6989                stop,
6990                crate::graph::Pause::new(),
6991                task,
6992            ))
6993            .await,
6994        );
6995    }
6996    hold_if_runnable(queue, task);
6997    quota
6998}
6999
7000/// Resumes an in-process run makes for withheld-text questions: the gate asks
7001/// at most twice, plus one for a resume that asks nothing new.
7002const MAX_WITHHELD_RESUMES: u32 = 3;
7003
7004/// How often an in-process run rechecks its withheld-text question.
7005const WITHHELD_POLL: Duration = Duration::from_secs(15);
7006
7007/// The `answer_timeout` (seconds) of the task's last run when that run is
7008/// parked on an unresolved withheld-text question; `None` otherwise.
7009fn withheld_text_wait(task: &Task) -> Option<u64> {
7010    let id = task.execution_runs().last()?;
7011    let s = RunState::load(id).ok()?;
7012    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
7013        .then_some(s.config.graph.answer_timeout)
7014}
7015
7016/// The quota losses `after` holds that `before` did not: what one execution
7017/// suffered, as opposed to the run's history.
7018///
7019/// Compared by value rather than by length or position because
7020/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
7021/// the vector can shrink and shift under a resume. A retried seat that hits
7022/// quota again is a `push` with a new `at`, so it shows up as new here.
7023/// Crash recovery uses the recorded pass start as its boundary when available;
7024/// legacy records without passes retain their original history-based policy.
7025fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
7026    after
7027        .iter()
7028        .filter(|q| !before.contains(q))
7029        .cloned()
7030        .collect()
7031}
7032
7033/// When the loop-wide quota cooldown should end, given this attempt's losses;
7034/// `None` when there were none. Reset-hint parsing and the cap live here.
7035fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
7036    let quota: Vec<_> = quota
7037        .iter()
7038        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
7039        .collect();
7040    if quota.is_empty() {
7041        return None;
7042    }
7043    let with_hint = quota.iter().find(|q| q.reset.is_some());
7044    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
7045    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
7046    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
7047    Some(
7048        now.checked_add(jiff::SignedDuration::from_secs(secs))
7049            .unwrap_or(Timestamp::MAX),
7050    )
7051}
7052
7053/// An explicit task count must agree with a run before any resume.
7054fn implementers_match(task: &Task, state: &RunState) -> bool {
7055    task.replacement.as_ref().map_or_else(
7056        || {
7057            task.implementers()
7058                .is_none_or(|n| n == state.config.graph.implementers)
7059        },
7060        |replacement| {
7061            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
7062                && state.config.graph.implementers == 1
7063        },
7064    )
7065}
7066
7067/// Never resume or take over candidate work built for a different seat count.
7068fn starter_with_implementers(
7069    task: &Task,
7070    previous: Option<&RunState>,
7071    proposed: Starter,
7072) -> Starter {
7073    if previous.is_some_and(|s| !implementers_match(task, s)) {
7074        task.review_of
7075            .as_ref()
7076            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
7077    } else {
7078        proposed
7079    }
7080}
7081
7082/// Apply this task's explicit count to the new attempt, without changing defaults.
7083fn apply_task_implementers(config: &mut Config, task: &Task) {
7084    if let Some(n) = task.implementers() {
7085        config.graph.implementers = n;
7086    }
7087}
7088
7089/// [`prepare`] for one task: its own `--config` and command-line overrides
7090/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
7091/// over the loop's, so handing a hand-started task to a daemon changes nothing
7092/// about what it does.
7093#[cfg(test)]
7094fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
7095    let explicit = match &task.overrides {
7096        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
7097        _ => opts.config.as_deref(),
7098    };
7099    let (mut config, _) = Config::discover(repo, explicit)?;
7100    apply_options(&mut config, opts, task)?;
7101    Ok(config)
7102}
7103
7104fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
7105    if task
7106        .overrides
7107        .as_ref()
7108        .is_none_or(|o| o.inherit_daemon_options)
7109        && let Some(mode) = opts.merge.as_deref()
7110    {
7111        config.merge.mode = merge_mode(mode)?;
7112    }
7113    if let Some(o) = &task.overrides {
7114        o.apply(config);
7115    }
7116    if let Some((mode, _)) = task.build_cache_override(config) {
7117        config.verify.build_cache = mode;
7118    }
7119    Ok(())
7120}
7121
7122/// Load the config for a task's repository, with the merge override applied.
7123fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
7124    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
7125    if let Some(mode) = &opts.merge {
7126        config.merge.mode = merge_mode(mode)?;
7127    }
7128    Ok(config)
7129}
7130
7131/// Prune the shared build cache at a between-runs boundary. The detached cache
7132/// service checks authoritative task jobs first; dispatch waits for that finite
7133/// service, so scheduler replacement cannot turn a compile into idle cleanup.
7134/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
7135async fn maybe_prune_cache_between_runs(
7136    repo: &Path,
7137    opts: &Opts,
7138    home: &Path,
7139    stop: &Stop,
7140    last_checked: &mut Option<Timestamp>,
7141    now: Timestamp,
7142) {
7143    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
7144        return;
7145    }
7146    *last_checked = Some(now);
7147    let cfg = match prepare(repo, opts) {
7148        Ok(cfg) => cfg,
7149        Err(e) => {
7150            tracing::warn!("cache check: no config: {e:#}");
7151            return;
7152        }
7153    };
7154    match clean::prune_cache_if_over_limit(&cfg, home) {
7155        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
7156            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
7157            pruned.files,
7158            pruned.freed
7159        ),
7160        Ok(_) => {}
7161        Err(e) => {
7162            tracing::warn!("housekeep: prune cache: {e:#}");
7163            notices::raise_in(
7164                home,
7165                Notice::warn(
7166                    "housekeep:cache",
7167                    format!(
7168                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
7169                        e.to_string()
7170                            .lines()
7171                            .next()
7172                            .unwrap_or("unknown cleanup error")
7173                    ),
7174                ),
7175            );
7176        }
7177    }
7178}
7179
7180/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
7181/// now, given when it last did (if ever). Pure, so the cadence is asserted
7182/// directly rather than by waiting out real minutes in a test.
7183fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
7184    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
7185}
7186
7187/// The disk janitor, with its housekeeping logged rather than fatal.
7188///
7189/// Called only at the loop's idle points, for the reason the caller documents:
7190/// a prune racing a live compile would delete files mid-build. The config is
7191/// re-read on every call because the repository that just ran may not be the
7192/// daemon's own default, and the cache directory is a repository fact.
7193///
7194/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
7195/// and [`crate::run::default_worktree_root`] read here, for the same reason
7196/// [`drive`] takes its queue and status file rather than resolving them: a
7197/// test driving the loop must not reach through to the operator's real home
7198/// or worktree bay just because the janitor runs on every idle tick.
7199/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
7200/// to get wrong silently - a test's `home` was already isolated, but nothing
7201/// exercised the parameter next to it, so a real worktree bay stayed wired in
7202/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
7203/// it for real, every test in this file that drives the loop at all started
7204/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
7205async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
7206    let cfg = match prepare(repo, opts) {
7207        Ok(cfg) => cfg,
7208        Err(e) => {
7209            tracing::warn!("housekeep: no config: {e:#}");
7210            return;
7211        }
7212    };
7213    // A run's own worktree lives under `config.graph.worktree_root` when the
7214    // repository sets one - the same precedence `RunState::worktree_root`
7215    // uses - and `worktrees_root` only stands in for the *default* an
7216    // unconfigured repository resolves to (see this function's own
7217    // parameter, or the test fixture wiring one to a fake path). Housekeeping
7218    // that always swept the default regardless of this override would never
7219    // see, and so never reclaim, a single worktree for a repository that
7220    // relocated them elsewhere.
7221    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
7222    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
7223    // Reported whenever there is anything to say, not only when `folded > 0`:
7224    // the incident this exists to prevent was 90 of 93 runs skipped and 0
7225    // folded, on every single pass, for months - a report gated on `folded`
7226    // would have stayed silent through every one of them.
7227    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
7228        let mut extra = Vec::new();
7229        if out.unreadable > 0 {
7230            extra.push(format!("{} unreadable", out.unreadable));
7231        }
7232        if out.orphaned_worktrees > 0 {
7233            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
7234        }
7235        let detail = if extra.is_empty() {
7236            String::new()
7237        } else {
7238            format!(" ({})", extra.join(", "))
7239        };
7240        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
7241    }
7242    if out.external_merges_recorded > 0 {
7243        tracing::info!(
7244            "housekeep: recorded {} run(s) as merged externally",
7245            out.external_merges_recorded
7246        );
7247    }
7248    if out.stale_pr_states_repaired > 0 {
7249        tracing::info!(
7250            "housekeep: updated {} run record(s) from the current pull request state",
7251            out.stale_pr_states_repaired
7252        );
7253    }
7254    if out.cache_files > 0 {
7255        tracing::info!(
7256            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
7257            out.cache_files,
7258            out.cache_freed
7259        );
7260    }
7261    if out.questions_abandoned > 0 {
7262        tracing::info!(
7263            "housekeep: abandoned {} question(s) left open by a finished run",
7264            out.questions_abandoned
7265        );
7266    }
7267}
7268
7269/// Run [`triage::run_once`] and log whatever it did, the same "only when
7270/// there is something to say" rule [`janitor`] follows for its own report.
7271///
7272/// Called at the same idle points as [`janitor`] - once per full poll
7273/// interval, never mid-attempt - for the same reason: it is not liveness
7274/// critical, and a task's own `hold_reason` string is the one thing this
7275/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
7276/// tick for no benefit.
7277async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
7278    let questions = Questions::at(home.join("questions"));
7279    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
7280    if report.is_empty() {
7281        return;
7282    }
7283    if !report.quarantined.is_empty() {
7284        tracing::info!(
7285            "triage: held {} blocked task(s) whose blocked-on task or \
7286             question no longer exists: {}",
7287            report.quarantined.len(),
7288            report.quarantined.join(", ")
7289        );
7290    }
7291    if !report.resumed.is_empty() {
7292        tracing::info!(
7293            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
7294            report.resumed.len(),
7295            report.resumed.join(", ")
7296        );
7297    }
7298    if !report.asked.is_empty() {
7299        tracing::info!(
7300            "triage: asked about {} held task(s): {}",
7301            report.asked.len(),
7302            report.asked.join(", ")
7303        );
7304    }
7305    if !report.answered.is_empty() {
7306        tracing::info!(
7307            "triage: applied {} operator answer(s): {}",
7308            report.answered.len(),
7309            report.answered.join(", ")
7310        );
7311    }
7312}
7313
7314/// The free-space gate: what stands between this task and a new run, if
7315/// anything. `Some(reason)` holds the task; `None` lets it start.
7316///
7317/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
7318/// the operator opted out. A measurement failure is a gate, not a pass: both
7319/// sides of "cannot tell" are served by not starting.
7320pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
7321    disk_gate_at(repo, config, crate::run::home)
7322}
7323
7324pub(crate) fn disk_gate_at(
7325    repo: &Path,
7326    config: &Config,
7327    home: impl FnOnce() -> PathBuf,
7328) -> Option<String> {
7329    let measure = if crate::build_target::isolated(config) {
7330        crate::disk::managed_free_bytes
7331    } else {
7332        crate::disk::free_bytes
7333    };
7334    disk_gate_with(repo, config, home, measure)
7335}
7336
7337/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
7338/// test can assert the exact wiring `attempt` runs - config's threshold in,
7339/// task-holding reason out - without asking the real machine's disk anything.
7340fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
7341    repo: &Path,
7342    config: &Config,
7343    home: impl FnOnce() -> PathBuf,
7344    free_bytes: F,
7345) -> Option<String> {
7346    let min = config.disk.min_free_bytes;
7347    if min == 0 {
7348        return None;
7349    }
7350    let output = match config.verify.build_cache {
7351        BuildCache::Shared => config.cache_dir(),
7352        BuildCache::Isolated => Some(home()),
7353    };
7354    let default_worktree_root;
7355    let worktree_root = match config.graph.worktree_root.as_deref() {
7356        Some(root) => root,
7357        None => {
7358            default_worktree_root = crate::run::default_worktree_root();
7359            &default_worktree_root
7360        }
7361    };
7362    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
7363        .into_iter()
7364        .flatten()
7365    {
7366        let probe = if path == repo {
7367            path
7368        } else {
7369            path.ancestors().find(|p| p.exists()).unwrap_or(path)
7370        };
7371        let reason = match free_bytes(probe) {
7372            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
7373            Err(e) => Some(crate::disk::unmeasured_in(
7374                probe,
7375                &e,
7376                &config.graph.language,
7377            )),
7378        };
7379        if reason.is_some() {
7380            return reason;
7381        }
7382    }
7383    None
7384}
7385
7386/// How long to wait before offering another task when a run lost a seat to a
7387/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
7388/// could read, or carried nothing at all. Long enough that a quota outage
7389/// cannot burn through a whole backlog in the few seconds each doomed attempt
7390/// takes to fail; short enough that a quota which clears early is not left
7391/// idle for the fallback's sake.
7392const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
7393
7394/// Longest a parsed reset hint may push the wait out to. The hint comes from
7395/// the CLI's own words, not a contract, so a parsing slip that lands a day
7396/// away must not leave the loop asleep for a day.
7397const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
7398
7399/// How long [`poll`] should wait before offering the next task, after a run
7400/// lost at least one seat to a rate limit.
7401///
7402/// Pure and separate from the loop so the policy can be exercised without a
7403/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
7404/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
7405/// nothing to parse, or the parsed time has already passed; `cap` bounds how
7406/// far a parsed hint is trusted to push the wait out.
7407fn quota_wait(
7408    reset_at: Option<Timestamp>,
7409    now: Timestamp,
7410    fallback: Duration,
7411    cap: Duration,
7412) -> Duration {
7413    match reset_at {
7414        Some(at) if at > now => {
7415            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
7416            Duration::from_secs(secs).min(cap)
7417        }
7418        _ => fallback,
7419    }
7420}
7421
7422/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
7423///
7424/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
7425/// explains why parsing it exactly "would be a bug factory" — so this only
7426/// recognises the shapes actually observed in the wild, and returns `None`
7427/// for anything else rather than guess at a format nobody has seen.
7428///
7429/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
7430/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
7431/// said it, not from whenever this loop happens to read it: anchoring on `now`
7432/// would push the reset later on every read and would read an already-elapsed
7433/// reset as still in the future. (A long hint is still clamped by
7434/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
7435fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
7436    parse_reset_hint_zoned(text, now)
7437        .or_else(|| parse_reset_hint_dated(text))
7438        .or_else(|| parse_reset_hint_relative(text, recorded))
7439}
7440
7441/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
7442/// optional but at least one required, in that order. A bare number or any
7443/// unknown unit is refused.
7444fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
7445    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
7446    let mut rest = rest.trim();
7447    if rest.is_empty() {
7448        return None;
7449    }
7450    let mut total: i64 = 0;
7451    let mut matched = false;
7452    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
7453        if let Some((digits, tail)) = rest.split_once(unit)
7454            && !digits.is_empty()
7455            && digits.bytes().all(|b| b.is_ascii_digit())
7456        {
7457            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
7458            rest = tail;
7459            matched = true;
7460        }
7461    }
7462    if !rest.is_empty() || !matched {
7463        return None;
7464    }
7465    recorded
7466        .checked_add(jiff::SignedDuration::from_secs(total))
7467        .ok()
7468}
7469
7470/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
7471/// case-insensitive) into a 24-hour hour and minute. Shared by every
7472/// reset-hint shape below.
7473fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
7474    let clock = clock.trim().to_lowercase();
7475    let (digits, pm) = clock
7476        .strip_suffix("am")
7477        .map(|d| (d, false))
7478        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
7479    let (h, m) = digits.trim().split_once(':')?;
7480    let mut hour: i8 = h.trim().parse().ok()?;
7481    let minute: i8 = m.trim().parse().ok()?;
7482    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
7483        return None;
7484    }
7485    if pm && hour != 12 {
7486        hour += 12;
7487    } else if !pm && hour == 12 {
7488        hour = 0;
7489    }
7490    Some((hour, minute))
7491}
7492
7493/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
7494/// and a zone, never a date. A clock reading already past today is read as
7495/// tomorrow's: a CLI naming a same-day reset that has already gone by means
7496/// the window rolled over while nothing was watching.
7497fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
7498    let open = text.find('(')?;
7499    let close = text.rfind(')')?;
7500    if close <= open {
7501        return None;
7502    }
7503    let zone = text[open + 1..close].trim();
7504    let (hour, minute) = parse_12h_clock(&text[..open])?;
7505    let tz = jiff::tz::TimeZone::get(zone).ok()?;
7506    let candidate = now
7507        .to_zoned(tz)
7508        .with()
7509        .hour(hour)
7510        .minute(minute)
7511        .second(0)
7512        .millisecond(0)
7513        .microsecond(0)
7514        .nanosecond(0)
7515        .build()
7516        .ok()?;
7517    let mut at = candidate.timestamp();
7518    if at <= now {
7519        at += jiff::SignedDuration::from_hours(24);
7520    }
7521    Some(at)
7522}
7523
7524/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
7525/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
7526/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
7527/// "already past today" correction to make: the year already disambiguates
7528/// it. Scanned as a five-word window so it can be pulled out of the middle
7529/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
7530/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
7531/// any other timestamp with no zone attached.
7532fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
7533    let words: Vec<&str> = text.split_whitespace().collect();
7534    if words.len() < 5 {
7535        return None;
7536    }
7537    (0..=words.len() - 5)
7538        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
7539}
7540
7541/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
7542/// parenthesis right after the window is refused rather than ignored — it
7543/// reads as an explicit zone annotation on a shape that otherwise carries
7544/// none, and guessing UTC anyway would be exactly the silent misread this
7545/// module's parsing otherwise avoids.
7546fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
7547    if trailing.is_some_and(|next| next.starts_with('(')) {
7548        return None;
7549    }
7550    let month = month_number(window[0])?;
7551    let day_token = window[1].strip_suffix(',')?.to_lowercase();
7552    let day_digits = ["st", "nd", "rd", "th"]
7553        .iter()
7554        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
7555    let day: i8 = day_digits.parse().ok()?;
7556    let year_token = window[2];
7557    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
7558        return None;
7559    }
7560    let year: i16 = year_token.parse().ok()?;
7561    // The am/pm word carries the sentence's own trailing punctuation, e.g.
7562    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
7563    // reusing the same 12-hour clock reader the bracketed shape uses.
7564    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
7565    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
7566    let date = jiff::civil::Date::new(year, month, day).ok()?;
7567    let candidate = date
7568        .at(hour, minute, 0, 0)
7569        .to_zoned(jiff::tz::TimeZone::UTC)
7570        .ok()?;
7571    Some(candidate.timestamp())
7572}
7573
7574/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
7575/// case-insensitively, into a 1-based month number.
7576fn month_number(name: &str) -> Option<i8> {
7577    const NAMES: [&str; 12] = [
7578        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
7579    ];
7580    let lower = name.to_lowercase();
7581    NAMES
7582        .iter()
7583        .position(|n| *n == lower.as_str())
7584        .map(|i| i as i8 + 1)
7585}
7586
7587/// Test probe for the shared resume policy's review-budget exclusion.
7588#[cfg(test)]
7589fn exhausted_review_budget(state: &RunState) -> bool {
7590    // A run whose task-head publication failed has nothing left to review:
7591    // resuming it only retries the publication, so it is never "exhausted".
7592    !crate::handover::can_resume(state)
7593        && state.status == RunStatus::Blocked
7594        && !state.released()
7595        && state.retired_to.is_none()
7596}
7597
7598/// This task's *most recent* run, if resuming it would actually make
7599/// progress. `short` is only for the warning's own message.
7600///
7601/// Only ever `runs.last()` — never a search back through older history.
7602/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
7603/// mint, oldest first, and every entry before the last one was already
7604/// superseded at the moment it was minted: the daemon only ever starts a new
7605/// run when the previous one was not worth resuming (unresumable, exhausted,
7606/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
7607/// opens a fresh review-only run alongside an older, already-failed
7608/// competition. Searching further back would let an old run that merely
7609/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
7610/// behind, say — get resumed instead of the fresh competition
7611/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
7612/// nothing asked to revisit.
7613///
7614/// Two runs paid for the "prefer resuming over restarting" half of this
7615/// lesson, which is why this still checks `runs.last()` rather than always
7616/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
7617/// task a moment later, duplicating two and a half hours of agent work. Then
7618/// b25f stalled on a judge that timed out and one that answered with no JSON
7619/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
7620/// **one second** later, buying three fresh implementations to reach the
7621/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
7622/// the second case: a stall is terminal, and its cheap recovery re-asks only
7623/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
7624/// that is technically `resumable()` but provably cannot progress must not
7625/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
7626/// no-op instead of the fresh competition it promises.
7627///
7628/// A load failure is warned about rather than silently read as "not
7629/// resumable": the alternative is exactly what let a schema mismatch on run
7630/// `eba2` fall through to a full re-competition with nobody told why.
7631/// `crate::conduct` is what actually offers a better answer than
7632/// `Runner::start` here (see `Recovery::Review`), once this task's next
7633/// failure shows it up as `held`/`failed` with the run state unreadable.
7634fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
7635    unfinished_run_with(runs, short, RunState::load)
7636}
7637
7638/// [`unfinished_run`] with an injected state reader. Tests provide their
7639/// fixtures directly rather than touching the process-global run home.
7640pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
7641where
7642    F: FnMut(&str) -> Result<RunState>,
7643{
7644    let mut id = runs.last()?.clone();
7645    let mut visited = std::collections::BTreeSet::new();
7646    let mut repo = None;
7647    loop {
7648        if !runs.contains(&id) || !visited.insert(id.clone()) {
7649            tracing::warn!("invalid or cyclic recovery authority for task {short}");
7650            return None;
7651        }
7652        let state = match load(&id) {
7653            Ok(state) if state.id == id => state,
7654            Ok(_) => return None,
7655            Err(e) => {
7656                tracing::warn!("could not read run {id} for task {short}: {e:#}");
7657                return None;
7658            }
7659        };
7660        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
7661            return None;
7662        }
7663        repo = Some(state.repo.clone());
7664        if let Some(authority) = state.retired_to {
7665            id = authority;
7666            continue;
7667        }
7668        return (crate::handover::can_resume(&state)
7669            && state.liveness(false) != crate::run::Liveness::Live)
7670            .then_some(id);
7671    }
7672}
7673
7674/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
7675/// that [`attempt`] will resume it on its own?
7676///
7677/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
7678/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
7679/// injected reader like its sibling. An unreadable run is not awaiting
7680/// anything: it keeps going to the conductor as before.
7681fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
7682where
7683    F: FnOnce(&str) -> Result<RunState>,
7684{
7685    // `Failed` stays: a record an older build wrote for a parked run.
7686    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
7687        || task.fresh_start
7688        || task.review_branch.is_some()
7689    {
7690        return false;
7691    }
7692    let Some(id) = task.execution_runs().last() else {
7693        return false;
7694    };
7695    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
7696}
7697
7698/// Which of the three ways [`attempt`] can mint or continue a run this task
7699/// should use.
7700#[derive(Debug, Clone, PartialEq, Eq)]
7701enum Starter {
7702    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
7703    /// and that still exists.
7704    Review(String),
7705    /// `crate::graph::Runner::resume` on an unfinished run of this task.
7706    Resume(String),
7707    /// `crate::graph::Runner::start`: a fresh competition.
7708    Start,
7709}
7710
7711fn load_retained_attempt(home: &Path, id: &str) -> Result<Option<RunState>> {
7712    match RunState::load_under(id, home) {
7713        Ok(state) => Ok(Some(state)),
7714        Err(error)
7715            if error
7716                .downcast_ref::<std::io::Error>()
7717                .is_some_and(|io| io.kind() == std::io::ErrorKind::NotFound)
7718                && !run_directory_present(&home.join("runs").join(id))? =>
7719        {
7720            Ok(None)
7721        }
7722        Err(error) => Err(error),
7723    }
7724}
7725
7726/// A second bound independent of inputs and the resettable failure counter.
7727/// Count execution and failed-startup recovery records once per run. Startup
7728/// failures can retain unrecorded preparation assets without an execution pass.
7729/// Unknown history is not evidence that a new set of worktrees is affordable.
7730fn retained_attempt_hold(
7731    task: &Task,
7732    starter: &Starter,
7733    limit: usize,
7734    mut load: impl FnMut(&str) -> Result<Option<RunState>>,
7735) -> Option<String> {
7736    if limit == 0 || matches!(starter, Starter::Resume(_)) {
7737        return None;
7738    }
7739    let mut retained = 0;
7740    for id in task
7741        .runs
7742        .iter()
7743        .chain(task.startup_failures.iter().map(|failure| &failure.run))
7744        .collect::<std::collections::BTreeSet<_>>()
7745    {
7746        let state = match load(id) {
7747            Ok(Some(state)) if state.id == *id => state,
7748            Ok(None)
7749                if !task
7750                    .startup_failures
7751                    .iter()
7752                    .any(|failure| failure.run == *id) =>
7753            {
7754                continue;
7755            }
7756            _ => {
7757                return Some(format!(
7758                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
7759                ));
7760            }
7761        };
7762        if state.retired_to.is_some() || state.released() {
7763            continue;
7764        }
7765        // Neither a completed status nor an empty candidate array proves that
7766        // all recovery sources (including unrecorded preparation) were retired.
7767        retained += 1;
7768    }
7769    (retained >= limit).then(|| format!(
7770        "[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."
7771    ))
7772}
7773
7774/// A selected public implementation overrides every historical candidate and pin.
7775fn selected_starter(
7776    selected: &crate::pr_recovery::Selection,
7777    previous: Option<&RunState>,
7778    unfinished: Option<&str>,
7779) -> Starter {
7780    if let Some(id) = unfinished
7781        && previous.is_some_and(|r| {
7782            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
7783        })
7784    {
7785        Starter::Resume(id.to_owned())
7786    } else {
7787        Starter::Review(selected.branch.clone())
7788    }
7789}
7790
7791/// The owner's answer to this branch's divergence question, consumed from the
7792/// task so a later, different divergence asks again. The runner applies it
7793/// (see `Runner::review_taking_over`), after the earlier worktree is released.
7794fn take_divergence_answer(
7795    branch: &str,
7796    remote: &str,
7797    task: &mut Task,
7798) -> Option<crate::reconcile::Choice> {
7799    let summary = crate::reconcile::summary_for(branch, remote);
7800    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
7801        (a.question == summary)
7802            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
7803            .flatten()
7804            .map(|c| (i, c))
7805    })?;
7806    task.answers.remove(idx);
7807    Some(choice)
7808}
7809
7810/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
7811/// this attempt should use. Pure, and separate from [`attempt`], so the
7812/// routing itself is assertable without spawning a real graph or a git
7813/// process: `attempt`'s own `crate::git::branch_exists` call has already
7814/// happened by the time this is called.
7815///
7816/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
7817/// whose branch is gone falls all the way through to [`Starter::Start`], not
7818/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
7819/// old (likely `Blocked`) run in the first place, and a branch that vanished
7820/// out from under that choice is not evidence resuming it would fare better.
7821fn choose_starter(
7822    review_branch: Option<&str>,
7823    branch_exists: bool,
7824    unfinished: Option<&str>,
7825) -> Starter {
7826    match review_branch {
7827        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
7828        Some(_) => Starter::Start,
7829        None => match unfinished {
7830            Some(id) => Starter::Resume(id.to_owned()),
7831            None => Starter::Start,
7832        },
7833    }
7834}
7835
7836/// Reuse a compatible latest review owner instead of taking its checked-out
7837/// branch into a new run. Different branches and changed criteria still use
7838/// the ordinary review/takeover policy.
7839fn review_retry_starter(
7840    task: &Task,
7841    previous: Option<&RunState>,
7842    branch: Option<&str>,
7843    exists: bool,
7844    unfinished: Option<&str>,
7845) -> Starter {
7846    if let Some(run) = previous
7847        && unfinished == Some(run.id.as_str())
7848        && run.reviewed_commits.is_some()
7849        && branch.is_some_and(|branch| {
7850            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
7851        })
7852        && may_resume_run(run, task)
7853    {
7854        return Starter::Resume(run.id.clone());
7855    }
7856    match (branch, unfinished, &task.review_of) {
7857        (None, None, Some(branch)) => Starter::Review(branch.clone()),
7858        _ => choose_starter(branch, exists, unfinished),
7859    }
7860}
7861
7862/// A retained review is valid only while its authored criteria still match.
7863fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
7864    task.review_branch
7865        .as_deref()
7866        .filter(|&branch| match &task.review_instruction {
7867            Some(authored) => *authored == task.instruction,
7868            // Legacy retained branches must agree with their prior run; only an
7869            // explicitly pinned review can proceed without recoverable provenance.
7870            None => previous.map_or_else(
7871                || task.review_of.as_deref() == Some(branch),
7872                |run| compatible_run_instruction(run, task),
7873            ),
7874        })
7875}
7876
7877/// A current explicit pin can select an otherwise incompatible run. Edits
7878/// and subsequent approvals invalidate pins selected for earlier criteria.
7879fn may_resume_run(run: &RunState, task: &Task) -> bool {
7880    if !task.assignment_accepts(run) {
7881        return false;
7882    }
7883    task.resume_override
7884        .as_ref()
7885        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
7886        || compatible_run_instruction(run, task)
7887}
7888
7889/// Review scaffolding is execution context, not evidence of an operator edit.
7890pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
7891    if run.task_instruction_rev.unwrap_or(0) != task.instruction_rev {
7892        return false;
7893    }
7894    if let Some(authored) = &run.task_instruction {
7895        return compatible_instruction(authored, task);
7896    }
7897    if compatible_instruction(&run.instruction, task) {
7898        return true;
7899    }
7900    // Recognize only the existing generated review shapes on legacy runs.
7901    // Ordinary authored text with a similar heading is left intact.
7902    if run.reviewed_commits.is_some() {
7903        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
7904            return strip_answers_block(authored, task).trim() == task.instruction.trim();
7905        }
7906        if let Some(branch) = &task.review_of {
7907            let canonical = format!(
7908                "Review the branch `{branch}` (review-only: no implementation, no judging)."
7909            );
7910            let generated = format!(
7911                "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"
7912            );
7913            return task.instruction == canonical && run.instruction.starts_with(&generated);
7914        }
7915    }
7916    false
7917}
7918
7919/// Compare authored instructions, excluding answer blocks appended by the daemon.
7920pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
7921    strip_answers_block(old, task) == task.instruction
7922}
7923
7924/// Which repository a task runs in. A task that names none — the normal case
7925/// for one filed from a phone — runs in the daemon's own default.
7926fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
7927    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
7928        return fallback.to_path_buf();
7929    }
7930    task.repo.clone()
7931}
7932
7933/// The header [`append_answers`] appends operator answers under. Shared with
7934/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
7935/// rather than grown a new block on every resume.
7936const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
7937
7938/// Render the first `count` answers in the block appended to an instruction.
7939fn answers_block(task: &Task, count: usize) -> String {
7940    let mut s = ANSWERS_HEADER.to_owned();
7941    for a in &task.answers[..count] {
7942        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
7943    }
7944    s
7945}
7946
7947/// Render the approval independently of transient task state, so historical
7948/// suffixes remain recognizable after another explicit release.
7949fn resumption_block(r: &crate::queue::Resumption) -> String {
7950    format!(
7951        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
7952         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
7953        r.generation, r.at, r.instruction, r.answers_through,
7954    )
7955}
7956
7957/// Append audit answers and the latest explicit approval to the instruction.
7958fn append_answers(base: &str, task: &Task) -> String {
7959    let mut s = base.to_owned();
7960    if !task.answers.is_empty() {
7961        s.push_str(&answers_block(task, task.answers.len()));
7962    }
7963    if let Some(r) = &task.resumption {
7964        s.push_str(&resumption_block(r));
7965    }
7966    s
7967}
7968
7969/// Drop the prior answer block only when it is exactly the suffix this task
7970/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
7971/// the task author is ordinary instruction text, not a block to remove.
7972fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
7973    let mut instruction = instruction;
7974    for approval in task
7975        .resumption
7976        .iter()
7977        .chain(task.resumption_history.iter().rev())
7978    {
7979        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
7980            instruction = base;
7981            break;
7982        }
7983    }
7984    for count in (1..=task.answers.len()).rev() {
7985        let block = answers_block(task, count);
7986        if let Some(base) = instruction.strip_suffix(&block) {
7987            return base;
7988        }
7989    }
7990    instruction
7991}
7992
7993/// The instruction handed to `Runner::start`: the task's own text, plus any
7994/// operator answers `crate::conduct` collected for it (see
7995/// [`Task::answers`]), so a decision the operator actually made reaches the
7996/// implementers rather than only clearing the block that was waiting on it.
7997///
7998/// Appended rather than merged into [`Task::instruction`] itself, so the
7999/// task's own record stays exactly what its author wrote.
8000fn instruction_for(task: &Task) -> String {
8001    append_answers(&task.instruction, task)
8002}
8003
8004/// The instruction a resumed run should carry on with: whatever it already
8005/// had, refreshed with the task's *current* operator answers.
8006///
8007/// A resumable run's own `RunState::instruction` predates any answer
8008/// `crate::conduct` collects after the run parks, so resuming it unchanged —
8009/// the behaviour before this function existed — silently drops the very
8010/// decision the operator made to unblock it. Re-stripping any block this
8011/// function appended on an earlier resume before re-appending the current
8012/// list (rather than blindly appending again) is what keeps a task resumed
8013/// three times over three answered questions from carrying the same answer
8014/// three times.
8015fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
8016    append_answers(strip_answers_block(old_instruction, task), task)
8017}
8018
8019/// Preserve the producer's verified boundary and target, independent of prose.
8020fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
8021    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
8022    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
8023    if let Some(cause) = task.hold_notice_cause.as_mut() {
8024        cause.target = failure.map(|f| f.target.clone());
8025    }
8026}
8027
8028#[derive(Debug, thiserror::Error)]
8029#[error("attachment `{name}` is recorded on the task but {path} is missing")]
8030struct MissingAttachment {
8031    name: String,
8032    path: PathBuf,
8033}
8034
8035/// The task's attachments as absolute paths, each checked to still exist.
8036fn task_attachments(
8037    queue: &Queue,
8038    task: &Task,
8039) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
8040    let paths = queue.attachment_paths(task);
8041    for (name, path) in task.attachments.iter().zip(&paths) {
8042        if !path.is_file() {
8043            return Err(MissingAttachment {
8044                name: name.clone(),
8045                path: path.clone(),
8046            });
8047        }
8048    }
8049    Ok(paths)
8050}
8051
8052/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
8053/// answers before handing it to `Runner` — the actual boundary between
8054/// [`choose_starter`]'s routing and the graph, factored out so it is
8055/// assertable without a real repository, git branch, or agent CLI.
8056///
8057/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
8058/// instruction from the reviewed branch's own commit log because there is no
8059/// task statement to speak of for hand-written work, and splicing operator
8060/// answers into that text would contradict the very message it sends
8061/// reviewers ("there is no task statement").
8062fn prepare_instruction(
8063    starter: &Starter,
8064    old_instruction: Option<&str>,
8065    task: &Task,
8066) -> Option<String> {
8067    match starter {
8068        Starter::Start => Some(instruction_for(task)),
8069        Starter::Resume(_) => Some(resumed_instruction(
8070            old_instruction.expect("a resumed run always has a prior instruction"),
8071            task,
8072        )),
8073        Starter::Review(_) => None,
8074    }
8075}
8076
8077/// Persist a transition. A queue write failure is logged rather than fatal: the
8078/// run already happened, and taking the daemon down would only add a lost
8079/// backlog to a full disk.
8080fn record(queue: &Queue, task: &mut Task) {
8081    if let Err(e) = queue.put(task) {
8082        tracing::error!("could not record task {}: {e:#}", task.short());
8083        let notice = Notice::error(
8084            "loop:record",
8085            format!(
8086                "Task {} state could not be saved: {}. Check the disk.",
8087                task.id,
8088                e.to_string().lines().next().unwrap_or("unknown save error")
8089            ),
8090        )
8091        .link(Link::Task {
8092            id: task.id.clone(),
8093        });
8094        // The queue lives at `<home>/queue`, so its parent is the home.
8095        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
8096            Some(home) => notices::raise_in(home, notice),
8097            None => notices::raise(notice),
8098        }
8099    }
8100}
8101
8102/// Every runnable task, in the order the loop should try them.
8103///
8104/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
8105/// tail exists so that a claim somebody else holds costs the loop the next
8106/// candidate rather than a whole poll interval of idleness.
8107fn runnable(queue: &Queue) -> Vec<Task> {
8108    let mut tasks: Vec<Task> = queue
8109        .list()
8110        .into_iter()
8111        .filter(|t| t.status.runnable())
8112        .collect();
8113    tasks.sort_unstable_by(crate::queue::dispatch_order);
8114    tasks
8115}
8116
8117/// Why a run ended where it did, in one line, for [`Task::last_error`].
8118///
8119/// A stalled run names the seats the quota took out: "out of quota" is not
8120/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
8121/// agent to replace or which plan to top up.
8122///
8123/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
8124/// purpose: unlike `label`'s other callers (an internal log line, an
8125/// already-a-bug fallback message), this string becomes `Task::last_error`
8126/// verbatim, which the phone renders in the same alarm-styled box an
8127/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
8128/// `.err` styling. A bare `verified_noop` there would read exactly like the
8129/// failure this whole feature exists to tell apart from one.
8130fn describe(state: &RunState) -> String {
8131    let p = phrases(&state.config.graph.language);
8132    let mut detail = if state.status == RunStatus::Stalled {
8133        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
8134        seats.sort_unstable();
8135        seats.dedup();
8136        if seats.is_empty() {
8137            p.quorum_lost.to_owned()
8138        } else {
8139            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
8140        }
8141    } else {
8142        format!("{}{}", p.run_ended, state.status.display_label())
8143    };
8144    if let Some(cause) = state.verification_blocking_cause() {
8145        detail.push_str(&format!(" ({cause})"));
8146    } else if let Some(last) = state.events.last() {
8147        // The review loop's "never answered" stop is the one event worth
8148        // translating; it is recognised from structured state, not by
8149        // matching the English event text (which stays as recorded).
8150        let unanswered = state
8151            .reviews
8152            .last()
8153            .filter(|r| {
8154                state.status == RunStatus::Blocked
8155                    && last.node == "review"
8156                    && r.incomplete()
8157                    && r.blocking == 0
8158                    && r.round == state.config.graph.review_rounds
8159                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
8160            })
8161            .map(|r| (r.expected - r.answered, r.round));
8162        match unanswered {
8163            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
8164                detail.push_str(&format!(
8165                    " ({}: {})",
8166                    last.node,
8167                    (p.reviewers_never_answered)(missing, rounds)
8168                ));
8169            }
8170            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
8171        }
8172    }
8173    detail.push_str(&format!(" [run {}]", state.id));
8174    detail
8175}
8176
8177/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
8178///
8179/// The task file lives in the backlog indefinitely; a diagnostic is an
8180/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
8181/// stay small regardless of how much a gate command or a candidate printed.
8182const DIAGNOSTIC_MAX: usize = 4_000;
8183
8184/// Tail kept from a single failing command's output inside a diagnostic.
8185/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
8186/// pointer for a human deciding whether to go read the full artifact by hand,
8187/// not a replacement for reading it.
8188const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
8189
8190/// Assemble a bounded diagnostic excerpt from a held task's own run, so
8191/// `magi task show` says more than the one-line reason in [`describe`].
8192///
8193/// The one-liner answers "where did the run stop"; this answers "what would a
8194/// human have found opening `artifacts/` by hand" — the point of the whole
8195/// feature is the case that one-liner actively misleads on: a run held as "no
8196/// candidate produced a change" can mean the implementer actually finished
8197/// the task (opened a PR, merged it, tagged a release) and only left a clean
8198/// local worktree behind, which reads as "nothing happened" unless someone
8199/// goes and reads what the agent actually said. `None` when the run carries
8200/// none of the three shapes this recognises — an ordinary run held for
8201/// something not diagnosable from `RunState` alone still explains itself
8202/// through `Task::last_error`.
8203pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
8204    diagnostic(state)
8205}
8206
8207fn diagnostic(state: &RunState) -> Option<String> {
8208    let mut parts: Vec<String> = Vec::new();
8209
8210    if let Some(e2e) = &state.head_e2e
8211        && !e2e.passed
8212    {
8213        for o in e2e
8214            .outcomes
8215            .iter()
8216            .filter(|o| !o.ok() && !o.resource_blocked)
8217        {
8218            parts.push(format!(
8219                "head_e2e `{}` failed on {} ({}):\n{}",
8220                o.command,
8221                e2e.head.chars().take(7).collect::<String>(),
8222                notices::exit_status(o.code),
8223                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8224            ));
8225        }
8226    }
8227
8228    // Gate failure: which check(s), and the tail of what each printed.
8229    for o in state.gate.iter().filter(|o| !o.ok()) {
8230        parts.push(format!(
8231            "gate `{}` failed ({}):\n{}",
8232            o.command,
8233            notices::exit_status(o.code),
8234            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
8235        ));
8236    }
8237
8238    // The land loop gave up because the fixer declined while checks were
8239    // still red: the message already names them (see `land::run`).
8240    if let Some(last) = state
8241        .events
8242        .iter()
8243        .rev()
8244        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
8245    {
8246        parts.push(last.message.clone());
8247    }
8248
8249    // No viable candidate: every implementer's own final word, sanitized the
8250    // same way a judge would have read it, so a run that actually finished
8251    // the job does not read as an unexplained failure. A verified no-op is
8252    // called out ahead of its own summary and apart from an ordinary
8253    // failure's `why` — this is the one candidate shape whose diagnostic a
8254    // human is expected to actually judge, not just skim.
8255    if state.viable().is_empty() {
8256        for c in &state.candidates {
8257            if c.has_valid_verified_noop()
8258                && let Some(evidence) = c.verified_noop_display()
8259            {
8260                parts.push(format!(
8261                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
8262                    c.label
8263                ));
8264            } else if !c.summary.trim().is_empty() {
8265                if let Some(why) = &c.failed {
8266                    parts.push(format!(
8267                        "candidate {} ({why}): {}",
8268                        c.label,
8269                        c.summary.trim()
8270                    ));
8271                } else {
8272                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
8273                }
8274            } else if let Some(why) = &c.failed {
8275                parts.push(format!("candidate {}: {why}", c.label));
8276            }
8277        }
8278    }
8279
8280    if parts.is_empty() {
8281        return None;
8282    }
8283    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
8284    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
8285    // back slightly over. Leave it enough room to always land under the
8286    // limit.
8287    Some(crate::run::tail(
8288        &parts.join("\n\n"),
8289        DIAGNOSTIC_MAX.saturating_sub(100),
8290    ))
8291}
8292
8293/// Stable lower-case name for a run status, for an internal log line and the
8294/// "graph stopped without reaching a terminal status" bug message in
8295/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
8296/// doc for why that one reads [`RunStatus::display_label`] instead. One
8297/// definition of a status's name, on the type that owns it: this table used
8298/// to live here as a second copy, and a status renamed in one place would
8299/// have gone on reading correctly in the other.
8300fn label(status: RunStatus) -> &'static str {
8301    status.as_str()
8302}
8303
8304/// Parse a merge mode override.
8305pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
8306    match mode {
8307        "none" => Ok(MergeMode::None),
8308        "local" => Ok(MergeMode::Local),
8309        "pr" => Ok(MergeMode::Pr),
8310        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
8311    }
8312}
8313
8314/// Take the status lock, recovering from a poisoned one.
8315///
8316/// A panic elsewhere must not silently stop the heartbeat: the status is plain
8317/// data, and the worst a poisoned lock can hold is a stale timestamp.
8318fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
8319    mutex
8320        .lock()
8321        .unwrap_or_else(std::sync::PoisonError::into_inner)
8322}
8323
8324#[cfg(test)]
8325mod tests {
8326    use super::*;
8327    use crate::queue::{Source, TaskStatus};
8328    use crate::run::{Candidate, CommandOutcome};
8329    use pretty_assertions::assert_eq;
8330
8331    fn task() -> Task {
8332        Task::new(
8333            "add retries".to_owned(),
8334            "add retries".to_owned(),
8335            PathBuf::from("/repo"),
8336            Source::Human,
8337        )
8338    }
8339
8340    #[test]
8341    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
8342        let skips = DispatchSkips::from([
8343            ("a".into(), SkipReason::CoolingDown),
8344            ("b".into(), SkipReason::WaitingOnLanding),
8345            ("c".into(), SkipReason::WaitingOnLanding),
8346            ("d".into(), SkipReason::OrdinaryCapacity),
8347        ]);
8348        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
8349        assert_eq!(wait.runnable, 4);
8350        assert_eq!(
8351            wait.reasons
8352                .iter()
8353                .map(|r| (r.reason.as_str(), r.count))
8354                .collect::<Vec<_>>(),
8355            [
8356                ("waiting_on_landing", 2),
8357                ("cooling_down", 1),
8358                ("ordinary_capacity", 1)
8359            ]
8360        );
8361        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
8362        assert!(
8363            aggregate_dispatch_wait(2, &DispatchSkips::new())
8364                .unwrap()
8365                .reasons
8366                .is_empty()
8367        );
8368    }
8369
8370    #[test]
8371    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
8372        let before = vec!["a".into(), "b".into(), "c".into()];
8373        let allowed = vec![task_with_id("b")];
8374        let skips = interrupt_skips(&before, &allowed);
8375        assert_eq!(
8376            skips,
8377            DispatchSkips::from([
8378                ("a".into(), SkipReason::InterruptGate),
8379                ("c".into(), SkipReason::InterruptGate),
8380            ])
8381        );
8382        let mut previous = DispatchSkips::new();
8383        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8384        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
8385        assert!(!changed_dispatch_skips(&mut previous, skips));
8386        assert!(changed_dispatch_skips(
8387            &mut previous,
8388            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
8389        ));
8390        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
8391    }
8392
8393    #[test]
8394    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
8395        let mut value = serde_json::to_value(Status::new()).unwrap();
8396        value.as_object_mut().unwrap().remove("dispatch_wait");
8397        assert!(
8398            serde_json::from_value::<Status>(value.clone())
8399                .unwrap()
8400                .dispatch_wait
8401                .is_none()
8402        );
8403        assert!(
8404            serde_json::from_value::<Reading>(value.clone())
8405                .unwrap()
8406                .dispatch_wait
8407                .is_none()
8408        );
8409        value["dispatch_wait"] = serde_json::json!({
8410            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
8411        });
8412        let reading = serde_json::from_value::<Reading>(value).unwrap();
8413        assert_eq!(
8414            reading.dispatch_wait.unwrap().reasons[0].reason,
8415            "future_reason"
8416        );
8417    }
8418
8419    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
8420        let job = crate::worker::Job {
8421            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
8422            sequence: 1,
8423            kind: "task".into(),
8424            key: format!("task:{}", request.task),
8425            payload: serde_json::to_value(request).unwrap(),
8426            generation: "a".repeat(64),
8427            version: None,
8428            status: crate::worker::Status::Starting,
8429            result: None,
8430            pid: None,
8431            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
8432            finished_at: None,
8433        };
8434        let dir = home.join("workers/jobs").join(&job.id);
8435        std::fs::create_dir_all(&dir).unwrap();
8436        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
8437        job
8438    }
8439
8440    #[test]
8441    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
8442        let home = tempfile::tempdir().unwrap();
8443        let request = TaskWorker {
8444            opts: Opts::default(),
8445            queue: home.path().join("queue"),
8446            task: "startup".into(),
8447            lane: PermitKind::Ordinary,
8448            standalone: false,
8449        };
8450        let job = starting_task_reservation(home.path(), &request);
8451        let error = task_worker_spawn_error(
8452            home.path(),
8453            &request,
8454            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
8455        )
8456        .expect_err("our own reservation must not turn a failed spawn into a resync");
8457        let active = crate::worker::active(home.path()).unwrap();
8458        assert_eq!(active.len(), 1);
8459        assert_eq!(active[0].id, job.id);
8460        assert_eq!(active[0].status, crate::worker::Status::Starting);
8461        assert!(
8462            crate::worker::control(home.path(), &job.key)
8463                .unwrap()
8464                .is_none()
8465        );
8466        let notices = notices::Notices::at(home.path().join("notifications")).list();
8467        assert_eq!(notices.len(), 1);
8468        assert_eq!(notices[0].key, "loop:worker-startup");
8469        assert!(!notices[0].message.contains("private-error-detail"));
8470        assert!(notices[0].message.contains(&request.task));
8471        assert!(
8472            notices[0]
8473                .message
8474                .contains("could not be started or acknowledged")
8475        );
8476        assert!(notices[0].message.contains("worker.log"));
8477        assert_eq!(
8478            notices[0].link,
8479            Some(Link::Task {
8480                id: request.task.clone()
8481            })
8482        );
8483        assert!(format!("{error:#}").contains("private-error-detail"));
8484    }
8485
8486    #[test]
8487    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
8488        let home = tempfile::tempdir().unwrap();
8489        let mut request = TaskWorker {
8490            opts: Opts::default(),
8491            queue: home.path().join("queue"),
8492            task: "handoff".into(),
8493            lane: PermitKind::Ordinary,
8494            standalone: true,
8495        };
8496        let job = starting_task_reservation(home.path(), &request);
8497        request.standalone = false;
8498        task_worker_spawn_error(
8499            home.path(),
8500            &request,
8501            anyhow::anyhow!("operation key is already reserved for a different request"),
8502        )
8503        .expect("a different standalone request is the handoff race, not our startup failure");
8504        let active = crate::worker::active(home.path()).unwrap();
8505        assert_eq!(active.len(), 1);
8506        assert_eq!(active[0].id, job.id);
8507        assert_eq!(active[0].payload, job.payload);
8508        assert!(
8509            notices::Notices::at(home.path().join("notifications"))
8510                .list()
8511                .is_empty()
8512        );
8513    }
8514
8515    #[test]
8516    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
8517        let home = tempfile::tempdir().unwrap();
8518        let queue = Queue::at(home.path().join("queue"));
8519        let mut task = task();
8520        task.runs = vec!["previous".into()];
8521        queue.put(&mut task).unwrap();
8522        let request = TaskWorker {
8523            opts: Opts::default(),
8524            queue: home.path().join("queue"),
8525            task: task.id.clone(),
8526            lane: PermitKind::Ordinary,
8527            standalone: false,
8528        };
8529        let job = starting_task_reservation(home.path(), &request);
8530        let claims = current_work(home.path(), Timestamp::now());
8531        assert_eq!(claims.len(), 1);
8532        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
8533        assert_eq!(claims[0].run, "previous");
8534        assert!(other_claims_run(&claims, "previous", None));
8535        // Only after confirming the executing caller may admission ignore
8536        // this exact projection. Cleanup continues to observe it as live.
8537        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
8538        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
8539    }
8540
8541    #[test]
8542    fn admission_excludes_only_the_callers_exact_reservation() {
8543        let own = Current {
8544            worker: Some("own".into()),
8545            task: "same-task".into(),
8546            run: "previous".into(),
8547        };
8548        assert!(!other_claims_run(
8549            std::slice::from_ref(&own),
8550            "previous",
8551            Some("own")
8552        ));
8553        assert!(other_claims_run(
8554            std::slice::from_ref(&own),
8555            "previous",
8556            None
8557        ));
8558        for worker in [None, Some("other".into())] {
8559            let other = Current {
8560                worker,
8561                ..own.clone()
8562            };
8563            assert!(other_claims_run(
8564                &[own.clone(), other],
8565                "previous",
8566                Some("own")
8567            ));
8568        }
8569        let legacy: Current =
8570            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
8571        assert!(other_claims_run(&[legacy], "previous", Some("own")));
8572    }
8573
8574    #[test]
8575    fn os_leased_task_worker_survives_wall_clock_advance() {
8576        let home = tempfile::tempdir().unwrap();
8577        let queue = Queue::at(home.path().join("queue"));
8578        let mut task = task();
8579        let run = "20260903-100000-abcd";
8580        task.start(run.into());
8581        queue.put(&mut task).unwrap();
8582        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
8583        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
8584        assert!(
8585            current_work(home.path(), future)
8586                .iter()
8587                .any(
8588                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
8589                        && claim.run == run
8590                )
8591        );
8592        worker.release_lease();
8593        assert!(worker.dir.join("job.json").is_file());
8594        assert!(!is_working_on(home.path(), run, future));
8595        let dir = worker.dir.clone();
8596        drop(worker);
8597        assert!(!dir.exists());
8598    }
8599
8600    #[test]
8601    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
8602        let mut task = task();
8603        let mut run = run_state(RunStatus::Reviewing);
8604        run.task_instruction = Some(task.instruction.clone());
8605        run.reviewed_commits = Some(vec!["committed-fix".into()]);
8606        let branch = "magi/test/B";
8607        run.candidates.push(crate::run::Candidate {
8608            branch: branch.into(),
8609            ..candidate('B', "preserved work", false, None)
8610        });
8611        task.runs = vec![run.id.clone()];
8612        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
8613        assert_eq!(
8614            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8615            Starter::Resume(run.id.clone())
8616        );
8617        assert!(matches!(
8618            review_retry_starter(
8619                &task,
8620                Some(&run),
8621                Some("different"),
8622                true,
8623                unfinished.as_deref()
8624            ),
8625            Starter::Review(_)
8626        ));
8627        assert_eq!(
8628            review_retry_starter(
8629                &task,
8630                Some(&run),
8631                Some(branch),
8632                false,
8633                unfinished.as_deref()
8634            ),
8635            Starter::Start
8636        );
8637        task.instruction.push_str(" changed criteria");
8638        assert!(matches!(
8639            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
8640            Starter::Review(_)
8641        ));
8642        assert!(matches!(
8643            review_retry_starter(&task, Some(&run), Some(branch), true, None),
8644            Starter::Review(_)
8645        ));
8646    }
8647
8648    #[test]
8649    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
8650        let dir = tempfile::tempdir().unwrap();
8651        let queue = Queue::at(dir.path().join("queue"));
8652        let mut task = task();
8653        task.status = TaskStatus::Running;
8654        task.attempts = 1;
8655        queue.put(&mut task).unwrap();
8656        let live = std::collections::BTreeSet::from([task.id.clone()]);
8657        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
8658        drop(queue.claim(&task.id).unwrap());
8659        let saved = queue.get(&task.id).unwrap();
8660        assert_eq!(saved.status, TaskStatus::Running);
8661        assert_eq!(saved.attempts, 1);
8662        assert!(saved.last_error.is_none());
8663    }
8664
8665    #[test]
8666    fn standalone_workers_do_not_consume_scheduler_lanes() {
8667        let request = |task: &str, lane, standalone| TaskWorker {
8668            opts: Opts::default(),
8669            queue: PathBuf::from("/queue"),
8670            task: task.to_owned(),
8671            lane,
8672            standalone,
8673        };
8674        let mut jobs = vec![
8675            request("ordinary", PermitKind::Ordinary, false),
8676            request("standalone-urgent", PermitKind::Urgent, true),
8677            request("standalone-ordinary", PermitKind::Ordinary, true),
8678            request("decision", PermitKind::None, false),
8679        ];
8680        assert_eq!(available_slots(&jobs, 2), (1, 1));
8681        jobs.push(request("urgent", PermitKind::Urgent, false));
8682        assert_eq!(available_slots(&jobs, 2), (1, 0));
8683        assert_eq!(available_slots(&jobs, 0), (0, 0));
8684    }
8685
8686    #[test]
8687    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
8688        let now = Timestamp::now();
8689        let mut reading = Reading {
8690            pid: Some(std::process::id()),
8691            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
8692            ..Reading::default()
8693        };
8694        assert!(!reading.running(now));
8695        assert!(legacy_scheduler_running(&reading, now, 0));
8696        reading.worker_protocol = Some(1);
8697        assert!(!legacy_scheduler_running(&reading, now, 0));
8698    }
8699
8700    #[test]
8701    fn selected_public_head_overrides_historical_resume_and_pin() {
8702        let mut t = task();
8703        let mut old = run_state(RunStatus::Blocked);
8704        let selection = crate::pr_recovery::Selection {
8705            url: "url".into(),
8706            branch: format!("magi/task-{}", t.id),
8707            head: "a".repeat(40),
8708            source_head: None,
8709            source_run: None,
8710            source_proof: None,
8711            disposition: Some(crate::pr_recovery::Disposition::Review),
8712            instruction: t.instruction.clone(),
8713            approved_at: Timestamp::now(),
8714        };
8715        t.resume_override = Some(crate::queue::OperatorResume {
8716            pinned_run: Some(old.id.clone()),
8717            question_id: "choice".into(),
8718            at: Timestamp::now(),
8719            conductor_rehold: None,
8720            forced: false,
8721        });
8722        assert_eq!(
8723            selected_starter(&selection, Some(&old), Some(&old.id)),
8724            Starter::Review(selection.branch.clone())
8725        );
8726        old.pr_recovery = Some(selection.clone());
8727        assert_eq!(
8728            selected_starter(&selection, Some(&old), Some(&old.id)),
8729            Starter::Review(selection.branch.clone())
8730        );
8731        old.reviewed_commits = Some(vec!["implementation".into()]);
8732        assert_eq!(
8733            selected_starter(&selection, Some(&old), Some(&old.id)),
8734            Starter::Resume(old.id.clone())
8735        );
8736        let mut changed = selection.clone();
8737        changed.head = "b".repeat(40);
8738        assert_eq!(
8739            selected_starter(&changed, Some(&old), Some(&old.id)),
8740            Starter::Review(changed.branch)
8741        );
8742    }
8743
8744    #[test]
8745    fn candidate_transplant_failure_is_one_actionable_hold() {
8746        let dir = tempfile::tempdir().unwrap();
8747        let q = Queue::at(dir.path().join("queue"));
8748        let mut t = task();
8749        let mut state = run_state(RunStatus::Blocked);
8750        state.event("prep", "cannot apply referenced commit: conflict");
8751        state.prep_failure = Some("conflict".into());
8752        t.start(state.id.clone());
8753        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
8754        assert_eq!(t.attempts, 1);
8755        assert_eq!(t.status, TaskStatus::Held);
8756        assert!(t.operator_held());
8757        assert!(!t.status.runnable());
8758        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
8759        let first = t.chat_notice_key().unwrap();
8760        t.chat_notices.push(first.clone());
8761        t.release_operator("test", None);
8762        state.id = "another-unprepared-run".into();
8763        t.start(state.id.clone());
8764        finish_attempt(
8765            3,
8766            &q,
8767            &mut t,
8768            &state,
8769            &[],
8770            Err(anyhow::anyhow!("still conflicts")),
8771        );
8772        assert_eq!(
8773            t.chat_notice_key().as_ref(),
8774            Some(&first),
8775            "no work happened"
8776        );
8777        t.release_operator("test", None);
8778        state.prep_failure = None;
8779        state.status = RunStatus::Failed;
8780        state.begin_pass();
8781        t.start(state.id.clone());
8782        finish_attempt(
8783            1,
8784            &q,
8785            &mut t,
8786            &state,
8787            &[],
8788            Err(anyhow::anyhow!("new gate failure")),
8789        );
8790        let failure = t.chat_notice_key().unwrap();
8791        assert_ne!(failure, first, "approved recovery reached a real failure");
8792        t.release_operator("test", None);
8793        state.begin_pass();
8794        t.start(state.id.clone());
8795        finish_attempt(
8796            1,
8797            &q,
8798            &mut t,
8799            &state,
8800            &[],
8801            Err(anyhow::anyhow!("new failure on resume")),
8802        );
8803        assert_ne!(
8804            t.chat_notice_key().as_ref(),
8805            Some(&failure),
8806            "a new settled pass"
8807        );
8808    }
8809
8810    #[test]
8811    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
8812        for source in ["cli", "web"] {
8813            let mut t = task();
8814            let mut run = run_state(RunStatus::Blocked);
8815            run.instruction = "Run A original criteria".into();
8816            run.task_instruction = Some(run.instruction.clone());
8817            t.start(run.id.clone());
8818            t.release_operator("choice", Some("resume-question"));
8819            t.resume_override = Some(crate::queue::OperatorResume {
8820                question_id: "resume-question".into(),
8821                at: Timestamp::now(),
8822                conductor_rehold: None,
8823                forced: true,
8824                pinned_run: Some(run.id.clone()),
8825            });
8826            t.hold_machine(Some("not enough free space to start a run".into()));
8827            let mut unchanged = t.clone();
8828            unchanged
8829                .edit("title changed".into(), unchanged.instruction.clone())
8830                .unwrap();
8831            unchanged.release_operator(source, None);
8832            assert_eq!(
8833                unchanged
8834                    .resume_override
8835                    .as_ref()
8836                    .unwrap()
8837                    .pinned_run
8838                    .as_deref(),
8839                Some(run.id.as_str())
8840            );
8841            assert!(!compatible_run_instruction(&run, &unchanged));
8842            assert!(may_resume_run(&run, &unchanged));
8843
8844            t.edit(
8845                "approved recovery".into(),
8846                "Reuse measured PR head B; fix Clippy; review".into(),
8847            )
8848            .unwrap();
8849            assert!(t.resume_override.is_none());
8850            t.release_operator(source, None);
8851            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
8852            assert!(reloaded.resume_override.is_none());
8853            assert!(!may_resume_run(&run, &reloaded));
8854            let unfinished =
8855                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
8856                    .filter(|_| may_resume_run(&run, &reloaded));
8857            assert_eq!(
8858                choose_starter(None, false, unfinished.as_deref()),
8859                Starter::Start
8860            );
8861            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
8862            assert_eq!(
8863                reloaded.resumption_history[0].question_id.as_deref(),
8864                Some("resume-question")
8865            );
8866
8867            // A revision already persisted with the old approval/pin is also
8868            // invalidated when the new operator release is recorded.
8869            unchanged.instruction = "Reuse measured PR head B".into();
8870            unchanged.hold_machine(Some("disk hold".into()));
8871            unchanged.release_operator(source, None);
8872            assert!(unchanged.resume_override.is_none());
8873            assert!(!may_resume_run(&run, &unchanged));
8874        }
8875    }
8876
8877    #[test]
8878    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
8879        let mut t = task();
8880        let mut run = run_state(RunStatus::Blocked);
8881        t.review_of = Some("approved-head".into());
8882        t.instruction =
8883            "Review the branch `approved-head` (review-only: no implementation, no judging)."
8884                .into();
8885        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();
8886        run.reviewed_commits = Some(vec!["Commit log".into()]);
8887        t.start(run.id.clone());
8888        t.hold_machine(Some("interrupted review".into()));
8889        t.release_operator("cli", None);
8890        assert!(
8891            compatible_run_instruction(&run, &t),
8892            "legacy explicit review remains resumable"
8893        );
8894        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
8895            .filter(|_| compatible_run_instruction(&run, &t));
8896        assert_eq!(
8897            choose_starter(None, false, unfinished.as_deref()),
8898            Starter::Resume(run.id.clone())
8899        );
8900        run.task_instruction = Some(t.instruction.clone());
8901        assert!(compatible_run_instruction(&run, &t));
8902        let reloaded: RunState =
8903            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
8904        assert!(compatible_run_instruction(&reloaded, &t));
8905        t.edit(
8906            "new approved head".into(),
8907            "Reuse measured PR head B".into(),
8908        )
8909        .unwrap();
8910        assert!(!compatible_run_instruction(&run, &t));
8911
8912        // Legacy recovery reviews retain the task criteria ahead of the log.
8913        t.review_of = None;
8914        t.instruction = "Fix Clippy on approved head".into();
8915        run.task_instruction = None;
8916        run.task_instruction_rev = Some(t.instruction_rev);
8917        run.instruction = format!(
8918            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
8919            t.instruction
8920        );
8921        assert!(compatible_run_instruction(&run, &t));
8922        t.instruction.push('\n');
8923        assert!(
8924            compatible_run_instruction(&run, &t),
8925            "legacy generated review trimmed the original criteria"
8926        );
8927        t.hold_for_handover(Some("approved-head".into()), "refused".into());
8928        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
8929        t.edit("new plan".into(), "Reuse measured PR head B".into())
8930            .unwrap();
8931        assert!(review_branch_for(&t, Some(&run)).is_none());
8932        assert!(!compatible_run_instruction(&run, &t));
8933        t.review_branch = Some("approved-head".into());
8934        t.review_instruction = None;
8935        assert!(
8936            review_branch_for(&t, Some(&run)).is_none(),
8937            "legacy retained candidate cannot replace a revised approved head"
8938        );
8939    }
8940
8941    #[test]
8942    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
8943        let home = crate::run::test_home();
8944        crate::run::pin_test_home();
8945        let dir = tempfile::tempdir().unwrap();
8946        let queue = Queue::at(dir.path().join("queue"));
8947        for resume in [true, false] {
8948            let state = run_state(RunStatus::Blocked);
8949            let mut t = task();
8950            t.start(state.id.clone());
8951            let action = if resume {
8952                ask::ChoiceAction::Resume {
8953                    run: state.id.clone(),
8954                }
8955            } else {
8956                ask::ChoiceAction::Requeue
8957            };
8958            let mut q = action_question(&state.id, action);
8959            q.status = ask::QuestionStatus::Open;
8960            q.answer = None;
8961            q.answered_at = None;
8962            t.fail("run stopped with a question", 3);
8963            hold_if_runnable(&queue, &mut t);
8964            assert!(t.operator_decided_at.is_none());
8965            assert!(t.operator_held());
8966            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
8967            let expected = if resume {
8968                ActionDecision::Resume(state.id.clone())
8969            } else {
8970                ActionDecision::Requeue
8971            };
8972            assert_eq!(
8973                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8974                expected
8975            );
8976            t.hold_manual(Some("later explicit hold".into()));
8977            assert_eq!(
8978                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
8979                ActionDecision::Stale
8980            );
8981        }
8982    }
8983
8984    #[test]
8985    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
8986        let mut t = task();
8987        t.answers.push(crate::queue::AnsweredQuestion {
8988            question: "Inspect the remote?".into(),
8989            answer: "Inspect then wait".into(),
8990        });
8991        let old = instruction_for(&t);
8992        assert!(compatible_instruction(&old, &t));
8993        t.instruction = "Reuse approved PR head and review".into();
8994        t.release_operator("cli", None);
8995        assert!(!compatible_instruction(&old, &t));
8996        let approved = instruction_for(&t);
8997        assert!(approved.contains("waiting premises are superseded"));
8998        assert!(compatible_instruction(&approved, &t));
8999        assert_eq!(resumed_instruction(&approved, &t), approved);
9000        t.release_operator("web", None);
9001        assert!(compatible_instruction(&approved, &t));
9002        assert_eq!(t.resumption_history.len(), 1);
9003        t.start("run".into());
9004        assert!(instruction_for(&t).contains("Explicit operator resumption"));
9005    }
9006
9007    /// A run that stopped on an infrastructure wait asked no agent anything:
9008    /// the task is held by the machine under a `[resource]` reason (resumable,
9009    /// re-checked by triage), and the attempt it started is given back.
9010    #[test]
9011    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
9012        let mut state = RunState::new(
9013            PathBuf::from("/repo"),
9014            "main".into(),
9015            "base".into(),
9016            "task".into(),
9017            Config::default(),
9018        );
9019        state.status = RunStatus::Landing;
9020        state.parked = true;
9021        state.pr_pushed_head = Some("head".into());
9022        state.land_unrelated = Some(
9023            serde_json::from_value(serde_json::json!({
9024                "head": "head", "question": "ci-question",
9025                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
9026            }))
9027            .unwrap(),
9028        );
9029        let mut t = task();
9030        t.start(state.id.clone());
9031        let verdict = Verdict {
9032            status: RunStatus::Landing,
9033            left_pr: true,
9034            quota_hit: false,
9035            parked: true,
9036            no_viable_candidates: false,
9037        };
9038        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
9039        assert_eq!(t.attempts, 0);
9040        assert_eq!(t.status, TaskStatus::Held);
9041        assert!(!t.operator_held());
9042        assert!(
9043            t.hold_reason
9044                .as_deref()
9045                .unwrap()
9046                .starts_with("[ci-unrelated]")
9047        );
9048        // A second settlement must not refund an earlier task attempt.
9049        t.attempts = 1;
9050        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
9051        assert_eq!(t.attempts, 1);
9052        assert_eq!(t.passes.len(), 1);
9053        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
9054        state.pr_pushed_head = Some("new-head".into());
9055        state.parked = false;
9056        state.status = RunStatus::Blocked;
9057        let stale = Verdict {
9058            status: RunStatus::Blocked,
9059            parked: false,
9060            ..verdict
9061        };
9062        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
9063        assert_eq!(t.attempts, 1);
9064        // A new execution pass can refund its own newly charged attempt.
9065        state.begin_pass();
9066        state.begin_pass();
9067        state.status = RunStatus::Landing;
9068        state.parked = true;
9069        state.pr_pushed_head = Some("head".into());
9070        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
9071        assert_eq!(t.attempts, 0);
9072        assert_eq!(t.passes.len(), 2);
9073    }
9074
9075    #[test]
9076    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
9077        let mut state = run_state(RunStatus::Failed);
9078        state
9079            .quota
9080            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
9081        state.begin_pass();
9082        let mut t = task();
9083        t.start(state.id.clone());
9084        reclaim(&mut t, Some(state), 2, "en");
9085        assert_eq!(t.attempts, 1);
9086    }
9087
9088    #[test]
9089    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
9090        let mut state = run_state(RunStatus::Blocked);
9091        let losses: Vec<_> = ["alpha", "beta"]
9092            .into_iter()
9093            .enumerate()
9094            .map(|(i, agent)| {
9095                QuotaLoss::from_report(
9096                    format!("advisor-{i}"),
9097                    "advise",
9098                    Some(&crate::agent::Quota {
9099                        cause: crate::agent::QuotaCause::Authentication,
9100                        agent: agent.to_owned(),
9101                        reset: None,
9102                    }),
9103                )
9104            })
9105            .collect();
9106        crate::graph::block_machine_outage(&mut state, "advise", &losses);
9107        state.quota = losses;
9108        let mut t = task();
9109        t.start(state.id.clone());
9110        let verdict = Verdict {
9111            status: state.status,
9112            left_pr: false,
9113            quota_hit: true,
9114            parked: false,
9115            no_viable_candidates: true,
9116        };
9117        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
9118        assert_eq!(t.attempts, 0);
9119        assert_eq!(t.status, TaskStatus::Held);
9120        assert!(!t.operator_held());
9121        let reason = t.hold_reason.as_deref().unwrap();
9122        assert!(reason.starts_with("[authentication]"));
9123        assert!(
9124            reason.contains("alpha")
9125                && reason.contains("beta")
9126                && reason.contains("re-authenticate")
9127        );
9128        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
9129        // Orphan recovery uses the same settlement and cannot spend an attempt.
9130        let mut orphan = task();
9131        orphan.start(state.id.clone());
9132        reclaim(&mut orphan, Some(state), 2, "en");
9133        assert_eq!(orphan.attempts, 0);
9134        assert_eq!(orphan.status, TaskStatus::Held);
9135    }
9136
9137    #[test]
9138    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
9139        let mut state = RunState::new(
9140            PathBuf::from("/repo"),
9141            "main".to_owned(),
9142            "abc1234".to_owned(),
9143            "task".to_owned(),
9144            Config::default(),
9145        );
9146        state.status = RunStatus::Blocked;
9147        state.resource_block = Some(crate::run::ResourceBlock {
9148            cause: crate::run::ResourceBlockCause::Other,
9149            node: "graft".to_owned(),
9150            kind: "shared build cache".to_owned(),
9151            detail: "timed out".to_owned(),
9152            at: jiff::Timestamp::now(),
9153        });
9154        let mut t = task();
9155        t.start("20260902-000000-aaaa".to_owned());
9156        assert_eq!(t.attempts, 1);
9157        let verdict = Verdict {
9158            status: RunStatus::Blocked,
9159            left_pr: false,
9160            quota_hit: false,
9161            parked: false,
9162            no_viable_candidates: false,
9163        };
9164        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
9165        assert_eq!(t.status, TaskStatus::Held);
9166        assert_eq!(t.attempts, 0, "the attempt is refunded");
9167        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
9168        assert!(
9169            !t.operator_held(),
9170            "a machine hold, released without a human"
9171        );
9172
9173        let mut selected = task();
9174        selected.start("20260902-000000-cccc".into());
9175        selected.replacement = Some(crate::merge_decision::Replacement {
9176            question: "fixture".into(),
9177            run: "earlier".into(),
9178            pr: "https://example.invalid/pr/1".into(),
9179            agent: "selected".into(),
9180            context: "fixture".into(),
9181        });
9182        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
9183        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
9184        assert_eq!(selected.attempts, 0);
9185        assert!(
9186            !selected.operator_held(),
9187            "a selected agent also retains a machine resource hold"
9188        );
9189        assert!(
9190            selected
9191                .hold_reason
9192                .as_deref()
9193                .unwrap()
9194                .starts_with("[resource] ")
9195        );
9196
9197        // A park request outranks it: still the operator's doing.
9198        let mut p = task();
9199        p.start("20260902-000000-bbbb".to_owned());
9200        settle_and_diagnose(
9201            &mut p,
9202            Verdict {
9203                parked: true,
9204                ..verdict
9205            },
9206            "parked",
9207            2,
9208            &state,
9209        );
9210        assert_eq!(p.status, TaskStatus::Parked);
9211        assert_eq!(
9212            p.attempts, 0,
9213            "parking refunds once rather than also settling the resource hold"
9214        );
9215    }
9216
9217    #[test]
9218    fn record_failure_notice_links_the_task() {
9219        let dir = tempfile::tempdir().unwrap();
9220        // A regular file where the queue directory should be makes every
9221        // `put` fail, on every platform and whoever runs the test.
9222        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
9223        let queue = Queue::at(dir.path().join("queue"));
9224        let mut t = interrupt_task("rec-fail-1");
9225        record(&queue, &mut t);
9226
9227        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
9228        assert_eq!(found.len(), 1);
9229        assert_eq!(found[0].key, "loop:record");
9230        assert_eq!(
9231            found[0].link,
9232            Some(Link::Task {
9233                id: "rec-fail-1".to_owned()
9234            })
9235        );
9236    }
9237
9238    /// A runnable task marked to interrupt, with an id fixed for assertions
9239    /// rather than the random one [`Task::new`] mints.
9240    fn interrupt_task(id: &str) -> Task {
9241        let mut t = task();
9242        t.id = id.to_owned();
9243        t.interrupt = true;
9244        t
9245    }
9246
9247    /// An ordinary runnable task with an id fixed for assertions.
9248    fn task_with_id(id: &str) -> Task {
9249        let mut t = task();
9250        t.id = id.to_owned();
9251        t
9252    }
9253
9254    /// A runnable task marked `--urgent`, with an id fixed for assertions.
9255    fn urgent_task(id: &str) -> Task {
9256        let mut t = task();
9257        t.id = id.to_owned();
9258        t.urgent = true;
9259        t
9260    }
9261
9262    #[test]
9263    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
9264        let dir = tempfile::tempdir().unwrap();
9265        let queue = Queue::at(dir.path().join("queue"));
9266        let mut parked = task_with_id("parked");
9267        parked.start("run".into());
9268        parked.park("upgrade");
9269        parked.record_pass_at(
9270            "run",
9271            0,
9272            Some(Timestamp::now()),
9273            1,
9274            Some(crate::run::ParkCause::Upgrade {
9275                from: "old".into(),
9276                to: None,
9277            }),
9278        );
9279        let mut fresh = task_with_id("fresh");
9280        fresh.priority = 100;
9281        let mut urgent_task = urgent_task("urgent");
9282        for t in [&mut parked, &mut fresh, &mut urgent_task] {
9283            queue.put(t).unwrap();
9284        }
9285        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9286        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9287        let candidates = runnable(&queue);
9288        assert_eq!(candidates[0].id, parked.id);
9289        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
9290        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
9291        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
9292        drop(first);
9293        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
9294        let next = runnable(&queue)
9295            .into_iter()
9296            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
9297            .unwrap();
9298        assert_eq!(next.task.id, fresh.id);
9299        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
9300        drop(claimed_elsewhere);
9301        drop(next);
9302        assert!(matches!(
9303            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
9304            Err(SkipReason::CoolingDown)
9305        ));
9306    }
9307
9308    #[test]
9309    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
9310        let dir = tempfile::tempdir().unwrap();
9311        let queue = Queue::at(dir.path().join("queue"));
9312        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9313        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9314        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9315        let mut first = task();
9316        queue.put(&mut first).unwrap();
9317        let stale_plain = queue.get(&first.id).unwrap();
9318        first.set_urgent(true).unwrap();
9319        queue.put(&mut first).unwrap();
9320        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
9321        let mut second = urgent_task("second");
9322        queue.put(&mut second).unwrap();
9323        assert!(matches!(
9324            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
9325            Err(SkipReason::UrgentCapacity)
9326        ));
9327        drop(queue.claim(&second.id).unwrap());
9328        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
9329        drop(dispatched);
9330        let stale_urgent = queue.get(&first.id).unwrap();
9331        first.set_urgent(false).unwrap();
9332        queue.put(&mut first).unwrap();
9333        assert!(matches!(
9334            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
9335            Err(SkipReason::OrdinaryCapacity)
9336        ));
9337        assert_eq!(urgent.available_permits(), 1);
9338        drop(queue.claim(&first.id).unwrap());
9339        drop(occupied);
9340    }
9341
9342    #[test]
9343    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
9344        let dir = tempfile::tempdir().unwrap();
9345        let queue = Queue::at(dir.path().join("queue"));
9346        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9347        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9348        let mut t = task();
9349        queue.put(&mut t).unwrap();
9350        for enabled in [true, false] {
9351            let stale = queue.get(&t.id).unwrap();
9352            t.set_urgent(enabled).unwrap();
9353            queue.put(&mut t).unwrap();
9354            assert_ne!(stale.urgent, enabled);
9355            let DispatchClaim {
9356                task: fresh,
9357                claim,
9358                lane,
9359                permit,
9360            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9361            assert_eq!(fresh.urgent, enabled);
9362            assert_eq!(
9363                lane,
9364                if enabled {
9365                    PermitKind::Urgent
9366                } else {
9367                    PermitKind::Ordinary
9368                }
9369            );
9370            assert_eq!(ordinary.available_permits(), usize::from(enabled));
9371            assert_eq!(urgent.available_permits(), usize::from(!enabled));
9372            assert!(queue.claim(&t.id).is_err());
9373            assert_eq!(fresh.attempts, stale.attempts);
9374            drop((claim, permit));
9375            assert_eq!(ordinary.available_permits(), 1);
9376            assert_eq!(urgent.available_permits(), 1);
9377        }
9378        t.set_urgent(true).unwrap();
9379        queue.put(&mut t).unwrap();
9380        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
9381        assert!(matches!(
9382            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9383            Err(SkipReason::UrgentCapacity)
9384        ));
9385        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
9386        drop(queue.claim(&t.id).unwrap());
9387        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
9388        drop(occupied);
9389        assert!(matches!(
9390            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
9391            Err(SkipReason::CoolingDown)
9392        ));
9393        drop(queue.claim(&t.id).unwrap());
9394        let held = queue.claim(&t.id).unwrap();
9395        assert!(matches!(
9396            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9397            Err(SkipReason::ClaimUnavailable)
9398        ));
9399        drop(held);
9400        t.status = TaskStatus::Held;
9401        queue.put(&mut t).unwrap();
9402        assert!(matches!(
9403            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9404            Err(SkipReason::NoLongerRunnable)
9405        ));
9406        drop(queue.claim(&t.id).unwrap());
9407        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
9408        assert!(matches!(
9409            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
9410            Err(SkipReason::RereadFailed)
9411        ));
9412        drop(queue.claim(&t.id).unwrap());
9413        assert_eq!(urgent.available_permits(), 1);
9414    }
9415
9416    /// The land-resume exemption wins outright, whether or not the candidate
9417    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
9418    /// queue behind anything" guarantee cannot be weaker just because the
9419    /// same task was also filed with `--urgent`.
9420    #[test]
9421    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
9422        assert_eq!(permit_kind(true, false, false), PermitKind::None);
9423        assert_eq!(permit_kind(true, false, true), PermitKind::None);
9424        assert_eq!(permit_kind(true, true, false), PermitKind::None);
9425        assert_eq!(permit_kind(true, true, true), PermitKind::None);
9426    }
9427
9428    /// The one property this whole feature exists for: `--urgent` draws from
9429    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
9430    /// ordinary candidate draws from the ordinary pool exactly as before,
9431    /// untouched by the urgent slot's existence.
9432    #[test]
9433    fn permit_kind_separates_urgent_from_ordinary() {
9434        assert_eq!(permit_kind(false, false, true), PermitKind::Urgent);
9435        assert_eq!(permit_kind(false, false, false), PermitKind::Ordinary);
9436        assert_eq!(permit_kind(false, true, false), PermitKind::Immediate);
9437        assert_eq!(permit_kind(false, true, true), PermitKind::Immediate);
9438    }
9439
9440    #[test]
9441    fn immediate_lane_does_not_consume_ordinary_or_urgent_slots() {
9442        let request = |task: &str, lane, standalone| TaskWorker {
9443            opts: Opts::default(),
9444            queue: PathBuf::from("/queue"),
9445            task: task.to_owned(),
9446            lane,
9447            standalone,
9448        };
9449        let jobs = vec![
9450            request("ordinary", PermitKind::Ordinary, false),
9451            request("urgent", PermitKind::Urgent, false),
9452            request("immediate-1", PermitKind::Immediate, false),
9453            request("immediate-2", PermitKind::Immediate, false),
9454            request("decision", PermitKind::None, false),
9455        ];
9456        assert_eq!(available_slots(&jobs, 1), (0, 0));
9457        assert_eq!(available_slots(&jobs, 2), (1, 0));
9458        let immediate_only = vec![
9459            request("immediate-1", PermitKind::Immediate, false),
9460            request("immediate-2", PermitKind::Immediate, false),
9461        ];
9462        assert_eq!(available_slots(&immediate_only, 1), (1, 1));
9463    }
9464
9465    #[test]
9466    fn immediate_dispatch_bypasses_saturated_lanes_and_preserves_non_concurrency_gates() {
9467        let dir = tempfile::tempdir().unwrap();
9468        let queue = Queue::at(dir.path().join("queue"));
9469        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
9470        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
9471        let _ord_permit = Arc::clone(&ordinary).try_acquire_owned().unwrap();
9472        let _urg_permit = Arc::clone(&urgent).try_acquire_owned().unwrap();
9473
9474        // Both ordinary and urgent lanes are saturated.
9475        let mut imm1 = task_with_id("imm-1");
9476        imm1.immediate = true;
9477        let mut imm2 = task_with_id("imm-2");
9478        imm2.immediate = true;
9479        imm2.urgent = true;
9480        queue.put(&mut imm1).unwrap();
9481        queue.put(&mut imm2).unwrap();
9482
9483        // Stale non-immediate listing still picks up saved immediate under claim.
9484        let mut stale = imm1.clone();
9485        stale.immediate = false;
9486        let claim1 = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
9487        assert_eq!(claim1.lane, PermitKind::Immediate);
9488        assert!(claim1.permit.is_none());
9489
9490        // Multiple immediate tasks can claim simultaneously without touching semaphores.
9491        let claim2 = claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).unwrap();
9492        assert_eq!(claim2.lane, PermitKind::Immediate);
9493        assert!(claim2.permit.is_none());
9494        assert_eq!(ordinary.available_permits(), 0);
9495        assert_eq!(urgent.available_permits(), 0);
9496
9497        // Duplicate claim on an already-claimed immediate task is refused.
9498        assert_eq!(
9499            claim_dispatch(&queue, &imm1, false, &ordinary, &urgent).err(),
9500            Some(SkipReason::ClaimUnavailable)
9501        );
9502        drop((claim1, claim2));
9503
9504        // Cooldown still blocks immediate tasks.
9505        assert_eq!(
9506            claim_dispatch(&queue, &imm1, true, &ordinary, &urgent).err(),
9507            Some(SkipReason::CoolingDown)
9508        );
9509
9510        // Clearing immediate while urgent remains true reverts to urgent lane.
9511        imm2.set_immediate(false).unwrap();
9512        queue.put(&mut imm2).unwrap();
9513        assert_eq!(
9514            claim_dispatch(&queue, &imm2, false, &ordinary, &urgent).err(),
9515            Some(SkipReason::UrgentCapacity)
9516        );
9517
9518        // Interrupt gate still withholds immediate candidates.
9519        let interrupt = Interrupt::Parking {
9520            parked: vec!["in-flight".into()],
9521            interrupt_task: "other".into(),
9522        };
9523        assert!(
9524            interrupt_gate(&interrupt, &["in-flight".into()], vec![imm1.clone()]).is_empty(),
9525            "an active interrupt sequence must withhold immediate tasks too"
9526        );
9527    }
9528
9529    #[test]
9530    fn admission_snapshot_distinguishes_mode_lane_blockers_and_unknown_state() {
9531        let dir = tempfile::tempdir().unwrap();
9532        let home = dir.path();
9533        let queue = Queue::at(home.join("queue"));
9534        let now = Timestamp::now();
9535
9536        let mut imm = task_with_id("imm-ready");
9537        imm.immediate = true;
9538        queue.put(&mut imm).unwrap();
9539
9540        // No scheduler running -> waiting, never "next poll".
9541        let snap = AdmissionSnapshot::capture(home, now);
9542        let adm = snap.evaluate(&imm, &queue, None, home);
9543        assert_eq!(adm.mode, "immediate");
9544        assert_eq!(adm.state, "waiting");
9545        assert_eq!(adm.label, "Immediate: waiting — scheduler not running");
9546
9547        // Live scheduler + saturated ordinary/urgent workers + stale capacity skip -> next poll!
9548        let mut status = Status::new();
9549        status.updated_at = now;
9550        status
9551            .dispatch_skips
9552            .insert(imm.id.clone(), SkipReason::UrgentCapacity.key().to_owned());
9553        write_status_to(&home.join("daemon.json"), &status).unwrap();
9554
9555        let mut ord = task_with_id("ord-running");
9556        ord.status = TaskStatus::Running;
9557        queue.put(&mut ord).unwrap();
9558        let ord_req = TaskWorker {
9559            opts: Opts::default(),
9560            queue: queue.root().to_path_buf(),
9561            task: ord.id.clone(),
9562            lane: PermitKind::Ordinary,
9563            standalone: false,
9564        };
9565        let (_ord_job, _ord_lease) = crate::worker::running_fixture(
9566            home,
9567            &format!("task:{}", ord.id),
9568            serde_json::to_value(&ord_req).unwrap(),
9569        )
9570        .unwrap();
9571
9572        let mut urg = task_with_id("urg-running");
9573        urg.urgent = true;
9574        urg.status = TaskStatus::Running;
9575        queue.put(&mut urg).unwrap();
9576        let urg_req = TaskWorker {
9577            opts: Opts::default(),
9578            queue: queue.root().to_path_buf(),
9579            task: urg.id.clone(),
9580            lane: PermitKind::Urgent,
9581            standalone: false,
9582        };
9583        let (_urg_job, _urg_lease) = crate::worker::running_fixture(
9584            home,
9585            &format!("task:{}", urg.id),
9586            serde_json::to_value(&urg_req).unwrap(),
9587        )
9588        .unwrap();
9589
9590        let snap = AdmissionSnapshot::capture(home, now);
9591        let adm = snap.evaluate(&imm, &queue, None, home);
9592        assert_eq!(adm.state, "next_poll");
9593        assert_eq!(adm.label, "Immediate: next poll");
9594        assert_eq!(adm.reservation_lane, None);
9595
9596        // Running worker reports its actual persisted reservation lane.
9597        let ord_adm = snap.evaluate(&ord, &queue, None, home);
9598        assert_eq!(ord_adm.state, "running");
9599        assert_eq!(ord_adm.reservation_lane, Some("ordinary"));
9600        assert_eq!(ord_adm.label, "Running (ordinary lane)");
9601
9602        // Held (manual + disk) and Blocked (dependency) report concrete blockers.
9603        let mut held = task_with_id("imm-held");
9604        held.immediate = true;
9605        held.hold_manual(Some("awaiting signoff".into()));
9606        queue.put(&mut held).unwrap();
9607        let held_adm = snap.evaluate(&held, &queue, None, home);
9608        assert_eq!(held_adm.state, "waiting");
9609        assert_eq!(
9610            held_adm.label,
9611            "Immediate: waiting — held (awaiting signoff)"
9612        );
9613
9614        let mut disk_held = task_with_id("imm-disk");
9615        disk_held.immediate = true;
9616        disk_held.hold_machine(Some("only 1 GiB free".into()));
9617        disk_held.mark_startup_disk_capacity();
9618        queue.put(&mut disk_held).unwrap();
9619        let disk_adm = snap.evaluate(&disk_held, &queue, None, home);
9620        assert_eq!(disk_adm.state, "waiting");
9621        assert!(disk_adm.label.contains("disk admission"), "{disk_adm:?}");
9622
9623        let mut blocked = task_with_id("imm-blocked");
9624        blocked.immediate = true;
9625        blocked.block(vec![held.id.clone()], Some("needs held task".into()));
9626        queue.put(&mut blocked).unwrap();
9627        let questions = Questions::at(home.join("questions"));
9628        let inv = crate::blockers::Inventory::load(&queue, &questions);
9629        let blocked_adm = snap.evaluate(&blocked, &queue, Some(&inv), home);
9630        assert_eq!(blocked_adm.state, "waiting");
9631        assert!(
9632            blocked_adm
9633                .label
9634                .starts_with("Immediate: waiting — waiting on dependencies"),
9635            "{blocked_adm:?}"
9636        );
9637
9638        // Existing claim blocks immediate.
9639        let _claim = queue.claim(&imm.id).unwrap();
9640        let claimed_adm = snap.evaluate(&imm, &queue, None, home);
9641        assert_eq!(claimed_adm.state, "waiting");
9642        assert_eq!(
9643            claimed_adm.label,
9644            "Immediate: waiting — claimed by another process"
9645        );
9646        drop(_claim);
9647
9648        // Quota cooldown blocks immediate.
9649        let until = now + jiff::SignedDuration::from_secs(120);
9650        std::fs::write(
9651            home.join("task-quota-cooldown.json"),
9652            serde_json::to_vec(&until).unwrap(),
9653        )
9654        .unwrap();
9655        let cool_snap = AdmissionSnapshot::capture(home, now);
9656        let cool_adm = cool_snap.evaluate(&imm, &queue, None, home);
9657        assert_eq!(cool_adm.state, "waiting");
9658        assert!(cool_adm.label.contains("quota cooldown"), "{cool_adm:?}");
9659        std::fs::remove_file(home.join("task-quota-cooldown.json")).unwrap();
9660
9661        // Corrupt interrupt file is reported as unknown, never "next poll".
9662        std::fs::write(home.join("scheduler-interrupt.json"), "{broken").unwrap();
9663        let bad_snap = AdmissionSnapshot::capture(home, now);
9664        let bad_adm = bad_snap.evaluate(&imm, &queue, None, home);
9665        assert_eq!(bad_adm.state, "unknown");
9666        assert_ne!(bad_adm.label, "Immediate: next poll");
9667    }
9668
9669    /// The exact wiring `attempt` runs before minting anything: a config's
9670    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
9671    /// Free space is injected rather than asked of the real disk - the point
9672    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
9673    /// is deterministic on every machine this test runs on, never dependent
9674    /// on how full the CI runner's own disk happens to be.
9675    #[test]
9676    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
9677        let cfg = Config::default();
9678        let repo = Path::new("/any/repo/path");
9679
9680        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
9681            .expect("must hold below the threshold");
9682        assert!(reason.contains("1024"), "{reason}");
9683        assert!(
9684            reason.contains(&cfg.disk.min_free_bytes.to_string()),
9685            "{reason}"
9686        );
9687
9688        assert_eq!(
9689            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
9690            None,
9691            "exactly at the floor is open"
9692        );
9693        assert_eq!(
9694            disk_gate_with(
9695                repo,
9696                &cfg,
9697                PathBuf::new,
9698                |_| Ok(cfg.disk.min_free_bytes + 1)
9699            ),
9700            None,
9701            "comfortably above the floor is open"
9702        );
9703    }
9704
9705    /// The collection threshold is not an admission floor: free space just
9706    /// above `min_free_bytes` but far below `reclaim_free_bytes` opens the gate
9707    /// with no hold, whatever the threshold is.
9708    #[test]
9709    fn disk_gate_ignores_the_collection_threshold() {
9710        let mut cfg = Config::default();
9711        cfg.disk.reclaim_free_bytes = Some(cfg.disk.min_free_bytes * 100);
9712        let repo = Path::new("/any/repo/path");
9713        assert_eq!(
9714            disk_gate_with(
9715                repo,
9716                &cfg,
9717                PathBuf::new,
9718                |_| Ok(cfg.disk.min_free_bytes + 1)
9719            ),
9720            None
9721        );
9722        assert!(
9723            disk_gate_with(
9724                repo,
9725                &cfg,
9726                PathBuf::new,
9727                |_| Ok(cfg.disk.min_free_bytes - 1)
9728            )
9729            .is_some(),
9730            "below the admission floor still holds"
9731        );
9732    }
9733
9734    #[test]
9735    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
9736        let dir = tempfile::tempdir().unwrap();
9737        let repo = dir.path().join("repo");
9738        let cache = dir.path().join("cache");
9739        let worktrees = dir.path().join("worktrees");
9740        for path in [&repo, &cache, &worktrees] {
9741            std::fs::create_dir(path).unwrap();
9742        }
9743        let mut cfg = Config::default();
9744        cfg.graph.worktree_root = Some(worktrees.clone());
9745        cfg.verify.gate = vec![format!(
9746            "CARGO_TARGET_DIR='{}' cargo build",
9747            cache.display()
9748        )];
9749        for blocked in [&cache, &worktrees] {
9750            for unmeasured in [false, true] {
9751                assert!(
9752                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
9753                        if path == blocked {
9754                            if unmeasured {
9755                                Err(anyhow::anyhow!("measurement failed"))
9756                            } else {
9757                                Ok(0)
9758                            }
9759                        } else {
9760                            Ok(u64::MAX)
9761                        }
9762                    })
9763                    .is_some(),
9764                    "a blocked secondary output volume must close admission"
9765                );
9766            }
9767        }
9768        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
9769    }
9770
9771    #[test]
9772    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
9773        let dir = tempfile::tempdir().unwrap();
9774        let repo = dir.path().join("repo");
9775        let cache = dir.path().join("cache");
9776        let home_parent = dir.path().join("run-volume");
9777        let home = home_parent.join("new-home");
9778        for path in [&repo, &cache, &home_parent] {
9779            std::fs::create_dir(path).unwrap();
9780        }
9781        let mut cfg = Config::default();
9782        cfg.graph.worktree_root = Some(repo.clone());
9783        cfg.verify.gate = vec![format!(
9784            "CARGO_TARGET_DIR='{}' cargo build",
9785            cache.display()
9786        )];
9787        cfg.verify.build_cache = BuildCache::Isolated;
9788        let denied = |blocked: &Path| {
9789            disk_gate_with(
9790                &repo,
9791                &cfg,
9792                || home.clone(),
9793                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
9794            )
9795            .is_some()
9796        };
9797        assert!(!denied(&cache));
9798        assert!(denied(&home_parent));
9799    }
9800
9801    #[test]
9802    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
9803        let mut cfg = Config::default();
9804        cfg.disk.min_free_bytes = 0;
9805        let repo = Path::new("/any/repo/path");
9806        assert_eq!(
9807            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
9808            None,
9809            "a zero floor never measures at all"
9810        );
9811    }
9812
9813    #[test]
9814    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
9815        let cfg = Config::default();
9816        let repo = Path::new("/any/repo/path");
9817        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
9818            Err(anyhow::anyhow!("no df on this box"))
9819        })
9820        .expect("a measurement failure must close the gate, not open it");
9821        assert!(reason.contains("could not measure"), "{reason}");
9822    }
9823
9824    #[test]
9825    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
9826        let ordinary = task();
9827        let next = advance_interrupt(
9828            Interrupt::Idle,
9829            std::slice::from_ref(&ordinary.id),
9830            std::slice::from_ref(&ordinary),
9831        );
9832        assert_eq!(next, Interrupt::Idle);
9833    }
9834
9835    #[test]
9836    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
9837        // Nothing to interrupt - this is just an ordinary candidate, and the
9838        // loop's normal dispatch will pick it up like any other.
9839        let marked = interrupt_task("marked");
9840        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9841        assert_eq!(next, Interrupt::Idle);
9842    }
9843
9844    #[test]
9845    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
9846        let marked = interrupt_task("marked");
9847        let next = advance_interrupt(
9848            Interrupt::Idle,
9849            &["running".to_owned()],
9850            std::slice::from_ref(&marked),
9851        );
9852        assert_eq!(
9853            next,
9854            Interrupt::Parking {
9855                parked: vec!["running".to_owned()],
9856                interrupt_task: "marked".to_owned(),
9857            }
9858        );
9859    }
9860
9861    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
9862    /// one run can be in flight when a task becomes runnable and marked.
9863    /// Parking all of them would mean `Resuming` later has more than one id
9864    /// to release back to ordinary dispatch, which cannot be made safe
9865    /// against that same setting's own extra concurrency slots letting two
9866    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
9867    /// The simplification the task's own constraints ask for: do not begin
9868    /// a sequence at all until the herd settles back to exactly one.
9869    #[test]
9870    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
9871        let marked = interrupt_task("marked");
9872
9873        let two = advance_interrupt(
9874            Interrupt::Idle,
9875            &["a".to_owned(), "b".to_owned()],
9876            std::slice::from_ref(&marked),
9877        );
9878        assert_eq!(two, Interrupt::Idle);
9879
9880        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
9881        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
9882    }
9883
9884    #[test]
9885    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
9886        let state = Interrupt::Parking {
9887            parked: vec!["running".to_owned()],
9888            interrupt_task: "marked".to_owned(),
9889        };
9890        // Still in flight: no change.
9891        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
9892        assert_eq!(still_going, state);
9893
9894        // Left flight, but the interrupt task has not been dispatched yet on
9895        // this tick - stays `Parking` so `interrupt_gate` can let it through,
9896        // as long as it is still runnable.
9897        let stopped_but_not_yet_dispatched =
9898            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
9899        assert_eq!(stopped_but_not_yet_dispatched, state);
9900
9901        // Left flight, and the interrupt task is now in flight itself.
9902        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
9903        assert_eq!(
9904            dispatched,
9905            Interrupt::Running {
9906                parked: vec!["running".to_owned()],
9907                interrupt_task: "marked".to_owned(),
9908            }
9909        );
9910    }
9911
9912    #[test]
9913    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
9914        let state = Interrupt::Running {
9915            parked: vec!["running".to_owned()],
9916            interrupt_task: "marked".to_owned(),
9917        };
9918        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
9919        assert_eq!(still_running, state);
9920
9921        // Whatever it ended as - merged, failed, held - is not this
9922        // function's concern: leaving flight is the only trigger, driven
9923        // straight off the same in-flight list `poll` already reaps. It does
9924        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
9925        // why that would let an unrelated task start ahead of, or alongside,
9926        // the guaranteed resume.
9927        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
9928        assert_eq!(
9929            ended,
9930            Interrupt::Resuming {
9931                parked: vec!["running".to_owned()]
9932            }
9933        );
9934    }
9935
9936    #[test]
9937    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
9938        let state = Interrupt::Resuming {
9939            parked: vec!["running".to_owned()],
9940        };
9941        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
9942        assert_eq!(still_waiting, state);
9943
9944        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
9945        assert_eq!(dispatched, Interrupt::Idle);
9946    }
9947
9948    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
9949    /// or otherwise moved on by an operator with no claim standing in the
9950    /// way - must not wedge the sequence (and so the whole loop's dispatch,
9951    /// via `interrupt_gate`) waiting forever for a dispatch that can never
9952    /// come. The parked run still gets its resume.
9953    #[test]
9954    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
9955    {
9956        let state = Interrupt::Parking {
9957            parked: vec!["running".to_owned()],
9958            interrupt_task: "marked".to_owned(),
9959        };
9960        // `marked` has been held/blocked/deleted since the sequence began:
9961        // it no longer appears in `runnable` at all.
9962        let next = advance_interrupt(state, &[], &[]);
9963        assert_eq!(
9964            next,
9965            Interrupt::Resuming {
9966                parked: vec!["running".to_owned()]
9967            },
9968            "abandoning the interrupt must not abandon the resume it owes"
9969        );
9970    }
9971
9972    /// The same abandonment, one step later: `Resuming` itself must not wait
9973    /// forever for a parked task that has since become unrunnable.
9974    #[test]
9975    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
9976        let state = Interrupt::Resuming {
9977            parked: vec!["running".to_owned()],
9978        };
9979        let next = advance_interrupt(state, &[], &[]);
9980        assert_eq!(
9981            next,
9982            Interrupt::Idle,
9983            "nothing is left to wait for; the loop must not stay wedged"
9984        );
9985    }
9986
9987    #[test]
9988    fn disabled_by_config_the_sequence_can_never_leave_idle() {
9989        let marked = interrupt_task("marked");
9990        let next = advance_interrupt_tick(
9991            false,
9992            Interrupt::Idle,
9993            &["running".to_owned()],
9994            std::slice::from_ref(&marked),
9995        );
9996        assert_eq!(
9997            next,
9998            Interrupt::Idle,
9999            "an unmarked, unconfigured daemon must behave exactly as before"
10000        );
10001    }
10002
10003    #[test]
10004    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
10005        let state = Interrupt::Parking {
10006            parked: vec!["running".to_owned()],
10007            interrupt_task: "marked".to_owned(),
10008        };
10009        let candidates = vec![interrupt_task("marked"), task()];
10010        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
10011        assert!(
10012            allowed.is_empty(),
10013            "nothing may dispatch - not even the interrupt task itself - \
10014             until the parked run has actually stopped"
10015        );
10016    }
10017
10018    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
10019    /// grow a special case for it: an urgent candidate that is not the
10020    /// interrupt task withholds exactly like an ordinary one for as long as
10021    /// the parked run it is racing has not actually left flight. A version
10022    /// of this feature once bypassed the gate for urgent candidates, on the
10023    /// theory that a genuinely separate concurrency lane could not collide
10024    /// with 75dd's own; it could, and did - the bypassed task dispatched
10025    /// alongside a run 75dd's own state machine had only *asked* to park,
10026    /// not yet confirmed gone, which is exactly the second run
10027    /// `Interrupt::Parking`'s own doc says must never happen. There is no
10028    /// tick during Parking/Running/Resuming where letting an extra
10029    /// candidate through is safe, urgent or not - the parked run may still
10030    /// be genuinely mid-call.
10031    #[test]
10032    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
10033        for state in [
10034            Interrupt::Parking {
10035                parked: vec!["running".to_owned()],
10036                interrupt_task: "marked".to_owned(),
10037            },
10038            Interrupt::Running {
10039                parked: vec!["running".to_owned()],
10040                interrupt_task: "marked".to_owned(),
10041            },
10042            Interrupt::Resuming {
10043                parked: vec!["running".to_owned()],
10044            },
10045        ] {
10046            let candidates = vec![
10047                interrupt_task("marked"),
10048                urgent_task("hot"),
10049                task_with_id("ordinary"),
10050            ];
10051            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
10052            assert!(
10053                !allowed.iter().any(|t| t.id == "hot"),
10054                "an urgent candidate must wait out the same gate as anything \
10055                 else while the run it would run alongside has not actually \
10056                 left flight, for state {state:?}: {allowed:?}"
10057            );
10058        }
10059    }
10060
10061    /// The one case where marking a task `--urgent` and `interrupt` at once
10062    /// is not redundant: once the interrupt sequence's own guaranteed
10063    /// resume/dispatch actually admits the task, it is unaffected by also
10064    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
10065    /// never on the urgent flag.
10066    #[test]
10067    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
10068        let state = Interrupt::Resuming {
10069            parked: vec!["hot".to_owned()],
10070        };
10071        let candidates = vec![urgent_task("hot"), task()];
10072        let allowed = interrupt_gate(&state, &[], candidates);
10073        assert_eq!(
10074            allowed.iter().filter(|t| t.id == "hot").count(),
10075            1,
10076            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
10077        );
10078    }
10079
10080    #[test]
10081    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
10082        let state = Interrupt::Parking {
10083            parked: vec!["running".to_owned()],
10084            interrupt_task: "marked".to_owned(),
10085        };
10086        let other = task();
10087        let candidates = vec![interrupt_task("marked"), other.clone()];
10088        let allowed = interrupt_gate(&state, &[], candidates);
10089        assert_eq!(allowed.len(), 1);
10090        assert_eq!(allowed[0].id, "marked");
10091    }
10092
10093    #[test]
10094    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
10095        let state = Interrupt::Running {
10096            parked: vec!["running".to_owned()],
10097            interrupt_task: "marked".to_owned(),
10098        };
10099        let candidates = vec![task(), task()];
10100        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
10101        assert!(allowed.is_empty());
10102    }
10103
10104    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
10105    /// sequence began (only reachable above the default
10106    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
10107    /// never both in the same tick, which is what "exactly one resume, no
10108    /// simultaneous run" actually requires structurally rather than by
10109    /// coincidence of how many ordinary slots happen to be free.
10110    #[test]
10111    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
10112        let state = Interrupt::Resuming {
10113            parked: vec!["a".to_owned(), "c".to_owned()],
10114        };
10115        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
10116        let allowed = interrupt_gate(&state, &[], candidates);
10117        assert_eq!(
10118            allowed.len(),
10119            1,
10120            "at most one candidate may be offered while resuming: {allowed:?}"
10121        );
10122        assert_eq!(allowed[0].id, "a");
10123    }
10124
10125    #[test]
10126    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
10127        let state = Interrupt::Resuming {
10128            parked: vec!["a".to_owned()],
10129        };
10130        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
10131        assert!(allowed.is_empty());
10132    }
10133
10134    /// The invariant the completion criteria ask for by name: across a whole
10135    /// simulated sequence, there is never a tick where the gate would let
10136    /// through both the parked run's resume and the interrupt task, and
10137    /// exactly one candidate resumes the instant the interrupt task's run
10138    /// ends - never zero, never more than one.
10139    #[test]
10140    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
10141        let running = task(); // id: whatever `Task::new` minted
10142        let marked = interrupt_task("marked");
10143
10144        let mut state = Interrupt::Idle;
10145        // Tick 1: `running` is in flight, `marked` becomes runnable.
10146        let in_flight = vec![running.id.clone()];
10147        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
10148        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
10149        assert!(gated.is_empty(), "still waiting on `running` to park");
10150
10151        // Tick 2: `running` parked and left flight; nothing dispatched yet.
10152        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
10153        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
10154        assert_eq!(
10155            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10156            vec!["marked"],
10157            "only the interrupt task may be offered to the dispatcher now"
10158        );
10159
10160        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
10161        state = advance_interrupt_tick(
10162            true,
10163            state,
10164            &["marked".to_owned()],
10165            std::slice::from_ref(&running),
10166        );
10167        let gated = interrupt_gate(
10168            &state,
10169            &["marked".to_owned()],
10170            vec![marked.clone(), running.clone()],
10171        );
10172        assert!(
10173            gated.is_empty(),
10174            "the parked run must not be offered back while the interrupt \
10175             task is still running"
10176        );
10177
10178        // Tick 4: `marked`'s run reached a terminal status and left flight.
10179        // A higher-priority ordinary task `other` is also runnable now - it
10180        // must not be let through instead of, or alongside, `running`.
10181        let other = task_with_id("other");
10182        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
10183        assert_eq!(
10184            state,
10185            Interrupt::Resuming {
10186                parked: vec![running.id.clone()]
10187            }
10188        );
10189        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
10190        assert_eq!(
10191            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10192            vec![running.id.as_str()],
10193            "exactly the parked run resumes - not the unrelated task, even \
10194             though it was offered first"
10195        );
10196
10197        // Tick 5: `running` is now in flight (dispatched from tick 4's
10198        // gate). Only now does the sequence end and ordinary dispatch fully
10199        // resume.
10200        state = advance_interrupt_tick(
10201            true,
10202            state,
10203            std::slice::from_ref(&running.id),
10204            std::slice::from_ref(&other),
10205        );
10206        assert_eq!(state, Interrupt::Idle);
10207        let gated = interrupt_gate(
10208            &state,
10209            std::slice::from_ref(&running.id),
10210            vec![other.clone()],
10211        );
10212        assert_eq!(
10213            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
10214            vec![other.id.as_str()],
10215            "ordinary dispatch is unrestricted again"
10216        );
10217    }
10218
10219    #[test]
10220    fn every_run_status_settles_the_task_it_came_from() {
10221        // run status, resulting task status, attempts still standing after one
10222        let table = [
10223            (RunStatus::Merged, TaskStatus::Done, 1),
10224            (RunStatus::Ready, TaskStatus::Held, 1),
10225            (RunStatus::Stalled, TaskStatus::Failed, 0),
10226            (RunStatus::Blocked, TaskStatus::Failed, 1),
10227            (RunStatus::Failed, TaskStatus::Failed, 1),
10228            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
10229            (RunStatus::Prep, TaskStatus::Failed, 1),
10230            (RunStatus::Implementing, TaskStatus::Failed, 1),
10231            (RunStatus::Judging, TaskStatus::Failed, 1),
10232            (RunStatus::Deliberating, TaskStatus::Failed, 1),
10233            (RunStatus::Voting, TaskStatus::Failed, 1),
10234            (RunStatus::Reviewing, TaskStatus::Failed, 1),
10235            (RunStatus::Gating, TaskStatus::Failed, 1),
10236        ];
10237        for (run, want, attempts) in table {
10238            let mut t = task();
10239            t.start("20260902-000000-aaaa".to_owned());
10240            settle(
10241                &mut t,
10242                Verdict {
10243                    status: run,
10244                    left_pr: false,
10245                    parked: false,
10246                    quota_hit: matches!(run, RunStatus::Stalled),
10247                    no_viable_candidates: false,
10248                },
10249                "why",
10250                2,
10251            );
10252            assert_eq!(t.status, want, "task status after {}", label(run));
10253            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
10254        }
10255    }
10256
10257    #[test]
10258    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
10259        let mut stalled = task();
10260        stalled.start("20260902-000000-aaaa".to_owned());
10261        settle(
10262            &mut stalled,
10263            Verdict {
10264                status: RunStatus::Stalled,
10265                left_pr: false,
10266                parked: false,
10267                quota_hit: true,
10268                no_viable_candidates: false,
10269            },
10270            "quota",
10271            1,
10272        );
10273        assert_eq!(stalled.attempts, 0);
10274        assert!(
10275            stalled.status.runnable(),
10276            "a machine problem must leave the task in line"
10277        );
10278
10279        let mut blocked = task();
10280        blocked.start("20260902-000000-aaaa".to_owned());
10281        settle(
10282            &mut blocked,
10283            Verdict {
10284                status: RunStatus::Blocked,
10285                left_pr: false,
10286                parked: false,
10287                quota_hit: false,
10288                no_viable_candidates: false,
10289            },
10290            "findings open",
10291            1,
10292        );
10293        assert_eq!(blocked.attempts, 1);
10294        assert_eq!(
10295            blocked.status,
10296            TaskStatus::Held,
10297            "the last attempt hands the task to a human"
10298        );
10299    }
10300
10301    #[test]
10302    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
10303        // Attempts to spare: without the pull request this task would go
10304        // straight back in line and run the whole competition again.
10305        let mut delivered = task();
10306        delivered.start("20260903-080619-01c2".to_owned());
10307        settle(
10308            &mut delivered,
10309            Verdict {
10310                status: RunStatus::Blocked,
10311                left_pr: true,
10312                parked: false,
10313                quota_hit: false,
10314                no_viable_candidates: false,
10315            },
10316            "no check status",
10317            4,
10318        );
10319        assert_eq!(
10320            delivered.status,
10321            TaskStatus::Held,
10322            "a pull request waiting on CI or a person is not a retryable failure"
10323        );
10324        assert!(
10325            !delivered.status.runnable(),
10326            "the loop must not pick this task up again"
10327        );
10328        assert_eq!(
10329            delivered.last_error.as_deref(),
10330            Some("no check status"),
10331            "the operator needs to be told what the gate was waiting for"
10332        );
10333
10334        // The same status without a pull request is a plain failure, and with
10335        // attempts left it is retried.
10336        let mut empty_handed = task();
10337        empty_handed.start("20260903-080619-01c2".to_owned());
10338        settle(
10339            &mut empty_handed,
10340            Verdict {
10341                status: RunStatus::Blocked,
10342                left_pr: false,
10343                parked: false,
10344                quota_hit: false,
10345                no_viable_candidates: false,
10346            },
10347            "findings open",
10348            4,
10349        );
10350        assert_eq!(empty_handed.status, TaskStatus::Failed);
10351        assert!(empty_handed.status.runnable());
10352    }
10353
10354    #[test]
10355    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
10356        // Every candidate agreed, with evidence, that nothing belonged in the
10357        // worktree. That is not a confirmed success to close automatically -
10358        // a human still has to check the claim - and it is not an ordinary
10359        // failure either, so this settles exactly like a pull request nobody
10360        // merged yet: `Held`, same as `Blocked` with a PR.
10361        let mut noop = task();
10362        noop.start("20260912-131304-391f".to_owned());
10363        settle(
10364            &mut noop,
10365            Verdict {
10366                status: RunStatus::VerifiedNoop,
10367                left_pr: false,
10368                parked: false,
10369                quota_hit: false,
10370                no_viable_candidates: true,
10371            },
10372            "candidate A: already fixed by b32cfc4, on main",
10373            4,
10374        );
10375        assert_eq!(
10376            noop.status,
10377            TaskStatus::Held,
10378            "an unverified claim is a request for a human, not a failure"
10379        );
10380        assert!(
10381            !noop.status.runnable(),
10382            "the loop must not requeue this on the same unverified claim"
10383        );
10384        // `Task::release` resets attempts to zero the moment a human looks at
10385        // the evidence and lets it run again, so it does not matter here
10386        // whether the one attempt already spent stays spent - what matters is
10387        // that nothing retries this task unattended in the meantime.
10388        assert_eq!(noop.attempts, 1);
10389    }
10390
10391    #[test]
10392    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
10393        // Parking is the operator asking for the process back - to replace the
10394        // binary, most of all. The run's work is intact on disk, so this is
10395        // not a failed attempt, and charging for it would mean a few upgrades
10396        // could exhaust a budget meant for agents that misbehaved.
10397        let mut parked = task();
10398        parked.start("20260903-183634-2d98".to_owned());
10399        settle(
10400            &mut parked,
10401            Verdict {
10402                status: RunStatus::Implementing,
10403                left_pr: false,
10404                quota_hit: false,
10405                parked: true,
10406                no_viable_candidates: false,
10407            },
10408            "parked after `implementing`",
10409            2,
10410        );
10411        assert_eq!(parked.attempts, 0, "a park is refunded");
10412        assert!(
10413            parked.status.runnable(),
10414            "and the task stays in line so the next loop resumes its run"
10415        );
10416        assert_eq!(parked.status, TaskStatus::Parked);
10417        assert_eq!(
10418            parked.park_reason.as_deref(),
10419            Some("parked after `implementing`"),
10420            "the card says where it stopped"
10421        );
10422        assert_eq!(parked.last_error, None, "nothing failed");
10423
10424        // Without the park flag the same non-terminal status is what it always
10425        // was: `execute` returning mid-flight, which is a bug and spends an
10426        // attempt so a task cannot loop on it forever.
10427        let mut broken = task();
10428        broken.start("20260903-183634-2d98".to_owned());
10429        settle(
10430            &mut broken,
10431            Verdict {
10432                status: RunStatus::Implementing,
10433                left_pr: false,
10434                quota_hit: false,
10435                parked: false,
10436                no_viable_candidates: false,
10437            },
10438            "returned mid-flight",
10439            2,
10440        );
10441        assert_eq!(broken.attempts, 1);
10442    }
10443
10444    #[test]
10445    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
10446        // Run e633: quorum lost because two judges answered with the wrong
10447        // JSON shape, `quota: []`. Refunding that takes the bound off the
10448        // retry loop, and each retry pays for a fresh hour-long implement
10449        // wave before it can fail the same way.
10450        let mut flaky = task();
10451        flaky.start("20260903-123023-e633".to_owned());
10452        settle(
10453            &mut flaky,
10454            Verdict {
10455                status: RunStatus::Stalled,
10456                left_pr: false,
10457                parked: false,
10458                quota_hit: false,
10459                no_viable_candidates: false,
10460            },
10461            "verdict rests on 1 of 3 judges",
10462            2,
10463        );
10464        assert_eq!(
10465            flaky.attempts, 1,
10466            "flakiness spends an attempt, so `max_attempts` still bounds it"
10467        );
10468        assert!(flaky.status.runnable(), "and it is still worth retrying");
10469
10470        // The same status, lost to a rate limit, is the machine's fault.
10471        let mut limited = task();
10472        limited.start("20260903-123023-e633".to_owned());
10473        settle(
10474            &mut limited,
10475            Verdict {
10476                status: RunStatus::Stalled,
10477                left_pr: false,
10478                parked: false,
10479                quota_hit: true,
10480                no_viable_candidates: false,
10481            },
10482            "judge-2, judge-3 out of quota",
10483            2,
10484        );
10485        assert_eq!(limited.attempts, 0, "a quota window is refunded");
10486        assert!(limited.status.runnable());
10487
10488        // And the bound really binds: a task that keeps stalling on flakiness
10489        // reaches a human instead of running the roster forever.
10490        let mut worn = task();
10491        for _ in 0..2 {
10492            worn.release();
10493        }
10494        worn.start("20260903-123023-e633".to_owned());
10495        worn.attempts = 2;
10496        settle(
10497            &mut worn,
10498            Verdict {
10499                status: RunStatus::Stalled,
10500                left_pr: false,
10501                parked: false,
10502                quota_hit: false,
10503                no_viable_candidates: false,
10504            },
10505            "no quorum again",
10506            2,
10507        );
10508        assert_eq!(worn.status, TaskStatus::Held);
10509        assert!(!worn.status.runnable());
10510    }
10511
10512    #[test]
10513    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
10514        // The implement wave loses every seat to the same rate limit and
10515        // `after_implement` bails with nothing viable, which surfaces as
10516        // `Failed` rather than `Stalled`. That is the same machine fact the
10517        // `Stalled`-quota row already refunds, and must be refunded the same
10518        // way, or a quota outage quietly holds every task it touches instead
10519        // of leaving them in line for the reset.
10520        let mut wiped_out = task();
10521        wiped_out.start("20260907-025000-a1b2".to_owned());
10522        settle(
10523            &mut wiped_out,
10524            Verdict {
10525                status: RunStatus::Failed,
10526                left_pr: false,
10527                parked: false,
10528                quota_hit: true,
10529                no_viable_candidates: true,
10530            },
10531            "no candidate produced a change; nothing to judge",
10532            2,
10533        );
10534        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
10535        assert!(
10536            wiped_out.status.runnable(),
10537            "a machine problem must leave the task in line"
10538        );
10539
10540        // This is the exemption that must stay narrow: a candidate that did
10541        // produce a change, and then failed for some other reason, still
10542        // spends the attempt even though a seat elsewhere hit its quota.
10543        // Otherwise every ordinary failure that happens to share a run with
10544        // an unrelated rate limit would be refunded for free.
10545        let mut partial_progress = task();
10546        partial_progress.start("20260907-025500-c3d4".to_owned());
10547        settle(
10548            &mut partial_progress,
10549            Verdict {
10550                status: RunStatus::Failed,
10551                left_pr: false,
10552                parked: false,
10553                quota_hit: true,
10554                no_viable_candidates: false,
10555            },
10556            "gate failed on the winning candidate",
10557            2,
10558        );
10559        assert_eq!(
10560            partial_progress.attempts, 1,
10561            "a candidate that actually produced a change spends the attempt \
10562             even though some other seat hit its quota"
10563        );
10564        assert!(partial_progress.status.runnable());
10565    }
10566
10567    #[test]
10568    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
10569        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
10570        // disk, and that construction must reach the same conclusion as the
10571        // one `attempt` builds from a live run, or a crash at exactly the
10572        // wrong moment gives a recovered task a different policy than one a
10573        // daemon finished settling itself.
10574        let mut t = task();
10575        t.start("20260907-025000-a1b2".to_owned());
10576        let mut state = run_state(RunStatus::Failed);
10577        state.quota.push(QuotaLoss {
10578            cause: crate::agent::QuotaCause::UsageLimit,
10579            agent: String::new(),
10580            seat: "cand-a".to_owned(),
10581            node: "implement".to_owned(),
10582            at: Timestamp::now(),
10583            reset: None,
10584        });
10585        assert!(
10586            state.viable().is_empty(),
10587            "no candidate was added, so nothing is viable"
10588        );
10589        reclaim(&mut t, Some(state), 2, "en");
10590        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
10591        assert!(t.status.runnable());
10592    }
10593
10594    #[test]
10595    fn a_held_task_is_never_offered_to_the_loop() {
10596        let dir = tempfile::tempdir().unwrap();
10597        let queue = Queue::at(dir.path().to_path_buf());
10598        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
10599            let mut t = task();
10600            t.id = format!("2026090{n}-000000-000{n}");
10601            t.priority = priority;
10602            queue.put(&mut t).unwrap();
10603        }
10604        let mut held = task();
10605        held.id = "20260909-000000-9999".to_owned();
10606        held.priority = 99;
10607        held.hold_machine(None);
10608        queue.put(&mut held).unwrap();
10609
10610        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
10611        assert_eq!(order.len(), 3);
10612        assert!(!order.contains(&held.id));
10613        assert_eq!(
10614            order.first().cloned(),
10615            queue.next_runnable().map(|t| t.id),
10616            "the loop's first candidate is exactly what the queue offers"
10617        );
10618        assert_eq!(
10619            order,
10620            vec![
10621                "20260902-000000-0002".to_owned(),
10622                "20260903-000000-0003".to_owned(),
10623                "20260901-000000-0001".to_owned(),
10624            ],
10625            "priority first, then oldest, so nothing starves"
10626        );
10627    }
10628
10629    #[test]
10630    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
10631        let dir = tempfile::tempdir().unwrap();
10632        let queue = Queue::at(dir.path().to_path_buf());
10633        let mut old = task();
10634        old.id = "20260101-000000-old0".to_owned();
10635        queue.put(&mut old).unwrap();
10636        let mut fresh = task();
10637        fresh.id = "20260101-000000-new0".to_owned();
10638        queue.put(&mut fresh).unwrap();
10639
10640        // No parseable pid at all, so age is the only signal there is to
10641        // check - unlike a real `Queue::claim`, which always names a real,
10642        // and therefore alive, pid this test cannot fake as dead.
10643        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
10644        std::thread::sleep(Duration::from_millis(60));
10645        let live = queue.claim(&fresh.id).unwrap();
10646
10647        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10648        assert_eq!(swept, vec![old.id.clone()]);
10649        assert!(
10650            queue.claim(&old.id).is_ok(),
10651            "an unparseable lock older than the threshold is swept"
10652        );
10653        assert!(
10654            queue.claim(&fresh.id).is_err(),
10655            "a live pid protects its lock regardless of age"
10656        );
10657        drop(live);
10658    }
10659
10660    #[test]
10661    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
10662        // A live worker's claim remains authoritative even beyond the sweep's
10663        // age limit. Sweeping it would permit a second competing attempt.
10664        let dir = tempfile::tempdir().unwrap();
10665        let queue = Queue::at(dir.path().to_path_buf());
10666        let mut t = task();
10667        t.id = "20260101-000000-live".to_owned();
10668        queue.put(&mut t).unwrap();
10669
10670        let claim = queue.claim(&t.id).unwrap();
10671        std::thread::sleep(Duration::from_millis(60));
10672
10673        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
10674        assert!(
10675            swept.is_empty(),
10676            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
10677        );
10678        assert!(
10679            queue.claim(&t.id).is_err(),
10680            "the lock still protects its task"
10681        );
10682        drop(claim);
10683    }
10684
10685    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
10686    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
10687    fn injected_dead_pid() -> u32 {
10688        std::process::id().checked_add(1).unwrap_or(1)
10689    }
10690
10691    #[test]
10692    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
10693        let dir = tempfile::tempdir().unwrap();
10694        let queue = Queue::at(dir.path().to_path_buf());
10695        let mut t = task();
10696        t.id = "20260101-000000-dead".to_owned();
10697        queue.put(&mut t).unwrap();
10698        let dead_pid = injected_dead_pid();
10699
10700        // Written directly rather than through `Queue::claim`, which would
10701        // stamp this test process's own very much alive pid and defeat the
10702        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
10703        // like moments after it died, not six hours later.
10704        std::fs::write(
10705            dir.path().join(format!("{}.lock", t.id)),
10706            dead_pid.to_string(),
10707        )
10708        .unwrap();
10709
10710        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10711            pid != dead_pid
10712        });
10713        assert_eq!(
10714            swept,
10715            vec![t.id.clone()],
10716            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
10717        );
10718        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
10719    }
10720
10721    #[test]
10722    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
10723        let dir = tempfile::tempdir().unwrap();
10724        let queue = Queue::at(dir.path().to_path_buf());
10725        let mut t = task();
10726        t.id = "20260101-000000-late".to_owned();
10727        queue.put(&mut t).unwrap();
10728        let dead_pid = injected_dead_pid();
10729
10730        // Tick one, standing in for the sweep `poll` already runs at
10731        // startup: nothing to find yet.
10732        assert!(
10733            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
10734            "nothing has claimed the task yet"
10735        );
10736
10737        // A second daemon claims the task and dies before it ever writes
10738        // `running`, well after this loop's own startup sweep already ran.
10739        std::fs::write(
10740            dir.path().join(format!("{}.lock", t.id)),
10741            dead_pid.to_string(),
10742        )
10743        .unwrap();
10744
10745        // Tick two, standing in for a poll long into this daemon's uptime:
10746        // the same function, called again, notices what only just appeared -
10747        // proving the sweep is not a one-shot startup check.
10748        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10749            pid != dead_pid
10750        });
10751        assert_eq!(swept, vec![t.id.clone()]);
10752    }
10753
10754    #[test]
10755    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
10756        // `reclaim_orphaned_running` looks up the task's last run, which
10757        // touches `run::home()`; the first call anywhere in this binary wins,
10758        // so this is a no-op if another test already pinned one, and either
10759        // way the run id below is never written under it.
10760        crate::run::pin_test_home();
10761        let dir = tempfile::tempdir().unwrap();
10762        let queue = Queue::at(dir.path().to_path_buf());
10763        let mut t = task();
10764        t.id = "20260101-000000-crsh".to_owned();
10765        t.status = TaskStatus::Running;
10766        t.attempts = 1;
10767        // No `run.json` behind this id: standing in for a run this test does
10768        // not need to make readable, since the point is the lock, not the
10769        // recovery table `reclaim` already has its own tests for.
10770        t.runs.push("20260904-000000-4043".to_owned());
10771        queue.put(&mut t).unwrap();
10772        let dead_pid = injected_dead_pid();
10773
10774        // The crashed daemon's own claim, naming a pid nothing on the
10775        // machine holds anymore.
10776        std::fs::write(
10777            dir.path().join(format!("{}.lock", t.id)),
10778            dead_pid.to_string(),
10779        )
10780        .unwrap();
10781
10782        // Before the lock is swept the task looks claimed, and
10783        // `reclaim_orphaned_running` must leave it alone - this is exactly
10784        // the bug: a `running` task stranded behind a dead daemon's lock,
10785        // invisible to the claim-as-proof check because the lock outlived
10786        // the process that wrote it.
10787        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
10788        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
10789
10790        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
10791            pid != dead_pid
10792        });
10793        assert_eq!(swept, vec![t.id.clone()]);
10794
10795        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10796        assert_eq!(reclaimed, vec![t.id.clone()]);
10797        let after = queue.get(&t.id).unwrap();
10798        assert_eq!(
10799            after.status,
10800            TaskStatus::Held,
10801            "no run.json to recover from, so a human is asked"
10802        );
10803        assert_eq!(
10804            after.runs,
10805            vec!["20260904-000000-4043".to_owned()],
10806            "the crashed run's id is kept as evidence, not discarded"
10807        );
10808    }
10809
10810    #[test]
10811    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
10812        let dir = tempfile::tempdir().unwrap();
10813        let queue = Queue::at(dir.path().to_path_buf());
10814        let mut t = task();
10815        t.id = "20260101-000000-unknown".to_owned();
10816        queue.put(&mut t).unwrap();
10817        let dead_pid = injected_dead_pid();
10818        std::fs::write(
10819            dir.path().join(format!("{}.lock", t.id)),
10820            dead_pid.to_string(),
10821        )
10822        .unwrap();
10823
10824        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
10825        assert!(swept.is_empty(), "an unknown pid must keep its lock");
10826        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
10827    }
10828
10829    fn run_state_in(status: RunStatus, language: &str) -> RunState {
10830        let mut s = run_state(status);
10831        s.config.graph.language = language.to_owned();
10832        s
10833    }
10834
10835    fn unstarted_verdict(status: RunStatus) -> Verdict {
10836        Verdict {
10837            status,
10838            left_pr: false,
10839            quota_hit: false,
10840            parked: false,
10841            no_viable_candidates: false,
10842        }
10843    }
10844
10845    #[test]
10846    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
10847        let mut t = task();
10848        t.attempts = 1;
10849        settle_in(
10850            &mut t,
10851            unstarted_verdict(RunStatus::AlreadyInBase),
10852            "already in main",
10853            1,
10854            phrases("en"),
10855            None,
10856        );
10857        assert_eq!(t.status, TaskStatus::Done);
10858        assert_eq!(t.attempts, 0);
10859    }
10860
10861    #[test]
10862    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
10863        let reason = |language: &str| {
10864            let mut t = task();
10865            settle_in(
10866                &mut t,
10867                unstarted_verdict(RunStatus::Judging),
10868                "boom",
10869                1,
10870                phrases(language),
10871                None,
10872            );
10873            t.last_error.or(t.hold_reason).unwrap_or_default()
10874        };
10875        assert!(
10876            reason("en").starts_with("the graph stopped at `"),
10877            "{}",
10878            reason("en")
10879        );
10880        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
10881        assert!(reason("日本語").contains("boom"));
10882        assert_eq!(reason("fr"), reason("en"));
10883    }
10884
10885    #[test]
10886    fn describe_follows_the_run_language_and_keeps_the_run_id() {
10887        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
10888        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
10889        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
10890        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
10891        assert!(ja.contains("[run "), "{ja}");
10892        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
10893        assert!(ended.starts_with("run 終了: "), "{ended}");
10894        let mut de = run_state_in(RunStatus::Failed, "de");
10895        let mut en = run_state_in(RunStatus::Failed, "en");
10896        de.id = "same".to_owned();
10897        en.id = "same".to_owned();
10898        assert_eq!(describe(&de), describe(&en));
10899    }
10900
10901    #[test]
10902    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
10903        use crate::handover::Refused;
10904        let cases = [
10905            Refused::Foreign {
10906                branch: "b".into(),
10907                path: "/w/x".into(),
10908                why: "made by hand".into(),
10909            },
10910            Refused::Unsafe {
10911                branch: "b".into(),
10912                path: "/w/x".into(),
10913                why: "its worktree has uncommitted changes (a.rs)".into(),
10914            },
10915            Refused::ReleaseFailed {
10916                branch: "b".into(),
10917                path: "/w/x".into(),
10918                run: "ab12".into(),
10919            },
10920        ];
10921        for r in &cases {
10922            let en = (phrases("en").handover_refused)(r);
10923            assert_eq!(en, r.to_string());
10924            let ja = (phrases("ja").handover_refused)(r);
10925            assert!(
10926                !ja.contains("is checked out") && !ja.contains("try again"),
10927                "{ja}"
10928            );
10929            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
10930            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
10931                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
10932            }
10933        }
10934        assert!(phrases("en").handover_hint.contains("release the task"));
10935        assert!(phrases("ja").handover_hint.contains("解放"));
10936    }
10937
10938    #[test]
10939    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
10940        let build = |lang: &str| {
10941            let mut s = run_state_in(RunStatus::Blocked, lang);
10942            s.id = "same".to_owned();
10943            s.config.graph.review_rounds = 3;
10944            let mut r = review_round(3);
10945            r.expected = 3;
10946            r.answered = 1;
10947            s.reviews.push(r);
10948            s.event(
10949                "review",
10950                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
10951            );
10952            s
10953        };
10954        let en = describe(&build("en"));
10955        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
10956        let ja = describe(&build("ja"));
10957        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
10958        assert!(!ja.contains("never answered"), "{ja}");
10959        assert!(ja.contains("[run "), "{ja}");
10960
10961        // An incomplete panel whose verification failed is a different stop:
10962        // the real event must survive in ja too.
10963        let mut failed = build("ja");
10964        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
10965            command: "cargo test".to_owned(),
10966            code: Some(1),
10967            output_tail: String::new(),
10968            duration_ms: 0,
10969            resource_blocked: false,
10970            ..Default::default()
10971        });
10972        failed.event("review", "stopped; e2e failed: cargo test");
10973        let ja = describe(&failed);
10974        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
10975        assert!(!ja.contains("席のレビュアー"), "{ja}");
10976    }
10977
10978    #[test]
10979    fn refusals_and_recovery_prose_follow_the_language() {
10980        let home = crate::run::test_home();
10981        let t = held_task_with("r1");
10982        let q = action_question(
10983            "r1",
10984            ask::ChoiceAction::Resume {
10985                run: "r1".to_owned(),
10986            },
10987        );
10988        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
10989            ActionDecision::Refuse(s) => s,
10990            other => panic!("{other:?}"),
10991        };
10992        assert!(refuse(phrases("en")).contains("could not be read: gone"));
10993        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
10994        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
10995
10996        let mut held = task();
10997        reclaim(&mut held, None, 2, "ja");
10998        assert!(held.hold_reason.unwrap().contains("保留にしました"));
10999        let mut held = task();
11000        reclaim(&mut held, None, 2, "xx");
11001        assert!(held.hold_reason.unwrap().contains("held for a human"));
11002    }
11003
11004    fn run_state(status: RunStatus) -> RunState {
11005        let mut state = RunState::new(
11006            PathBuf::from("/repo"),
11007            "main".to_owned(),
11008            "abc1234def".to_owned(),
11009            "add retries".to_owned(),
11010            Config::default(),
11011        );
11012        state.status = status;
11013        state
11014    }
11015
11016    #[test]
11017    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
11018        crate::run::pin_test_home();
11019        let dir = tempfile::tempdir().unwrap();
11020        let mut state = run_state(RunStatus::Blocked);
11021        state.id = "20260101-000000-audit".into();
11022        state.save_under(dir.path()).unwrap();
11023        let mut t = task();
11024        t.start(state.id.clone());
11025        // The final state is newer than disk, as when a worker settles its
11026        // in-memory outcome or recovery is passed an already loaded run.
11027        state.status = RunStatus::Merged;
11028        settle_and_diagnose(
11029            &mut t,
11030            unstarted_verdict(RunStatus::Merged),
11031            "Verified delivery",
11032            2,
11033            &state,
11034        );
11035        let completion = t.completion_history.last().unwrap();
11036        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
11037        assert_eq!(completion.prior_status, TaskStatus::Running);
11038        assert_eq!(completion.reason.as_deref(), Some("Verified delivery"));
11039        let snapshot = completion.run.as_ref().unwrap();
11040        assert_eq!(snapshot.id, state.id);
11041        assert_eq!(snapshot.status, Some(RunStatus::Merged));
11042        assert_eq!(
11043            RunState::load_under(&state.id, dir.path()).unwrap().status,
11044            RunStatus::Blocked,
11045            "settlement records the actual outcome without rewriting run history"
11046        );
11047    }
11048
11049    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
11050        Candidate {
11051            index: 0,
11052            label,
11053            agent: "claude".to_owned(),
11054            branch: format!("magi/x/{label}"),
11055            worktree: PathBuf::from("/repo"),
11056            summary: summary.to_owned(),
11057            stat: String::new(),
11058            files: 0,
11059            commits: usize::from(!empty),
11060            empty,
11061            failed: failed.map(str::to_owned),
11062            verified_noop: None,
11063            duration_ms: 0,
11064            folded: false,
11065        }
11066    }
11067
11068    #[test]
11069    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
11070        let mut state = run_state(RunStatus::Blocked);
11071        state.gate = vec![
11072            CommandOutcome {
11073                command: "cargo make check".to_owned(),
11074                code: Some(0),
11075                output_tail: "ok".to_owned(),
11076                duration_ms: 0,
11077                resource_blocked: false,
11078                ..Default::default()
11079            },
11080            CommandOutcome {
11081                command: "cargo test".to_owned(),
11082                code: Some(101),
11083                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
11084                duration_ms: 0,
11085                resource_blocked: false,
11086                ..Default::default()
11087            },
11088        ];
11089        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
11090        assert!(d.contains("cargo test"), "{d}");
11091        assert!(
11092            !d.contains("cargo make check"),
11093            "a passing check is not a diagnostic: {d}"
11094        );
11095        assert!(d.contains("assertion failed"), "{d}");
11096    }
11097
11098    #[test]
11099    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
11100        let mut state = run_state(RunStatus::Blocked);
11101        state.event(
11102            "land",
11103            "stopped: the fixer produced no commit while 2 check(s) were failing \
11104             (build, lint); stopping instead of looping on an unchanged tree",
11105        );
11106        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
11107        assert!(d.contains("build"), "{d}");
11108        assert!(d.contains("lint"), "{d}");
11109        assert!(d.contains("fixer produced no commit"), "{d}");
11110    }
11111
11112    #[test]
11113    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
11114        // `describe`'s output becomes `Task::last_error` verbatim, and the
11115        // phone renders that in the same alarm-styled box an ordinary
11116        // failure gets. A bare `verified_noop` there would read exactly like
11117        // the failure this status exists to be told apart from.
11118        let state = run_state(RunStatus::VerifiedNoop);
11119        let d = describe(&state);
11120        assert!(
11121            d.contains("agent-verified no-op"),
11122            "expected the display label, not the wire spelling: {d}"
11123        );
11124        assert!(!d.contains("verified_noop"), "{d}");
11125    }
11126
11127    #[test]
11128    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
11129        let mut state = run_state(RunStatus::Failed);
11130        state.gate.push(crate::run::CommandOutcome {
11131            command: "cargo test".into(),
11132            code: Some(101),
11133            output_tail: format!(
11134                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
11135                "  41: 0x1234 - backtrace frame\n".repeat(10000)
11136            ),
11137            duration_ms: 1,
11138            resource_blocked: false,
11139            ..Default::default()
11140        });
11141        let d = diagnostic(&state).unwrap();
11142        assert!(d.contains("panicked at widget.rs:12"), "{d}");
11143        assert!(d.contains("assertion failed: widget missing"));
11144        assert!(d.contains("widget log"));
11145    }
11146
11147    #[test]
11148    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
11149        // The whole point of the feature: a run held as "no candidate produced
11150        // a change" can mean the implementer actually finished the task and
11151        // only left a clean local tree behind - see AGENTS.md on this exact
11152        // failure mode. The diagnostic has to carry what the agent actually
11153        // said, not just the fact that nothing was there to judge.
11154        let mut state = run_state(RunStatus::Failed);
11155        state.candidates = vec![candidate(
11156            'A',
11157            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
11158            true,
11159            None,
11160        )];
11161        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
11162        assert!(d.contains("candidate A"), "{d}");
11163        assert!(d.contains("tagged v1.2.3"), "{d}");
11164    }
11165
11166    #[test]
11167    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
11168        let mut state = run_state(RunStatus::Failed);
11169        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
11170        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
11171        assert!(d.contains("candidate A"), "{d}");
11172        assert!(d.contains("agent timed out"), "{d}");
11173    }
11174
11175    #[test]
11176    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
11177        // A viable candidate existed, the gate never ran, and nothing land
11178        // said matches - `Task::last_error` is left to explain this one alone.
11179        let mut state = run_state(RunStatus::Failed);
11180        state.candidates = vec![candidate('A', "did the work", false, None)];
11181        assert!(diagnostic(&state).is_none());
11182    }
11183
11184    #[test]
11185    fn diagnostic_is_bounded_however_much_a_run_printed() {
11186        let mut state = run_state(RunStatus::Blocked);
11187        state.gate = vec![
11188            CommandOutcome {
11189                command: "cargo test".to_owned(),
11190                code: Some(101),
11191                output_tail: "x".repeat(50_000),
11192                duration_ms: 0,
11193                resource_blocked: false,
11194                ..Default::default()
11195            },
11196            CommandOutcome {
11197                command: "cargo clippy".to_owned(),
11198                code: Some(1),
11199                output_tail: "y".repeat(50_000),
11200                duration_ms: 0,
11201                resource_blocked: false,
11202                ..Default::default()
11203            },
11204        ];
11205        state.candidates = vec![
11206            candidate('A', &"z".repeat(50_000), true, None),
11207            candidate('B', &"w".repeat(50_000), true, None),
11208        ];
11209        let d = diagnostic(&state).expect("plenty here to diagnose");
11210        assert!(
11211            d.len() <= DIAGNOSTIC_MAX,
11212            "diagnostic grew to {} bytes, unbounded",
11213            d.len()
11214        );
11215    }
11216
11217    #[test]
11218    fn selected_delivery_guards_survive_recovery_failure_accounting() {
11219        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
11220            let mut t = task();
11221            let mut state = run_state(status);
11222            t.pr_recovery = Some(crate::pr_recovery::Selection {
11223                url: "url".into(),
11224                branch: format!("magi/task-{}", t.id),
11225                head: "a".repeat(40),
11226                source_head: None,
11227                source_run: None,
11228                source_proof: None,
11229                disposition: Some(crate::pr_recovery::Disposition::Land),
11230                instruction: t.instruction.clone(),
11231                approved_at: Timestamp::now(),
11232            });
11233            state.pr_recovery = t.pr_recovery.clone();
11234            t.start(state.id.clone());
11235            settle_and_diagnose(
11236                &mut t,
11237                Verdict {
11238                    status,
11239                    left_pr: false,
11240                    quota_hit: false,
11241                    parked: false,
11242                    no_viable_candidates: false,
11243                },
11244                "delivery stopped",
11245                5,
11246                &state,
11247            );
11248            assert_eq!(t.status, TaskStatus::Held);
11249            let reason = t.hold_reason.as_deref().unwrap();
11250            if status == RunStatus::Ready {
11251                assert!(reason.contains("Selected PR delivery is incomplete"));
11252                assert!(t.recovery_budget.is_none());
11253            } else {
11254                assert!(reason.contains("Selected recovery stopped"));
11255                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
11256            }
11257            assert!(t.pr_recovery.is_some());
11258        }
11259    }
11260
11261    #[test]
11262    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
11263        let mut state = run_state(RunStatus::Voting);
11264        state.base_sync = Some(crate::run::BaseSync {
11265            tip: "base-tip".into(),
11266            behind: 3,
11267            attempts: 4,
11268            conflict: Some("base stopped".into()),
11269            already_in: None,
11270        });
11271        state.record_base_sync_stop("candidate-head");
11272        let mut t = task();
11273        t.start(state.id.clone());
11274        let verdict = Verdict {
11275            status: RunStatus::Blocked,
11276            left_pr: false,
11277            quota_hit: false,
11278            parked: false,
11279            no_viable_candidates: false,
11280        };
11281        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11282        assert_eq!(
11283            t.status,
11284            TaskStatus::Held,
11285            "unspent task attempts cannot start another competition"
11286        );
11287        let at = t.held_at;
11288        let cause = t.hold_notice_cause.clone();
11289        state.begin_pass();
11290        t.release_operator("test-resume", None);
11291        t.start(state.id.clone());
11292        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
11293        assert_eq!(t.status, TaskStatus::Held);
11294        assert_eq!(t.held_at, at);
11295        assert_eq!(t.hold_notice_cause, cause);
11296    }
11297
11298    #[test]
11299    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
11300        let mut state = run_state(RunStatus::Blocked);
11301        state.gate = vec![CommandOutcome {
11302            command: "cargo test".to_owned(),
11303            code: Some(101),
11304            output_tail: "assertion failed".to_owned(),
11305            duration_ms: 0,
11306            resource_blocked: false,
11307            ..Default::default()
11308        }];
11309        let verdict = Verdict {
11310            status: RunStatus::Blocked,
11311            left_pr: false,
11312            quota_hit: false,
11313            parked: false,
11314            no_viable_candidates: false,
11315        };
11316
11317        // Attempt one of two still has a retry coming: no diagnostic yet, the
11318        // task is going to run again and this run's evidence would go stale.
11319        let mut t = task();
11320        t.start("run-1".to_owned());
11321        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11322        assert_eq!(t.status, TaskStatus::Failed);
11323        assert!(t.diagnostic.is_none());
11324
11325        // Attempt two exhausts the budget: now it is held, and the
11326        // diagnostic is what `magi task show` has to say more than one line.
11327        t.start("run-2".to_owned());
11328        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
11329        assert_eq!(t.status, TaskStatus::Held);
11330        let d = t.diagnostic.expect("a held task must carry its diagnostic");
11331        assert!(d.contains("cargo test"), "{d}");
11332    }
11333
11334    fn verified_noop_run_state() -> RunState {
11335        let mut state = run_state(RunStatus::VerifiedNoop);
11336        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":[]}"#;
11337        let mut c = candidate('A', summary, true, None);
11338        c.verified_noop = Some(summary.to_owned());
11339        state.candidates = vec![c];
11340        state
11341    }
11342
11343    #[test]
11344    fn a_held_task_names_the_open_question_it_is_waiting_on() {
11345        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
11346        // `magi ask` question settled Held with `hold_reason: null`, so the
11347        // notification said nothing actionable. `note_open_question` should
11348        // append the question id to whatever `handed_off` already wrote.
11349        crate::run::pin_test_home();
11350        let home = crate::run::home();
11351        let state = verified_noop_run_state();
11352        let mut q = ask::Question::new(
11353            state.id.clone(),
11354            "implement".to_owned(),
11355            "impl-A".to_owned(),
11356            "is this really a no-op?".to_owned(),
11357            String::new(),
11358            Vec::new(),
11359        );
11360        Questions::at(home.join("questions")).put(&mut q).unwrap();
11361
11362        let verdict = Verdict {
11363            status: RunStatus::VerifiedNoop,
11364            left_pr: false,
11365            quota_hit: false,
11366            parked: false,
11367            no_viable_candidates: true,
11368        };
11369        let mut t = task();
11370        t.start(state.id.clone());
11371        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11372
11373        assert_eq!(t.status, TaskStatus::Held);
11374        let reason = t.hold_reason.expect("a held task must record why");
11375        assert!(
11376            reason.starts_with("run ended agent-verified no-op"),
11377            "the original settle reason must survive unchanged: {reason}"
11378        );
11379        assert!(
11380            reason.contains(q.short()),
11381            "the open question's id must be named so the notice is actionable: {reason}"
11382        );
11383    }
11384
11385    #[test]
11386    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
11387        crate::run::pin_test_home();
11388        let state = verified_noop_run_state();
11389
11390        let verdict = Verdict {
11391            status: RunStatus::VerifiedNoop,
11392            left_pr: false,
11393            quota_hit: false,
11394            parked: false,
11395            no_viable_candidates: true,
11396        };
11397        let mut t = task();
11398        t.start(state.id.clone());
11399        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
11400
11401        assert_eq!(t.status, TaskStatus::Held);
11402        assert_eq!(
11403            t.hold_reason.as_deref(),
11404            Some("run ended agent-verified no-op"),
11405            "nothing to append when the question was already answered or never asked"
11406        );
11407    }
11408
11409    #[test]
11410    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
11411        crate::run::pin_test_home();
11412
11413        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
11414        // regression prose instead of valid structured evidence.
11415        let mut bad = run_state(RunStatus::VerifiedNoop);
11416        let mut c = candidate(
11417            'A',
11418            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
11419            true,
11420            None,
11421        );
11422        c.verified_noop = Some("Not established.".to_owned());
11423        bad.candidates = vec![c];
11424
11425        let mut t = task();
11426        t.start(bad.id.clone());
11427        let verdict = Verdict {
11428            status: RunStatus::VerifiedNoop,
11429            left_pr: false,
11430            quota_hit: true,
11431            parked: false,
11432            no_viable_candidates: true,
11433        };
11434        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
11435        assert_eq!(
11436            t.status,
11437            TaskStatus::Failed,
11438            "inconsistent verified_noop must retry as Failed when attempts remain"
11439        );
11440        assert_eq!(t.attempts, 1);
11441        assert_eq!(
11442            t.last_error.as_deref(),
11443            Some("no-change result lacks verified evidence")
11444        );
11445        assert!(t.hold_reason.is_none());
11446
11447        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
11448        // attempts exhausted holds as `failed`, never `verified_noop`, and
11449        // never auto-closes to `Done`.
11450        let mut t_exhausted = task();
11451        t_exhausted.start(bad.id.clone());
11452        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
11453        assert_eq!(t_exhausted.status, TaskStatus::Held);
11454        assert_eq!(t_exhausted.attempts, 1);
11455        assert_eq!(
11456            t_exhausted
11457                .hold_notice_cause
11458                .as_ref()
11459                .map(|c| c.stage.as_str()),
11460            Some("failed"),
11461            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
11462        );
11463        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
11464        assert!(
11465            !diag.contains("agent-verified no-op"),
11466            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
11467        );
11468        assert!(diag.contains("Not established"), "{diag}");
11469    }
11470
11471    #[test]
11472    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
11473        let mut state = verified_noop_run_state();
11474        let summary = state.candidates[0].summary.clone();
11475        state.candidates[0].summary = "Already satisfied.".to_owned();
11476        assert!(state.all_candidates_verified_noop());
11477
11478        state.candidates[0].summary = summary;
11479        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
11480        assert!(!state.all_candidates_verified_noop());
11481    }
11482
11483    #[test]
11484    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
11485        crate::run::pin_test_home();
11486        let mut first = run_state(RunStatus::Blocked);
11487        first.id = "20260101-000000-sup1".to_owned();
11488        first.save().unwrap();
11489        let mut second = run_state(RunStatus::Merged);
11490        second.id = "20260101-000000-sup2".to_owned();
11491        second.save().unwrap();
11492
11493        let mut t = task();
11494        t.runs = vec![first.id.clone(), second.id.clone()];
11495        t.status = TaskStatus::Done;
11496
11497        supersede_prior_runs(&t, &crate::run::home());
11498
11499        assert_eq!(
11500            RunState::load(&first.id).unwrap().status,
11501            RunStatus::Superseded,
11502            "the first attempt's Blocked no longer needs anyone's attention"
11503        );
11504        assert_eq!(
11505            RunState::load(&second.id).unwrap().status,
11506            RunStatus::Merged,
11507            "the run that actually succeeded is left exactly as it was"
11508        );
11509    }
11510
11511    #[test]
11512    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
11513        // `is_working_on` alone only proves a *daemon* claim; a `magi run
11514        // --resume` invoked by hand outside the daemon never touches
11515        // `daemon.json` at all, so it would look identical to a genuinely
11516        // idle run without also consulting `RunState::liveness`, which reads
11517        // this run's own recorded `driver_pid` instead.
11518        crate::run::pin_test_home();
11519        let mut first = run_state(RunStatus::Blocked);
11520        first.id = "20260101-000000-sup9".to_owned();
11521        // This test process's own pid: guaranteed alive without needing a
11522        // real second process or daemon.
11523        first.driver_pid = Some(std::process::id());
11524        first.driver_started_at = Some(
11525            crate::proc::process_started_at(std::process::id())
11526                .expect("this test process's own start time must be queryable"),
11527        );
11528        first.save().unwrap();
11529        let mut second = run_state(RunStatus::Merged);
11530        second.id = "20260101-000000-supa".to_owned();
11531        second.save().unwrap();
11532
11533        let mut t = task();
11534        t.runs = vec![first.id.clone(), second.id.clone()];
11535        t.status = TaskStatus::Done;
11536
11537        supersede_prior_runs(&t, &crate::run::home());
11538
11539        assert_eq!(
11540            RunState::load(&first.id).unwrap().status,
11541            RunStatus::Blocked,
11542            "a live driver_pid means something is still actually working this run, \
11543             even though no daemon claims it - rewriting under it would just be \
11544             undone the next time that process saves"
11545        );
11546    }
11547
11548    #[test]
11549    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
11550        // The first resweep must skip a still-live attempt exactly like
11551        // `supersede_prior_runs` itself does; a later resweep, once that
11552        // process is no longer actually driving it, is what closes the gap
11553        // `supersede_prior_runs` alone leaves - a task only ever reaches
11554        // `Done` once, so nothing else would ever look at this run again.
11555        let dir = tempfile::tempdir().unwrap();
11556        let home = dir.path().to_path_buf();
11557        let queue = Queue::at(dir.path().join("queue"));
11558
11559        let mut first = run_state(RunStatus::Blocked);
11560        first.id = "20260101-000000-supd".to_owned();
11561        first.driver_pid = Some(std::process::id());
11562        first.driver_started_at = Some(
11563            crate::proc::process_started_at(std::process::id())
11564                .expect("this test process's own start time must be queryable"),
11565        );
11566        first.save_under(&home).unwrap();
11567        let mut second = run_state(RunStatus::Merged);
11568        second.id = "20260101-000000-supe".to_owned();
11569        second.save_under(&home).unwrap();
11570
11571        let mut t = task();
11572        t.runs = vec![first.id.clone(), second.id.clone()];
11573        t.status = TaskStatus::Done;
11574        queue.put(&mut t).unwrap();
11575
11576        resweep_superseded_attempts(&queue, &home);
11577        assert_eq!(
11578            RunState::load_under(&first.id, &home).unwrap().status,
11579            RunStatus::Blocked,
11580            "still live on the first pass, so still untouched"
11581        );
11582
11583        // Stand in for the manual process no longer being the one driving
11584        // this run: same pid (this test process really is still alive), but
11585        // an identity marker that no longer matches it - see
11586        // `RunState::liveness`'s own doc for why a mismatched
11587        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
11588        let mut stale = RunState::load_under(&first.id, &home).unwrap();
11589        stale.driver_started_at = Some("1".to_owned());
11590        stale.save_under(&home).unwrap();
11591
11592        resweep_superseded_attempts(&queue, &home);
11593        assert_eq!(
11594            RunState::load_under(&first.id, &home).unwrap().status,
11595            RunStatus::Superseded,
11596            "the second pass catches up what the first one correctly skipped"
11597        );
11598    }
11599
11600    #[test]
11601    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
11602        crate::run::pin_test_home();
11603        let mut first = run_state(RunStatus::Blocked);
11604        first.id = "20260101-000000-sup3".to_owned();
11605        first.save().unwrap();
11606        let mut second = run_state(RunStatus::Blocked);
11607        second.id = "20260101-000000-sup4".to_owned();
11608        second.save().unwrap();
11609
11610        let mut t = task();
11611        t.runs = vec![first.id.clone(), second.id.clone()];
11612        // Still retrying: nothing about this task's story is settled yet, so
11613        // neither Blocked run may be relabelled, even though a later attempt
11614        // already exists.
11615        t.status = TaskStatus::Failed;
11616
11617        supersede_prior_runs(&t, &crate::run::home());
11618
11619        assert_eq!(
11620            RunState::load(&first.id).unwrap().status,
11621            RunStatus::Blocked
11622        );
11623        assert_eq!(
11624            RunState::load(&second.id).unwrap().status,
11625            RunStatus::Blocked
11626        );
11627    }
11628
11629    #[test]
11630    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
11631        // `magi task done` (or the API's equivalent) can close a task with no
11632        // run of its own ever having succeeded - there is nothing here that
11633        // counts as "the attempt that finished it", so nothing is rewritten.
11634        crate::run::pin_test_home();
11635        let mut first = run_state(RunStatus::Blocked);
11636        first.id = "20260101-000000-sup5".to_owned();
11637        first.save().unwrap();
11638
11639        let mut t = task();
11640        t.runs = vec![first.id.clone()];
11641        t.status = TaskStatus::Done;
11642
11643        supersede_prior_runs(&t, &crate::run::home());
11644
11645        assert_eq!(
11646            RunState::load(&first.id).unwrap().status,
11647            RunStatus::Blocked,
11648            "a single-attempt task has no earlier run to supersede"
11649        );
11650    }
11651
11652    #[test]
11653    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
11654        for status in [
11655            RunStatus::Blocked,
11656            RunStatus::Stalled,
11657            RunStatus::Failed,
11658            RunStatus::Ready,
11659            RunStatus::Merged,
11660        ] {
11661            let dir = tempfile::tempdir().unwrap();
11662            let home = dir.path();
11663            let mut first = run_state(RunStatus::Blocked);
11664            first.id = "20260101-000000-supb".to_owned();
11665            first.save_under(home).unwrap();
11666            let mut second = run_state(status);
11667            second.id = "20260101-000000-supc".to_owned();
11668            second.save_under(home).unwrap();
11669
11670            let mut t = task();
11671            t.runs = vec![first.id.clone(), second.id.clone()];
11672            t.hold_manual(Some("Unmerged work remains".into()));
11673            let mut context = CompletionContext::new(
11674                CompletionActor::Cli,
11675                Some("Discard the unmerged attempts".into()),
11676                home,
11677                &t,
11678            );
11679            context.discard = true;
11680            t.succeed(context);
11681            assert_eq!(t.completion_history.len(), 1);
11682
11683            supersede_prior_runs(&t, home);
11684
11685            assert_eq!(
11686                RunState::load_under(&first.id, home).unwrap().status,
11687                RunStatus::Blocked,
11688                "an audited manual close is not proof the earlier work landed"
11689            );
11690            assert_eq!(
11691                RunState::load_under(&second.id, home).unwrap().status,
11692                status,
11693                "the latest attempt retains its actual outcome"
11694            );
11695        }
11696    }
11697
11698    #[test]
11699    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
11700        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
11701        // to look" - `Failed` and `VerifiedNoop` are already their own
11702        // terminal answers and must not be relabelled into a third one.
11703        crate::run::pin_test_home();
11704        let mut failed = run_state(RunStatus::Failed);
11705        failed.id = "20260101-000000-sup6".to_owned();
11706        failed.save().unwrap();
11707        let mut noop = run_state(RunStatus::VerifiedNoop);
11708        noop.id = "20260101-000000-sup7".to_owned();
11709        noop.save().unwrap();
11710        let mut winner = run_state(RunStatus::Ready);
11711        winner.id = "20260101-000000-sup8".to_owned();
11712        winner.save().unwrap();
11713
11714        let mut t = task();
11715        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
11716        t.status = TaskStatus::Done;
11717
11718        supersede_prior_runs(&t, &crate::run::home());
11719
11720        assert_eq!(
11721            RunState::load(&failed.id).unwrap().status,
11722            RunStatus::Failed
11723        );
11724        assert_eq!(
11725            RunState::load(&noop.id).unwrap().status,
11726            RunStatus::VerifiedNoop
11727        );
11728    }
11729
11730    fn approval_question(run: &str) -> ask::Question {
11731        ask::Question::new(
11732            run.to_owned(),
11733            land::APPROVAL_NODE.to_owned(),
11734            "land".to_owned(),
11735            "merge?".to_owned(),
11736            String::new(),
11737            vec!["merge".to_owned(), "hold".to_owned()],
11738        )
11739    }
11740
11741    #[test]
11742    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
11743        crate::run::pin_test_home();
11744        let mut state = run_state(RunStatus::Landing);
11745        state.id = "20260101-000000-fre1".to_owned();
11746        state.parked = true;
11747        state.save().unwrap();
11748        ask::Questions::open()
11749            .put(&mut approval_question(&state.id))
11750            .unwrap();
11751
11752        let mut t = task();
11753        t.runs.push(state.id.clone());
11754        assert_eq!(
11755            land_resume_state(&t),
11756            LandResume::StillWaiting,
11757            "nobody has answered and the timeout has not passed"
11758        );
11759    }
11760
11761    #[test]
11762    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
11763        crate::run::pin_test_home();
11764        let mut state = run_state(RunStatus::Gating);
11765        state.id = "20260101-000000-gt01".to_owned();
11766        state.parked = true;
11767        state.config.graph.answer_timeout = 60;
11768        state.github_text = Some(crate::run::GithubTextAsk {
11769            rewrite: None,
11770            fingerprint: "f".into(),
11771            title: true,
11772            body: false,
11773            categories: vec!["title-language".into()],
11774            question: None,
11775            asks: 1,
11776            resolved: false,
11777            chosen_title: None,
11778            choice: None,
11779            publication: None,
11780        });
11781        state.save().unwrap();
11782        let store = ask::Questions::open();
11783        let mut q = ask::Question::new(
11784            state.id.clone(),
11785            crate::github_text::ASK_NODE.to_owned(),
11786            crate::github_text::ASK_SEAT.to_owned(),
11787            "s".into(),
11788            String::new(),
11789            vec!["use fallback".into()],
11790        );
11791        store.put(&mut q).unwrap();
11792        let mut t = task();
11793        t.runs.push(state.id.clone());
11794        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
11795        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11796        store.put(&mut q).unwrap();
11797        assert_eq!(land_resume_state(&t), LandResume::Ready);
11798        assert!(!store.get(&q.id).unwrap().status.open());
11799        // Once decided, a parked run is an ordinary candidate again.
11800        state.github_text.as_mut().unwrap().resolved = true;
11801        state.save().unwrap();
11802        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
11803    }
11804
11805    #[test]
11806    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
11807        // `ask::ask_and_wait`'s own deadline used to retire a question
11808        // nobody answered; land's approval bypasses that wait (see
11809        // `land::approval_gate`), so this is now the only place
11810        // `graph.answer_timeout` is enforced for a land approval at all.
11811        crate::run::pin_test_home();
11812        let mut state = run_state(RunStatus::Landing);
11813        state.id = "20260101-000000-exp1".to_owned();
11814        state.parked = true;
11815        state.config.graph.answer_timeout = 60;
11816        state.save().unwrap();
11817
11818        let store = ask::Questions::open();
11819        let mut q = approval_question(&state.id);
11820        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
11821        store.put(&mut q).unwrap();
11822
11823        let mut t = task();
11824        t.runs.push(state.id.clone());
11825        assert_eq!(
11826            land_resume_state(&t),
11827            LandResume::Ready,
11828            "an expired question must not be waited on forever"
11829        );
11830
11831        let after = store.get(&q.id).unwrap();
11832        assert!(
11833            !after.status.open(),
11834            "the question is abandoned, not silently ignored"
11835        );
11836        assert!(
11837            after.resolution().is_none(),
11838            "an abandoned question is not read as a decision"
11839        );
11840    }
11841
11842    #[test]
11843    fn reclaim_settles_a_running_task_against_its_last_run() {
11844        let mut t = task();
11845        t.start("20260904-000000-4043".to_owned());
11846        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
11847        assert_eq!(
11848            t.status,
11849            TaskStatus::Held,
11850            "an unlanded Ready run settles to held awaiting landing rather than staying `running`"
11851        );
11852        assert!(t.has_awaiting_landing_cause());
11853        let mut merged = task();
11854        merged.start("20260904-000000-4044".to_owned());
11855        reclaim(&mut merged, Some(run_state(RunStatus::Merged)), 2, "en");
11856        assert_eq!(
11857            merged.status,
11858            TaskStatus::Done,
11859            "a merged run closes the task cleanly"
11860        );
11861    }
11862
11863    #[test]
11864    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
11865        let dir = tempfile::tempdir().unwrap();
11866        let queue = Queue::at(dir.path().join("queue"));
11867        let mut task = task();
11868        let mut run = run_state(RunStatus::Blocked);
11869        run.reserve_under(dir.path()).unwrap();
11870        run.driver_exited = true;
11871        run.save_under(dir.path()).unwrap();
11872        queue.put(&mut task).unwrap();
11873        let stale = task.clone();
11874        task.resume_override = Some(crate::queue::OperatorResume {
11875            question_id: "pending-resume".into(),
11876            at: Timestamp::now(),
11877            conductor_rehold: None,
11878            forced: true,
11879            pinned_run: Some(run.id.clone()),
11880        });
11881        task.start(run.id.clone());
11882        queue.put(&mut task).unwrap();
11883        // Discard every in-memory handoff, as a worker death before execute does.
11884        let mut recovered = queue.get(&task.id).unwrap();
11885        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
11886        reclaim(&mut recovered, Some(disk), 2, "en");
11887        queue.put(&mut recovered).unwrap();
11888        assert!(recovered.resume_override.is_none());
11889        assert_eq!(
11890            recovered.dispatched_resumes.get("pending-resume"),
11891            Some(&run.id)
11892        );
11893        let mut stale = stale;
11894        queue.put(&mut stale).unwrap();
11895        assert_eq!(
11896            stale.dispatched_resumes, recovered.dispatched_resumes,
11897            "a stale task writer cannot erase dispatch ownership"
11898        );
11899        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
11900        assert!(resumed.decision_starts.is_empty());
11901        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
11902        assert!(
11903            resumed.decision_starts.is_empty(),
11904            "handoff is not execution proof"
11905        );
11906        resumed.begin_pass();
11907        resumed.save_under(dir.path()).unwrap();
11908        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
11909        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
11910        disk.carry_dispatched_resumes(&recovered);
11911        disk.begin_pass();
11912        assert_eq!(
11913            disk.decision_starts.get("pending-resume"),
11914            Some(&0),
11915            "later execution must preserve the original pass receipt"
11916        );
11917    }
11918
11919    #[test]
11920    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
11921        let mut t = task();
11922        t.start("20260904-000000-4043".to_owned());
11923        t.last_error = Some("earlier trouble".to_owned());
11924        let mut state = run_state(RunStatus::Judging);
11925        state.parked = true;
11926        reclaim(&mut t, Some(state), 1, "en");
11927        assert_eq!(t.status, TaskStatus::Parked);
11928        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
11929        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11930        assert!(t.park_reason.is_some());
11931        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
11932        assert!(!t.fresh_start);
11933        assert!(t.status.runnable());
11934    }
11935
11936    #[test]
11937    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
11938        let mut t = task();
11939        t.start("20260904-000000-4043".to_owned());
11940        t.last_error = Some("earlier trouble".to_owned());
11941        settle(
11942            &mut t,
11943            Verdict {
11944                status: RunStatus::Judging,
11945                left_pr: false,
11946                quota_hit: false,
11947                parked: true,
11948                no_viable_candidates: false,
11949            },
11950            "parked after `judging`",
11951            1,
11952        );
11953        assert_eq!(t.status, TaskStatus::Parked);
11954        assert_eq!(t.attempts, 0);
11955        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
11956        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
11957        assert_eq!(t.schema, crate::queue::SCHEMA);
11958        assert!(
11959            crate::notices::task_held(&t).is_none(),
11960            "a park is not news"
11961        );
11962        t.start("20260904-000000-4043".to_owned());
11963        assert_eq!(t.park_reason, None);
11964    }
11965
11966    #[test]
11967    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
11968        // A blocked run with attempts left goes back to `Failed`, exactly as
11969        // it would from `attempt` itself - `reclaim` must not invent a second
11970        // policy for a task a daemon merely stopped without reporting.
11971        let mut t = task();
11972        t.start("20260904-000000-4043".to_owned());
11973        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
11974        assert_eq!(t.status, TaskStatus::Failed);
11975        assert!(t.status.runnable());
11976    }
11977
11978    #[test]
11979    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
11980        let mut t = task();
11981        t.start("20260904-000000-4043".to_owned());
11982        assert_eq!(t.attempts, 1);
11983        let mut run = run_state(RunStatus::Implementing);
11984        run.id = "20260904-000000-4043".to_owned();
11985        run.begin_pass();
11986        let cause = crate::run::ParkCause::Upgrade {
11987            from: "0.121.0".to_owned(),
11988            to: Some("0.121.1".to_owned()),
11989        };
11990        run.end_pass_parked(cause.clone());
11991        run.parked = true;
11992        let verdict = Verdict {
11993            status: run.status,
11994            left_pr: false,
11995            quota_hit: false,
11996            parked: true,
11997            no_viable_candidates: false,
11998        };
11999        // A crash after the checkpoint but before queue settlement must
12000        // recover exactly the same scheduling evidence and refund.
12001        let mut orphan = t.clone();
12002        reclaim(&mut orphan, Some(run.clone()), 2, "en");
12003        assert_eq!(orphan.status, TaskStatus::Parked);
12004        assert_eq!(orphan.attempts, 0);
12005        assert_eq!(
12006            orphan.upgrade_resume_key(),
12007            Some((run.passes[0].started_at, orphan.id.as_str()))
12008        );
12009        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
12010        assert_eq!(t.attempts, 0);
12011        assert_eq!(t.passes.len(), 1);
12012        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
12013        assert_eq!(t.passes[0].parked, Some(cause));
12014        assert_eq!(t.passes[0].pass_index, 0);
12015        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
12016        assert!(t.upgrade_resume_key().is_some());
12017
12018        // A resumed pass that then fails spends its attempt, and the earlier
12019        // pass's entry is untouched.
12020        t.start("20260904-000000-4043".to_owned());
12021        run.begin_pass();
12022        run.status = RunStatus::Failed;
12023        let verdict = Verdict {
12024            status: RunStatus::Failed,
12025            left_pr: false,
12026            quota_hit: false,
12027            parked: false,
12028            no_viable_candidates: false,
12029        };
12030        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
12031        assert_eq!(t.passes.len(), 2);
12032        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
12033        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
12034        assert_eq!(t.passes[1].pass_index, 1);
12035        assert_eq!(t.attempts, 1);
12036    }
12037
12038    #[test]
12039    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
12040        let mut t = task();
12041        t.start("20260904-000000-4043".to_owned());
12042        reclaim(&mut t, None, 2, "en");
12043        assert_eq!(t.status, TaskStatus::Held);
12044        assert!(
12045            t.last_error
12046                .as_deref()
12047                .is_some_and(|e| e.contains("running")),
12048            "the operator needs to know why this task was held"
12049        );
12050    }
12051
12052    #[test]
12053    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
12054        let dir = tempfile::tempdir().unwrap();
12055        let queue = Queue::at(dir.path().to_path_buf());
12056        let mut task = task();
12057        let run = "20261124-000000-dead";
12058        task.link_run(run);
12059        task.attempts = 2;
12060        task.status = TaskStatus::Running;
12061        task.sync_only = Some(crate::base_sync_only::Request {
12062            run: run.into(),
12063            at: Timestamp::now(),
12064        });
12065        queue.put(&mut task).unwrap();
12066        assert_eq!(
12067            reclaim_orphaned_running(&queue, 3, &Default::default()),
12068            vec![task.id.clone()]
12069        );
12070        let saved = queue.get(&task.id).unwrap();
12071        assert_eq!(saved.status, TaskStatus::Held);
12072        assert_eq!(saved.attempts, 2);
12073        assert_eq!(saved.execution_runs(), [run]);
12074        assert!(
12075            saved
12076                .last_error
12077                .unwrap()
12078                .contains("verification was not allowed")
12079        );
12080        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
12081    }
12082
12083    #[test]
12084    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
12085        use crate::base_sync_only::{Outcome, Pass, Request};
12086
12087        let mut state = run_state(RunStatus::Blocked);
12088        let mut task = task();
12089        let request = Request {
12090            run: state.id.clone(),
12091            at: Timestamp::now(),
12092        };
12093        task.start(state.id.clone());
12094        task.sync_only = Some(request.clone());
12095        // Dedicated dispatch saves Running with the pre-pass attempt count.
12096        task.attempts = 2;
12097        let mut pass = Pass::new(request, &state);
12098        pass.result = Outcome::AlreadyCurrent;
12099        state.sync_only_passes.push(pass);
12100        state.begin_pass();
12101
12102        reclaim(&mut task, Some(state), 3, "en");
12103
12104        assert_eq!(task.status, TaskStatus::Held);
12105        assert_eq!(task.attempts, 2);
12106        assert!(task.sync_only.is_none());
12107        let detail = task.hold_reason.unwrap();
12108        assert!(detail.contains("HEAD already contains the base"));
12109        assert!(detail.contains("verification was not allowed"));
12110    }
12111
12112    #[test]
12113    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
12114        let dir = tempfile::tempdir().unwrap();
12115        let queue = Queue::at(dir.path().to_path_buf());
12116
12117        // No run recorded, so this never has to touch `RunState::load`.
12118        let mut orphaned = task();
12119        orphaned.id = "20260904-000000-orph".to_owned();
12120        orphaned.status = TaskStatus::Running;
12121        orphaned.attempts = 1;
12122        queue.put(&mut orphaned).unwrap();
12123
12124        let mut alive = task();
12125        alive.id = "20260904-000000-live".to_owned();
12126        alive.status = TaskStatus::Running;
12127        alive.attempts = 1;
12128        queue.put(&mut alive).unwrap();
12129        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
12130
12131        let mut queued = task();
12132        queued.id = "20260904-000000-wait".to_owned();
12133        queue.put(&mut queued).unwrap();
12134
12135        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
12136        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
12137
12138        assert_eq!(
12139            queue.get(&orphaned.id).unwrap().status,
12140            TaskStatus::Held,
12141            "nothing was driving it and there was no run to recover"
12142        );
12143        assert_eq!(
12144            queue.get(&alive.id).unwrap().status,
12145            TaskStatus::Running,
12146            "a live claim must protect the task it belongs to"
12147        );
12148        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
12149    }
12150
12151    /// Read a run.json back from an explicit `home`, the same way
12152    /// `reclaim_abandoned_runs` itself does - never through the
12153    /// process-global `RunState::load`, which this test's own `home` (an
12154    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
12155    /// use at all.
12156    fn read_run_under(home: &Path, id: &str) -> RunState {
12157        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
12158        serde_json::from_str(&body).unwrap()
12159    }
12160
12161    #[test]
12162    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
12163        let dir = tempfile::tempdir().unwrap();
12164        let home = dir.path().to_path_buf();
12165        let now = Timestamp::now();
12166        let overrun_seat = || crate::run::ActiveSeat {
12167            node: "implement".to_owned(),
12168            started_at: now - jiff::SignedDuration::new(21_000, 0),
12169            timeout_secs: 3_600,
12170            attempt: 0,
12171            task: None,
12172            command: None,
12173            index: None,
12174            total: None,
12175        };
12176
12177        let mut dead = run_state(RunStatus::Implementing);
12178        dead.id = "20260101-000000-dead".to_owned();
12179        dead.active.insert("impl-A".to_owned(), overrun_seat());
12180        // A `driver_pid` the injected query below confirms gone outright —
12181        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
12182        dead.driver_pid = Some(4242);
12183        dead.save_under(&home).unwrap();
12184
12185        // Same shape, but a live daemon's heartbeat names it: must be left
12186        // exactly alone, however far past its own timeout the seat sits.
12187        let mut alive = run_state(RunStatus::Implementing);
12188        alive.id = "20260101-000000-aliv".to_owned();
12189        alive.active.insert("impl-A".to_owned(), overrun_seat());
12190        alive.save_under(&home).unwrap();
12191        let mut status = Status::new();
12192        status.current = vec![Current {
12193            worker: None,
12194            task: "20260101-000000-task".to_owned(),
12195            run: alive.id.clone(),
12196        }];
12197        write_status_to(&home.join("daemon.json"), &status).unwrap();
12198
12199        // The abandoned seat left an open question behind: nobody is left to
12200        // read an answer once the run is failed, and this must not wait for
12201        // some later daemon startup's own sweep to notice that.
12202        let questions = Questions::at(home.join("questions"));
12203        let mut q = ask::Question::new(
12204            dead.id.clone(),
12205            "implement".to_owned(),
12206            "impl-A".to_owned(),
12207            "Which storage backend?".to_owned(),
12208            String::new(),
12209            vec!["SQLite".to_owned(), "Redis".to_owned()],
12210        );
12211        questions.put(&mut q).unwrap();
12212
12213        let abandoned = reclaim_abandoned_runs_with(
12214            &home,
12215            now,
12216            |pid| if pid == 4242 { Some(false) } else { None },
12217            |_| panic!("a query answering Dead outright needs no identity corroboration"),
12218        );
12219        assert_eq!(abandoned, vec![dead.id.clone()]);
12220
12221        let reloaded = read_run_under(&home, &dead.id);
12222        assert_eq!(reloaded.status, RunStatus::Failed);
12223        assert!(reloaded.active.is_empty());
12224        assert!(
12225            !questions.get(&q.id).unwrap().status.open(),
12226            "the failed run's own open question must be settled in the same pass"
12227        );
12228
12229        let still_alive = read_run_under(&home, &alive.id);
12230        assert_eq!(
12231            still_alive.status,
12232            RunStatus::Implementing,
12233            "a live daemon's claim protects it"
12234        );
12235        assert!(!still_alive.active.is_empty());
12236    }
12237
12238    /// The exact shape a review round flagged as broken: `magi serve` running
12239    /// in this same `home` scans *every* run on disk, including a manual
12240    /// `magi review` / `magi run` this daemon never started and that
12241    /// therefore claims no heartbeat of its own. Before this scan asked
12242    /// `liveness` rather than just `is_working_on`, a manual run whose active
12243    /// seat merely ran a little past its own timeout — the CLI finishing up,
12244    /// its result still being collected — got wiped and failed by a daemon
12245    /// that had nothing to do with it, out from under a process that was
12246    /// still very much running.
12247    #[test]
12248    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
12249        let dir = tempfile::tempdir().unwrap();
12250        let home = dir.path().to_path_buf();
12251        let now = Timestamp::now();
12252
12253        let mut manual = run_state(RunStatus::Reviewing);
12254        manual.id = "20260101-000000-manl".to_owned();
12255        manual.active.insert(
12256            "review-1".to_owned(),
12257            crate::run::ActiveSeat {
12258                node: "review".to_owned(),
12259                started_at: now - jiff::SignedDuration::new(21_000, 0),
12260                timeout_secs: 3_600,
12261                attempt: 0,
12262                task: None,
12263                command: None,
12264                index: None,
12265                total: None,
12266            },
12267        );
12268        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
12269        // but a real, still-running process: `liveness` must corroborate this
12270        // as `Live`, not read the missing daemon claim as death.
12271        manual.driver_pid = Some(4242);
12272        manual.driver_started_at = Some("1790000000".to_owned());
12273        manual.save_under(&home).unwrap();
12274
12275        let abandoned = reclaim_abandoned_runs_with(
12276            &home,
12277            now,
12278            |pid| if pid == 4242 { Some(true) } else { None },
12279            |pid| {
12280                if pid == 4242 {
12281                    Some("1790000000".to_owned())
12282                } else {
12283                    None
12284                }
12285            },
12286        );
12287        assert!(
12288            abandoned.is_empty(),
12289            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
12290        );
12291
12292        let reloaded = read_run_under(&home, &manual.id);
12293        assert_eq!(reloaded.status, RunStatus::Reviewing);
12294        assert!(!reloaded.active.is_empty());
12295    }
12296
12297    #[test]
12298    fn an_already_claimed_task_is_skipped_rather_than_failed() {
12299        let dir = tempfile::tempdir().unwrap();
12300        let queue = Queue::at(dir.path().to_path_buf());
12301        let mut only = task();
12302        queue.put(&mut only).unwrap();
12303
12304        let _elsewhere = queue.claim(&only.id).unwrap();
12305        let candidates = runnable(&queue);
12306        assert_eq!(candidates.len(), 1, "the task is still runnable");
12307        assert!(
12308            queue.claim(&candidates[0].id).is_err(),
12309            "the loop cannot take a claim somebody else holds"
12310        );
12311
12312        let after = queue.get(&only.id).unwrap();
12313        assert_eq!(after.status, TaskStatus::Queued);
12314        assert_eq!(
12315            after.attempts, 0,
12316            "losing the race is not an attempt at the task"
12317        );
12318        assert_eq!(after.last_error, None);
12319    }
12320
12321    #[test]
12322    fn the_status_file_round_trips_and_its_heartbeat_advances() {
12323        let dir = tempfile::tempdir().unwrap();
12324        let path = dir.path().join("daemon.json");
12325
12326        let mut status = Status::new();
12327        status.idle = false;
12328        status.completed = 7;
12329        status.current = vec![Current {
12330            worker: None,
12331            task: "20260902-000000-t111".to_owned(),
12332            run: "20260902-000001-r111".to_owned(),
12333        }];
12334        write_status_to(&path, &status).unwrap();
12335        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12336        assert_eq!(first.schema, SCHEMA);
12337        assert_eq!(first.pid, std::process::id());
12338        assert!(!first.idle);
12339        assert_eq!(first.completed, 7);
12340        assert_eq!(first.current, status.current);
12341        assert!(
12342            !path.with_extension("json.tmp").exists(),
12343            "the temp file is renamed, not left behind"
12344        );
12345
12346        std::thread::sleep(Duration::from_millis(5));
12347        status.updated_at = Timestamp::now();
12348        status.polls = 3;
12349        write_status_to(&path, &status).unwrap();
12350        let second: Status =
12351            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
12352        assert!(
12353            second.updated_at > first.updated_at,
12354            "a reader can only detect staleness if the heartbeat moves"
12355        );
12356        assert_eq!(
12357            second.started_at, first.started_at,
12358            "the start time is not a heartbeat"
12359        );
12360        assert_eq!(second.polls, 3);
12361    }
12362
12363    #[test]
12364    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
12365        let dir = tempfile::tempdir().unwrap();
12366
12367        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
12368
12369        let mut status = Status::new();
12370        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
12371        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12372        let stale = read_status(dir.path()).unwrap();
12373        assert!(
12374            !stale.running(Timestamp::now()),
12375            "a minute without a heartbeat is a dead daemon, not a busy one"
12376        );
12377        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
12378
12379        status.updated_at = Timestamp::now();
12380        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12381        let fresh = read_status(dir.path()).unwrap();
12382        assert!(fresh.running(Timestamp::now()));
12383    }
12384
12385    #[test]
12386    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
12387        let dir = tempfile::tempdir().unwrap();
12388        let now = Timestamp::now();
12389        let mine = "20260903-080619-01c2";
12390
12391        assert!(
12392            !is_working_on(dir.path(), mine, now),
12393            "no status file means nobody is working on anything"
12394        );
12395
12396        let mut status = Status::new();
12397        status.current = vec![Current {
12398            worker: None,
12399            task: "20260903-080340-0167".to_owned(),
12400            run: mine.to_owned(),
12401        }];
12402        status.updated_at = now;
12403        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12404        assert!(is_working_on(dir.path(), mine, now));
12405        assert!(
12406            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
12407            "a daemon busy with one run is not working on another"
12408        );
12409
12410        // A killed daemon stops writing heartbeats but leaves the file behind
12411        // naming the run it died in. That run must not be undeletable forever.
12412        status.updated_at = now - jiff::SignedDuration::from_secs(600);
12413        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12414        assert!(
12415            !is_working_on(dir.path(), mine, now),
12416            "a stale heartbeat is a dead daemon, so its run is a leftover"
12417        );
12418    }
12419
12420    #[test]
12421    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
12422        let dir = tempfile::tempdir().unwrap();
12423        let now = Timestamp::now();
12424
12425        assert!(
12426            !is_working_on_short(dir.path(), "01c2", now),
12427            "no status file means nobody is working on anything"
12428        );
12429
12430        let mut status = Status::new();
12431        status.current = vec![Current {
12432            worker: None,
12433            task: "20260903-080340-0167".to_owned(),
12434            run: "20260903-080619-01c2".to_owned(),
12435        }];
12436        status.updated_at = now;
12437        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12438        assert!(
12439            is_working_on_short(dir.path(), "01c2", now),
12440            "the run's short id is the last block of its full id"
12441        );
12442        assert!(
12443            !is_working_on_short(dir.path(), "3cbf", now),
12444            "a daemon busy with one worktree bay is not working on another"
12445        );
12446    }
12447
12448    #[test]
12449    fn a_newer_status_file_still_yields_a_reading() {
12450        let dir = tempfile::tempdir().unwrap();
12451        // A field this build has never heard of must not turn the reading into
12452        // nothing at all; that is the whole reason the reader is permissive.
12453        std::fs::write(
12454            dir.path().join("daemon.json"),
12455            serde_json::json!({
12456                "schema": 2,
12457                "updated_at": Timestamp::now().to_string(),
12458                "idle": true,
12459                "surprise": { "nested": [1, 2, 3] },
12460            })
12461            .to_string(),
12462        )
12463        .unwrap();
12464
12465        let reading = read_status(dir.path()).expect("a forward-compatible read");
12466        assert!(reading.running(Timestamp::now()));
12467        assert!(reading.idle);
12468        assert!(reading.current.is_empty());
12469    }
12470
12471    #[test]
12472    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
12473        // A daemon started before `current` became a list keeps writing this
12474        // shape on every heartbeat until it is restarted. A rolling upgrade
12475        // - a newer `magi web` or `magi doctor` reading an older `magi
12476        // serve`'s heartbeat - must still see the run it is on, not "no
12477        // daemon" from a type mismatch failing the whole struct.
12478        let dir = tempfile::tempdir().unwrap();
12479        std::fs::write(
12480            dir.path().join("daemon.json"),
12481            serde_json::json!({
12482                "schema": 1,
12483                "pid": 4242,
12484                "updated_at": Timestamp::now().to_string(),
12485                "idle": false,
12486                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
12487                "completed": 3,
12488                "polls": 9,
12489            })
12490            .to_string(),
12491        )
12492        .unwrap();
12493
12494        let reading = read_status(dir.path()).expect("an older shape must still parse");
12495        assert!(reading.running(Timestamp::now()));
12496        assert_eq!(
12497            reading.current,
12498            vec![Current {
12499                worker: None,
12500                task: "20260902-140501-aaaa".to_owned(),
12501                run: "20260902-140502-bbbb".to_owned(),
12502            }]
12503        );
12504    }
12505
12506    #[test]
12507    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
12508        let dir = tempfile::tempdir().unwrap();
12509        std::fs::write(
12510            dir.path().join("daemon.json"),
12511            serde_json::json!({
12512                "schema": 1,
12513                "updated_at": Timestamp::now().to_string(),
12514                "idle": true,
12515                "current": null,
12516            })
12517            .to_string(),
12518        )
12519        .unwrap();
12520        let with_null = read_status(dir.path()).expect("null must still parse");
12521        assert!(with_null.current.is_empty());
12522
12523        std::fs::write(
12524            dir.path().join("daemon.json"),
12525            serde_json::json!({
12526                "schema": 1,
12527                "updated_at": Timestamp::now().to_string(),
12528                "idle": true,
12529            })
12530            .to_string(),
12531        )
12532        .unwrap();
12533        let absent = read_status(dir.path()).expect("a missing field must still parse");
12534        assert!(absent.current.is_empty());
12535    }
12536
12537    #[test]
12538    fn a_task_without_a_repository_runs_in_the_daemons_default() {
12539        let fallback = Path::new("/default");
12540        let mut blank = task();
12541        blank.repo = PathBuf::new();
12542        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
12543        let mut dot = task();
12544        dot.repo = PathBuf::from(".");
12545        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
12546        assert_eq!(
12547            repo_for(&task(), fallback),
12548            PathBuf::from("/repo"),
12549            "a task that names a repository keeps it"
12550        );
12551    }
12552
12553    #[test]
12554    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
12555        let dir = tempfile::tempdir().unwrap();
12556        let repo = dir.path();
12557        let path = repo.join("explicit.toml");
12558        std::fs::write(
12559            &path,
12560            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
12561        )
12562        .unwrap();
12563        let opts = Opts {
12564            config: Some(path),
12565            ..Opts::default()
12566        };
12567        let queue = Queue::at(repo.join("queue"));
12568        let mut new = task();
12569        queue.put(&mut new).unwrap();
12570        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
12571        assert_eq!(
12572            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
12573            BuildCache::Isolated
12574        );
12575
12576        let mut old = task();
12577        old.schema = 22;
12578        queue.put(&mut old).unwrap();
12579        let mut old = queue.get(&old.id).unwrap();
12580        let config = resolved(&old);
12581        assert_eq!(config.verify.build_cache, BuildCache::Shared);
12582        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
12583        old.hold_manual(Some("wait".into()));
12584        queue.put(&mut old).unwrap();
12585
12586        let mut saved = queue.get(&old.id).unwrap();
12587        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
12588        saved
12589            .overrides
12590            .as_mut()
12591            .unwrap()
12592            .merge_over(&crate::queue::RunOverrides {
12593                build_cache: Some(BuildCache::Isolated),
12594                ..Default::default()
12595            });
12596        queue.put(&mut saved).unwrap();
12597        assert_eq!(
12598            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
12599            BuildCache::Isolated
12600        );
12601    }
12602
12603    #[test]
12604    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
12605        let dir = tempfile::tempdir().unwrap();
12606        let path = dir.path().join("explicit.toml");
12607        let write = |verify: &str| {
12608            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
12609        };
12610        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
12611        let opts = Opts {
12612            config: Some(path.clone()),
12613            ..Opts::default()
12614        };
12615        let mut task = task();
12616        task.set_urgent(true).unwrap();
12617        let resolved = |task: &Task| {
12618            prepare_for(dir.path(), &opts, task)
12619                .unwrap()
12620                .verify
12621                .build_cache
12622        };
12623        assert_eq!(resolved(&task), BuildCache::Isolated);
12624        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
12625        assert_eq!(resolved(&task), BuildCache::Shared);
12626        task.change_build_cache(None).unwrap();
12627        assert_eq!(resolved(&task), BuildCache::Isolated);
12628        task.set_urgent(false).unwrap();
12629        assert_eq!(resolved(&task), BuildCache::Shared);
12630
12631        // Urgent work must never be the one stopped by isolation: with no
12632        // shared cache to wait behind, or with a verification command isolated
12633        // mode cannot run, an urgent task keeps the configured mode.
12634        task.set_urgent(true).unwrap();
12635        write("e2e = [\"npm test\"]\n");
12636        assert_eq!(resolved(&task), BuildCache::Shared);
12637        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
12638        assert_eq!(resolved(&task), BuildCache::Shared);
12639        // An explicit choice stays strict and is applied as asked.
12640        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
12641        assert_eq!(resolved(&task), BuildCache::Isolated);
12642    }
12643
12644    #[test]
12645    fn task_implementers_edit_inherits_daemon_config_and_merge() {
12646        let dir = tempfile::tempdir().unwrap();
12647        let path = dir.path().join("explicit.toml");
12648        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
12649        let opts = Opts {
12650            config: Some(path),
12651            merge: Some("none".into()),
12652            ..Default::default()
12653        };
12654        let mut t = task();
12655        t.set_implementers(
12656            2,
12657            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12658                .unwrap(),
12659        )
12660        .unwrap();
12661        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12662        assert_eq!(cfg.graph.implementers, 2);
12663        assert_eq!(cfg.graph.judges, 1);
12664        assert_eq!(cfg.merge.mode, MergeMode::None);
12665        t.set_implementers(1, &cfg).unwrap();
12666        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
12667        apply_task_implementers(&mut cfg, &t);
12668        assert_eq!(cfg.graph.implementers, 1);
12669        assert_eq!(cfg.graph.judges, 1);
12670        assert_eq!(cfg.merge.mode, MergeMode::None);
12671    }
12672
12673    #[test]
12674    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
12675        let dir = tempfile::tempdir().unwrap();
12676        let repo = dir.path().join("repo");
12677        std::fs::create_dir(&repo).unwrap();
12678        std::fs::write(
12679            repo.join("magi.toml"),
12680            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
12681        )
12682        .unwrap();
12683        let daemon_config = dir.path().join("daemon.toml");
12684        std::fs::write(
12685            &daemon_config,
12686            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
12687        )
12688        .unwrap();
12689        let opts = Opts {
12690            config: Some(daemon_config),
12691            merge: Some("pr".into()),
12692            ..Default::default()
12693        };
12694        let q = Queue::at(dir.path().join("queue"));
12695        let validation: Config =
12696            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12697                .unwrap();
12698        // No provenance field on legacy direct tasks: both shapes stay isolated.
12699        for record in ["{}", r#"{"candidates":2}"#] {
12700            let overrides = serde_json::from_str(record).unwrap();
12701            let filing = crate::direct::Filing {
12702                instruction: "work".into(),
12703                title: "direct".into(),
12704                repo: repo.clone(),
12705                source: crate::queue::Source::Human,
12706                issue: None,
12707                solo: false,
12708                overrides,
12709                review_of: None,
12710                sources: Default::default(),
12711            };
12712            let filed =
12713                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
12714            let crate::direct::Filed::Standalone {
12715                mut task,
12716                claim: _claim,
12717            } = filed
12718            else {
12719                panic!("local filing")
12720            };
12721            let before = prepare_for(&repo, &opts, &task).unwrap();
12722            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
12723            assert_eq!(
12724                before.merge.mode,
12725                MergeMode::None,
12726                "daemon --merge must not leak"
12727            );
12728            for n in [2, 1, 2] {
12729                task.set_implementers(n, &validation).unwrap();
12730                q.put(&mut task).unwrap();
12731                task = q.get(&task.id).unwrap();
12732                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
12733                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
12734                apply_task_implementers(&mut cfg, &task);
12735                assert_eq!(cfg.graph.implementers, usize::from(n));
12736                assert_eq!(cfg.graph.judges, 2);
12737                assert_eq!(cfg.merge.mode, MergeMode::None);
12738            }
12739        }
12740    }
12741
12742    #[test]
12743    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
12744        let cfg: Config =
12745            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12746                .unwrap();
12747        let mut t = task();
12748        t.review_of = Some("review-target".into());
12749        t.hold_manual(Some("retry".into()));
12750        let mut previous = RunState::new(
12751            PathBuf::from("/repo"),
12752            "main".into(),
12753            "abc1234".into(),
12754            "review".into(),
12755            cfg.clone(),
12756        );
12757        previous.config.graph.implementers = 2;
12758        for count in [1, 3] {
12759            t.set_implementers(count, &cfg).unwrap();
12760            t.release();
12761            assert_eq!(t.review_of.as_deref(), Some("review-target"));
12762            for proposed in [
12763                Starter::Resume(previous.id.clone()),
12764                Starter::Review("recovery-target".into()),
12765            ] {
12766                assert_eq!(
12767                    starter_with_implementers(&t, Some(&previous), proposed),
12768                    Starter::Review("review-target".into())
12769                );
12770            }
12771            let mut configured = cfg.clone();
12772            apply_task_implementers(&mut configured, &t);
12773            assert_eq!(configured.graph.implementers, usize::from(count));
12774            assert_eq!(previous.config.graph.implementers, 2);
12775        }
12776    }
12777
12778    #[test]
12779    fn task_implementers_dispatch_and_resume_agree() {
12780        let mut t = task();
12781        let cfg: crate::config::Config =
12782            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
12783                .unwrap();
12784        let mut run = RunState::new(
12785            PathBuf::from("/repo"),
12786            "main".into(),
12787            "abc1234".into(),
12788            "work".into(),
12789            cfg.clone(),
12790        );
12791        run.config.graph.implementers = 2;
12792        for n in [2, 1, 3, 2] {
12793            t.set_implementers(n, &cfg).unwrap();
12794            let mut dispatched = cfg.clone();
12795            apply_task_implementers(&mut dispatched, &t);
12796            assert_eq!(dispatched.graph.implementers, usize::from(n));
12797            assert_eq!(implementers_match(&t, &run), n == 2);
12798            for proposed in [
12799                Starter::Resume(run.id.clone()),
12800                Starter::Review("old-branch".into()),
12801            ] {
12802                let expected = if n == 2 {
12803                    proposed.clone()
12804                } else {
12805                    Starter::Start
12806                };
12807                assert_eq!(
12808                    starter_with_implementers(&t, Some(&run), proposed),
12809                    expected
12810                );
12811            }
12812            assert_eq!(
12813                run.config.graph.implementers, 2,
12814                "history must not be rewritten"
12815            );
12816        }
12817        t.solo = false;
12818        t.overrides = None;
12819        assert!(implementers_match(&t, &run));
12820    }
12821
12822    #[test]
12823    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
12824        // Three seats said out loud. What `solo` promises is one candidate
12825        // *whatever the config asks for*, so the contrast has to be a number
12826        // this test owns - it used to be `Config::default()`'s, which became
12827        // 1 when one implementation became the default and left the two
12828        // halves of this test asserting the same thing.
12829        let mut solo_cfg = Config::default();
12830        solo_cfg.graph.implementers = 3;
12831        let mut solo_task = task();
12832        solo_task.solo = true;
12833        apply_task_implementers(&mut solo_cfg, &solo_task);
12834        assert_eq!(solo_cfg.graph.implementers, 1);
12835
12836        let mut plain_cfg = Config::default();
12837        plain_cfg.graph.implementers = 3;
12838        let plain_task = task();
12839        assert!(!plain_task.solo);
12840        apply_task_implementers(&mut plain_cfg, &plain_task);
12841        assert_eq!(
12842            plain_cfg.graph.implementers, 3,
12843            "a task that did not ask to run alone keeps the config's candidates"
12844        );
12845    }
12846
12847    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
12848        QuotaLoss {
12849            cause: crate::agent::QuotaCause::UsageLimit,
12850            agent: String::new(),
12851            seat: seat.into(),
12852            node: "judge".into(),
12853            at: at.parse().unwrap(),
12854            reset: reset.map(str::to_string),
12855        }
12856    }
12857
12858    #[test]
12859    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
12860        let now = Timestamp::now();
12861        for reset in [None, Some("in 1h")] {
12862            let auth = crate::agent::Quota {
12863                cause: crate::agent::QuotaCause::Authentication,
12864                agent: "alpha".into(),
12865                reset: reset.map(str::to_owned),
12866            };
12867            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
12868            assert_eq!(cooldown_until(&[loss], now), None);
12869        }
12870    }
12871
12872    #[test]
12873    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
12874        let old: Vec<QuotaLoss> = (1..=4)
12875            .map(|i| {
12876                loss(
12877                    &format!("judge-{i}"),
12878                    "2026-09-23T05:23:00Z",
12879                    Some("2:40pm (Asia/Tokyo)"),
12880                )
12881            })
12882            .collect();
12883        let fresh = losses_this_attempt(&old, &old);
12884        assert!(fresh.is_empty());
12885        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
12886        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
12887    }
12888
12889    #[test]
12890    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
12891        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
12892        let now = Timestamp::now();
12893        let mut after = old.clone();
12894        after.push(loss("judge-2", &now.to_string(), None));
12895        let fresh = losses_this_attempt(&old, &after);
12896        assert_eq!(fresh, vec![after[1].clone()]);
12897        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
12898        assert_eq!(
12899            until,
12900            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
12901        );
12902    }
12903
12904    #[test]
12905    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
12906        // `recover_stall` removes judge-1's loss and the retry then hits quota
12907        // again: the vector is the same length, so an index diff sees nothing.
12908        let before = vec![
12909            loss("judge-1", "2026-09-23T05:23:00Z", None),
12910            loss("judge-2", "2026-09-23T05:24:00Z", None),
12911        ];
12912        let after = vec![
12913            loss("judge-2", "2026-09-23T05:24:00Z", None),
12914            loss("judge-1", "2026-09-24T01:00:00Z", None),
12915        ];
12916        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
12917    }
12918
12919    #[test]
12920    fn merge_overrides_are_parsed_or_refused() {
12921        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
12922        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
12923        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
12924        assert!(merge_mode("squash").is_err());
12925    }
12926
12927    #[test]
12928    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
12929        let now = Timestamp::now();
12930        let fallback = Duration::from_secs(300);
12931        let cap = Duration::from_secs(1800);
12932
12933        // No reset hint at all: the fallback.
12934        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
12935
12936        // A reset ten minutes out, well inside the cap: waited for exactly.
12937        let soon = now + jiff::SignedDuration::from_secs(600);
12938        assert_eq!(
12939            quota_wait(Some(soon), now, fallback, cap),
12940            Duration::from_secs(600)
12941        );
12942
12943        // A reset already in the past is not trusted: the fallback, not a
12944        // zero or negative wait that would spin the loop right back around.
12945        let past = now - jiff::SignedDuration::from_secs(60);
12946        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
12947
12948        // A reset further out than the cap is trusted for direction but not
12949        // for magnitude: a parsing slip must not sleep the loop for a day.
12950        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
12951        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
12952    }
12953
12954    #[test]
12955    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
12956        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12957
12958        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
12959        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
12960
12961        // Same clock reading, but it has already gone by today: read as
12962        // tomorrow's, since the CLI would not still be reporting a limit past
12963        // its own stated reset.
12964        let already_past =
12965            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
12966        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
12967
12968        assert!(
12969            parse_reset_hint("session limit reached", now, now).is_none(),
12970            "free text with no recognised shape is not guessed at"
12971        );
12972        assert!(
12973            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
12974            "an unresolvable zone name is not guessed at either"
12975        );
12976    }
12977
12978    #[test]
12979    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
12980        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
12981
12982        let at = parse_reset_hint(
12983            "You've hit your usage limit. Visit \
12984             https://chatgpt.com/codex/settings/usage to purchase more \
12985             credits or try again at Sep 19th, 2026 5:10 PM.",
12986            now,
12987            now,
12988        )
12989        .expect("the codex reset wording is a recognised shape");
12990        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
12991
12992        // The month is explicit, so a date already earlier in the same
12993        // sentence-implied year than `now` is trusted as written rather than
12994        // rolled forward a year the way the bracketed shape rolls a
12995        // same-day clock reading to tomorrow.
12996        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
12997            .expect("an explicit year needs no rollover");
12998        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
12999
13000        assert!(
13001            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
13002            "a two-digit year is not the documented shape and is not guessed at"
13003        );
13004        assert!(
13005            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
13006            "a four-letter month name is not the documented three-letter abbreviation"
13007        );
13008        assert!(
13009            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
13010            "an explicit zone on the dated shape is a format nobody has \
13011             documented, and is refused rather than guessed at as UTC"
13012        );
13013    }
13014
13015    #[test]
13016    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
13017        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
13018        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
13019
13020        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
13021        assert_eq!(at.as_second() - recorded.as_second(), 3769);
13022
13023        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
13024        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
13025
13026        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
13027            assert!(
13028                parse_reset_hint(bad, now, recorded).is_none(),
13029                "{bad:?} must not be guessed at"
13030            );
13031        }
13032    }
13033
13034    /// A loop whose queue lives in a temp tree and whose poll interval is far
13035    /// longer than the test's patience, so anything that waits out a poll
13036    /// instead of noticing the stop fails rather than merely being slow.
13037    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
13038        let config = dir.join("magi.toml");
13039        std::fs::write(
13040            &config,
13041            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
13042        )
13043        .unwrap();
13044        let opts = Opts {
13045            poll: Duration::from_secs(30),
13046            config: Some(config),
13047            // The explicit fixture config keeps startup cleanup from reading
13048            // machine configuration. This fictional repository likewise
13049            // keeps any best-effort git cleanup away from this checkout.
13050            repo: dir.join("repo"),
13051            ..Opts::default()
13052        };
13053        // The status file goes in a directory that does not exist yet, so its
13054        // creation is itself evidence the loop published one. `worktrees`
13055        // must be just as fictional: the janitor reclaims worktrees under it
13056        // for real, and a test that let it fall through to
13057        // `crate::run::default_worktree_root()` would have it reclaim
13058        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
13059        // which is exactly what happened before this function took the
13060        // parameter at all.
13061        let home = dir.join("home");
13062        // These control-only fixtures do not launch native workers. Give the
13063        // independently tested maintenance services a fresh cadence receipt.
13064        let stamps = home.join("service-ticks");
13065        std::fs::create_dir_all(&stamps).unwrap();
13066        for service in ["waiter", "deputies", "release-watch"] {
13067            std::fs::write(
13068                stamps.join(service),
13069                Timestamp::now().as_second().to_string(),
13070            )
13071            .unwrap();
13072        }
13073        for operation in [
13074            "conductor",
13075            "maintenance",
13076            "housekeeping",
13077            "disk-pressure",
13078            "fold",
13079            "cache",
13080            "fetch",
13081            "chat-goals",
13082            "decisions",
13083        ] {
13084            std::fs::write(
13085                stamps.join(format!("daemon-{operation}")),
13086                serde_json::to_vec(&Timestamp::now()).unwrap(),
13087            )
13088            .unwrap();
13089        }
13090        let worktrees = dir.join("wt");
13091        (
13092            opts,
13093            Queue::at(dir.join("queue")),
13094            home.join("daemon.json"),
13095            home,
13096            worktrees,
13097        )
13098    }
13099
13100    #[tokio::test]
13101    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
13102        let dir = tempfile::tempdir().unwrap();
13103        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13104        let mut waiting = task();
13105        waiting.repo = opts.repo.clone();
13106        waiting.hold_machine(crate::disk::gate(1, 100));
13107        waiting.mark_disk_capacity();
13108        waiting.attempts = 2;
13109        queue.put(&mut waiting).unwrap();
13110        let mut busy = task();
13111        busy.status = TaskStatus::Running;
13112        queue.put(&mut busy).unwrap();
13113        let payload = serde_json::to_value(ServiceWorker {
13114            opts,
13115            queue: queue.root().to_owned(),
13116            worktrees_root: worktrees,
13117            operation: "maintenance".into(),
13118        })
13119        .unwrap();
13120        run_service_worker(&home, payload.clone()).await.unwrap();
13121        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13122        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
13123        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13124        run_service_worker(&home, payload).await.unwrap();
13125        assert!(
13126            crate::worker::active(&home).unwrap().is_empty(),
13127            "monitoring only queues; normal dispatch owns launches"
13128        );
13129        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
13130    }
13131
13132    #[tokio::test]
13133    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
13134        let dir = tempfile::tempdir().unwrap();
13135        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13136        let cfg = Config::default();
13137        start_service(
13138            &home,
13139            &opts,
13140            &queue,
13141            &worktrees,
13142            "housekeeping",
13143            Some(&cfg),
13144            true,
13145        )
13146        .await
13147        .unwrap();
13148        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
13149        let read = |path: &Path| -> serde_json::Value {
13150            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
13151        };
13152        assert_eq!(read(&receipt)["detail"], "cadence not due");
13153        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
13154        start_service(
13155            &home,
13156            &opts,
13157            &queue,
13158            &worktrees,
13159            "housekeeping",
13160            Some(&cfg),
13161            true,
13162        )
13163        .await
13164        .unwrap();
13165        assert_eq!(
13166            read(&receipt)["detail"],
13167            "active work or runnable task queue"
13168        );
13169        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
13170        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
13171        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
13172        start_service(
13173            &home,
13174            &opts,
13175            &queue,
13176            &worktrees,
13177            "disk-pressure",
13178            Some(&cfg),
13179            false,
13180        )
13181        .await
13182        .unwrap();
13183        assert_eq!(
13184            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
13185            "no active work; idle housekeeping owns scan"
13186        );
13187        assert!(crate::worker::active(&home).unwrap().is_empty());
13188    }
13189
13190    /// The folding turn exists exactly where idle housekeeping does not: with
13191    /// work busy or runnable. On `origin/main` the only caller of
13192    /// `clean::fold_due` was housekeeping, so a queue that was never empty
13193    /// admitted no finished-run folding at all.
13194    #[test]
13195    fn the_fold_turn_is_admitted_exactly_where_housekeeping_is_not() {
13196        let on = Config::default();
13197        for busy in [false, true] {
13198            for runnable in [false, true] {
13199                assert_ne!(
13200                    housekeeping_eligible(busy, runnable),
13201                    fold_turn_eligible(busy, runnable, Some(&on)),
13202                    "busy={busy} runnable={runnable}"
13203                );
13204            }
13205        }
13206        assert!(!housekeeping_eligible(true, true), "the 1275 machine");
13207        assert!(!fold_turn_eligible(true, true, None));
13208        let mut off = Config::default();
13209        off.disk.auto_fold = false;
13210        assert!(!fold_turn_eligible(true, true, Some(&off)));
13211        assert!(fold_turn_eligible(true, true, Some(&Config::default())));
13212    }
13213
13214    #[tokio::test]
13215    async fn the_fold_service_says_why_it_skipped_a_dispatch() {
13216        let dir = tempfile::tempdir().unwrap();
13217        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13218        let read = || -> serde_json::Value {
13219            serde_json::from_slice(
13220                &std::fs::read(home.join("source-eviction-fold-dispatch.json")).unwrap(),
13221            )
13222            .unwrap()
13223        };
13224        let tick = home.join("service-ticks/daemon-fold");
13225        let cfg = Config::default();
13226        let dispatch = |busy: bool, cfg: Config| {
13227            let (home, opts, queue, worktrees) = (&home, &opts, &queue, &worktrees);
13228            async move {
13229                start_service(home, opts, queue, worktrees, "fold", Some(&cfg), busy)
13230                    .await
13231                    .unwrap();
13232            }
13233        };
13234        dispatch(true, cfg.clone()).await;
13235        assert_eq!(read()["detail"], "cadence not due");
13236
13237        std::fs::remove_file(&tick).unwrap();
13238        dispatch(false, cfg.clone()).await;
13239        assert_eq!(
13240            read()["detail"],
13241            "idle machine; housekeeping owns finished-run folding"
13242        );
13243        let mut off = cfg.clone();
13244        off.disk.auto_fold = false;
13245        dispatch(true, off).await;
13246        assert_eq!(read()["detail"], "auto_fold disabled");
13247        // An unreadable startup configuration is its own reason, not "idle".
13248        start_service(&home, &opts, &queue, &worktrees, "fold", None, true)
13249            .await
13250            .unwrap();
13251        assert_eq!(read()["detail"], "startup configuration unavailable");
13252
13253        // A housekeeping worker already folding: one folding service at a time.
13254        let directory = home.join("workers/jobs/abcdef");
13255        std::fs::create_dir_all(&directory).unwrap();
13256        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13257        crate::pr_head::try_lock_file(&lease).unwrap();
13258        let mut job = crate::worker::Job {
13259            id: "abcdef".into(),
13260            sequence: 1,
13261            kind: "daemon-service".into(),
13262            key: "service:daemon-housekeeping".into(),
13263            payload: serde_json::Value::Null,
13264            generation: "fixture".into(),
13265            version: None,
13266            status: crate::worker::Status::Running,
13267            result: None,
13268            pid: Some(std::process::id()),
13269            created_at: Timestamp::now().as_second() as u64,
13270            finished_at: None,
13271        };
13272        let record = directory.join("job.json");
13273        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13274        dispatch(true, cfg).await;
13275        assert_eq!(
13276            read()["detail"],
13277            "another finished-run folding service is active"
13278        );
13279        assert_eq!(crate::worker::active(&home).unwrap().len(), 1);
13280        job.status = crate::worker::Status::Finished;
13281        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13282        drop(lease);
13283    }
13284
13285    /// Issue 1275 through the scheduler's own admission: a leased task worker is
13286    /// busy, another task is runnable, and a confirmed merged run of the same
13287    /// repository is long past its grace. `poll` admits the fold service (the
13288    /// worker runs inline here: a unit test has no `magi` executable to exec),
13289    /// the historical worktree goes, the repository's active checkout stays and
13290    /// the merged run's evidence is kept. Removing `"fold"` from the operation
13291    /// list in `poll` leaves the worktree standing and fails this test.
13292    #[tokio::test]
13293    async fn the_scheduler_folds_a_merged_run_beside_a_busy_worker_and_a_runnable_task() {
13294        let dir = tempfile::tempdir().unwrap();
13295        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13296        let repo = dir.path().join("checkout");
13297        std::fs::create_dir_all(&repo).unwrap();
13298        crate::clean::tests::init_repo(&repo);
13299        std::fs::write(
13300            opts.config.as_ref().unwrap(),
13301            "[disk]\nmin_free_bytes = 0\nauto_fold = true\ncache_limit_bytes = 0\n",
13302        )
13303        .unwrap();
13304        let (id, historical) = crate::clean::tests::merged_run_with_worktree(
13305            &home,
13306            &repo,
13307            &worktrees,
13308            "20260801-000000-s001",
13309        )
13310        .await;
13311        let active = dir.path().join("active");
13312        crate::git::worktree_add_branch(&repo, &active, "magi/active", "main")
13313            .await
13314            .unwrap();
13315        // The busy worker belongs to the scheduler's own queue and owns a
13316        // recorded run of the same repository that is eligible on paper
13317        // (finished, past its grace). Its execution lease is held, as a
13318        // driving worker holds it.
13319        let (owned_id, owned_worktree) = crate::clean::tests::due_run_with_winner_worktree(
13320            &home.join("runs"),
13321            &worktrees,
13322            &repo,
13323            "20260801-000000-s002",
13324            RunStatus::Superseded,
13325        )
13326        .await;
13327        let owned_run = home.join("runs").join(&owned_id);
13328        let owned_record = std::fs::read(owned_run.join("run.json")).unwrap();
13329        let mut busy = task();
13330        busy.repo = repo.clone();
13331        busy.status = TaskStatus::Running;
13332        busy.link_run(&owned_id);
13333        queue.put(&mut busy).unwrap();
13334        let worker_lease = crate::worker::running_fixture(
13335            &home,
13336            &format!("task:{}", busy.id),
13337            serde_json::to_value(TaskWorker {
13338                opts: Opts::default(),
13339                queue: queue.root().to_owned(),
13340                task: busy.id.clone(),
13341                lane: PermitKind::default(),
13342                standalone: true,
13343            })
13344            .unwrap(),
13345        )
13346        .unwrap();
13347        let execution = crate::driver::maintenance(&home, &owned_id).unwrap();
13348        let mut waiting = task();
13349        waiting.repo = repo.clone();
13350        queue.put(&mut waiting).unwrap();
13351        std::fs::remove_file(home.join("service-ticks/daemon-fold")).unwrap();
13352
13353        let mut cfg = Config::default();
13354        cfg.disk.auto_fold = true;
13355        INLINE_SERVICES.with(|inline| inline.set(true));
13356        let status = Arc::new(Mutex::new(Status::new()));
13357        let stop = Stop::new();
13358        let mut dispatch = Box::pin(poll(
13359            &opts,
13360            &queue,
13361            &status,
13362            &home,
13363            &worktrees,
13364            &stop,
13365            DispatchLimits {
13366                max_concurrent: 0,
13367                pause_for_interrupts: false,
13368                recovery_cfg: Some(cfg),
13369            },
13370        ));
13371        let receipt = home.join("source-eviction-fold-worker.json");
13372        let completed = async {
13373            loop {
13374                let done = std::fs::read(&receipt)
13375                    .ok()
13376                    .and_then(|body| serde_json::from_slice::<serde_json::Value>(&body).ok())
13377                    .is_some_and(|receipt| receipt["outcome"] == "completed");
13378                if done {
13379                    break;
13380                }
13381                tokio::time::sleep(Duration::from_millis(25)).await;
13382            }
13383        };
13384        tokio::select! {
13385            result = &mut dispatch => panic!("the scheduler stopped before the fold service ran: {result:?}"),
13386            result = tokio::time::timeout(Duration::from_secs(120), completed) => {
13387                result.expect("the scheduler never admitted the fold service");
13388            }
13389        }
13390        stop.stop();
13391        dispatch.await.unwrap();
13392        INLINE_SERVICES.with(|inline| inline.set(false));
13393
13394        assert!(!historical.exists(), "the merged run's worktree is folded");
13395        assert!(
13396            active.join("README.md").is_file(),
13397            "the repository's active checkout is untouched"
13398        );
13399        let run = home.join("runs").join(&id);
13400        assert!(run.join("run.json").is_file());
13401        assert!(run.join("artifacts/fold-evidence/manifest.json").is_file());
13402        let read = |name: &str| -> serde_json::Value {
13403            serde_json::from_slice(&std::fs::read(home.join(name)).unwrap()).unwrap()
13404        };
13405        assert_eq!(
13406            read("source-eviction-fold-dispatch.json")["detail"],
13407            "eligible and cadence due"
13408        );
13409        let worker = read("source-eviction-fold-worker.json");
13410        assert_eq!(worker["fold"]["records"], 2);
13411        assert_eq!(worker["fold"]["folded"], 1);
13412        assert_eq!(worker["fold"]["invoked"], 1);
13413        assert_eq!(
13414            worker["fold"]["live"], 1,
13415            "the busy worker's own run is left alone: {worker}"
13416        );
13417        // The run the busy worker owns - eligible on paper (finished, past its
13418        // grace) - keeps its checkout, its candidate and its record, byte for byte.
13419        assert!(owned_worktree.exists());
13420        assert_eq!(
13421            std::fs::read(owned_run.join("run.json")).unwrap(),
13422            owned_record
13423        );
13424        assert!(
13425            !RunState::load_under(&owned_id, &home).unwrap().candidates[0].folded,
13426            "the owned run's candidate is not folded"
13427        );
13428        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
13429        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
13430        drop(execution);
13431        drop(worker_lease);
13432    }
13433
13434    /// On a platform without process containment the disk-pressure service
13435    /// refuses to reclaim, and says so in both places an operator looks: the
13436    /// persisted retention report and the worker receipt. Driven through the
13437    /// service handler itself, so removing either publication fails this test.
13438    #[tokio::test]
13439    async fn the_disk_pressure_service_reports_a_platform_without_containment() {
13440        let dir = tempfile::tempdir().unwrap();
13441        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13442        let payload = serde_json::to_value(ServiceWorker {
13443            opts,
13444            queue: queue.root().to_owned(),
13445            worktrees_root: worktrees,
13446            operation: "disk-pressure".into(),
13447        })
13448        .unwrap();
13449        let _platform = crate::retention::WithoutContainment::new();
13450        run_service_worker(&home, payload).await.unwrap();
13451
13452        let refusal = "Automatic output reclamation requires Unix process containment";
13453        let report: serde_json::Value =
13454            serde_json::from_slice(&std::fs::read(home.join("retention.json")).unwrap()).unwrap();
13455        assert_eq!(report["failures"], serde_json::json!([refusal]));
13456        let receipt: serde_json::Value = serde_json::from_slice(
13457            &std::fs::read(home.join("source-eviction-disk-pressure-worker.json")).unwrap(),
13458        )
13459        .unwrap();
13460        assert_eq!(receipt["outcome"], "retention swept");
13461        assert_eq!(receipt["retention"]["failure_count"], 1);
13462        assert_eq!(
13463            receipt["retention"]["failures"],
13464            serde_json::json!([refusal])
13465        );
13466    }
13467
13468    #[tokio::test]
13469    async fn goal_observation_service_does_not_block_scheduler_decisions() {
13470        let dir = tempfile::tempdir().unwrap();
13471        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
13472        let queue = Queue::at(home.join("queue"));
13473        let mut task = task();
13474        task.repo = opts.repo.clone();
13475        task.chat = Some("decision-chat".into());
13476        let mut state = run_state(RunStatus::Merged);
13477        state.repo = task.repo.clone();
13478        state.merge = Some(crate::run::MergeOutcome {
13479            mode: MergeMode::Pr,
13480            ok: true,
13481            detail: "confirmed merge".into(),
13482            empty: false,
13483        });
13484        task.link_run(&state.id);
13485        state.save_under(&home).unwrap();
13486        task.hold_machine(Some("waiting for a decision".into()));
13487        queue.put(&mut task).unwrap();
13488        let questions = Questions::at(home.join("questions"));
13489        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
13490        question.node = crate::conduct::NODE.into();
13491        question.status = ask::QuestionStatus::Open;
13492        question.answer = None;
13493        question.answered_at = None;
13494        questions.put(&mut question).unwrap();
13495        questions
13496            .update(&question.id, |q| {
13497                q.answer(ask::Answer::Choice("resume で続行する".into()))
13498            })
13499            .unwrap();
13500
13501        let talks = crate::talk::Talks::at(home.join("talks"));
13502        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
13503        decision_chat.pending = "Keep this unsent status question".into();
13504        talks.put(&mut decision_chat).unwrap();
13505        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
13506        talk.goals.push(serde_json::from_value(serde_json::json!({
13507            "id":"goal","purpose":"follow the retained job","scope":"one task",
13508            "condition":{"description":"land the result","kind":"runs_merged"},
13509            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
13510            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
13511            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
13512        })).unwrap());
13513        talks.put(&mut talk).unwrap();
13514
13515        // A retained service lease models an observation still waiting on its
13516        // external dependency. Admission must neither await nor repeat it.
13517        let directory = home.join("workers/jobs/abcdef");
13518        std::fs::create_dir_all(&directory).unwrap();
13519        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13520        crate::pr_head::try_lock_file(&lease).unwrap();
13521        let mut job = crate::worker::Job {
13522            id: "abcdef".into(),
13523            sequence: 1,
13524            kind: "daemon-service".into(),
13525            key: "service:daemon-chat-goals".into(),
13526            payload: serde_json::Value::Null,
13527            generation: "fixture".into(),
13528            version: None,
13529            status: crate::worker::Status::Running,
13530            result: None,
13531            pid: Some(std::process::id()),
13532            created_at: Timestamp::now().as_second() as u64,
13533            finished_at: None,
13534        };
13535        let record = directory.join("job.json");
13536        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13537        let status = Arc::new(Mutex::new(Status::new()));
13538        let stop = Stop::new();
13539        let mut dispatch = Box::pin(poll(
13540            &opts,
13541            &queue,
13542            &status,
13543            &home,
13544            &worktrees,
13545            &stop,
13546            DispatchLimits {
13547                max_concurrent: 1,
13548                pause_for_interrupts: false,
13549                recovery_cfg: None,
13550            },
13551        ));
13552        std::future::poll_fn(|cx| {
13553            assert!(dispatch.as_mut().poll(cx).is_pending());
13554            std::task::Poll::Ready(())
13555        })
13556        .await;
13557        assert!(lock(&status).polls > 0);
13558        let saved = queue.get(&task.id).unwrap();
13559        assert_eq!(saved.status, TaskStatus::Done);
13560        assert!(saved.action_applied(&question.id));
13561        assert!(
13562            talks
13563                .get("decision-chat")
13564                .unwrap()
13565                .pending
13566                .contains("Keep this unsent status question")
13567        );
13568        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
13569        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
13570        assert_eq!(
13571            goal.started,
13572            Some(1),
13573            "only the observation worker may reconcile its goal"
13574        );
13575        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
13576
13577        stop.stop();
13578        dispatch.await.unwrap();
13579        job.status = crate::worker::Status::Finished;
13580        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
13581        drop(lease);
13582    }
13583
13584    #[test]
13585    fn a_stop_is_idempotent_and_once_set_stays_set() {
13586        let stop = Stop::new();
13587        assert!(!stop.stopped());
13588
13589        stop.stop();
13590        assert!(stop.stopped());
13591        stop.stop();
13592        assert!(stop.stopped(), "a second stop is not a toggle");
13593
13594        let shared = stop.clone();
13595        assert!(
13596            shared.stopped(),
13597            "a clone is the same stop; that is how the loop and its caller share one"
13598        );
13599    }
13600
13601    #[tokio::test]
13602    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
13603        for operation in ["conductor", "maintenance", "housekeeping", "decisions"] {
13604            let dir = tempfile::tempdir().unwrap();
13605            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
13606            opts.once = true;
13607            opts.poll = Duration::from_millis(1);
13608            // This test exercises answer scheduling, not explicit discard:
13609            // ordinary Done requires confirmed landing.
13610            let mut state = run_state(RunStatus::Merged);
13611            state.merge = Some(crate::run::MergeOutcome {
13612                mode: MergeMode::Pr,
13613                ok: true,
13614                detail: "confirmed merge".into(),
13615                empty: false,
13616            });
13617            state.reserve_under(&home).unwrap();
13618            state.save_under(&home).unwrap();
13619            let mut task = task();
13620            // Completing a human task would reserve a task chat and start a
13621            // chat worker; this fixture only exercises answer scheduling. A
13622            // linked chat that does not exist is skipped, never created.
13623            task.chat = Some("task-fixture".into());
13624            task.chat_reservation = crate::queue::ChatReservation::Established;
13625            task.runs.push(state.id.clone());
13626            queue.put(&mut task).unwrap();
13627            let claim = queue.claim(&task.id).unwrap();
13628
13629            // Model a live service holding the task's claim across the
13630            // scheduler's dispatch scan. No real subprocess or timed race.
13631            let directory = home.join("workers/jobs/abcdef");
13632            std::fs::create_dir_all(&directory).unwrap();
13633            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
13634            crate::pr_head::try_lock_file(&lease).unwrap();
13635            let mut job = crate::worker::Job {
13636                id: "abcdef".into(),
13637                sequence: 1,
13638                kind: "daemon-service".into(),
13639                key: format!("service:daemon-{operation}"),
13640                payload: serde_json::Value::Null,
13641                generation: "fixture".into(),
13642                version: None,
13643                status: crate::worker::Status::Running,
13644                result: None,
13645                pid: Some(std::process::id()),
13646                created_at: Timestamp::now().as_second() as u64,
13647                finished_at: None,
13648            };
13649            let record = directory.join("job.json");
13650            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13651
13652            let status = Arc::new(Mutex::new(Status::new()));
13653            let stop = Stop::new();
13654            let mut drain = Box::pin(poll(
13655                &opts,
13656                &queue,
13657                &status,
13658                &home,
13659                &worktrees,
13660                &stop,
13661                DispatchLimits {
13662                    max_concurrent: 1,
13663                    pause_for_interrupts: false,
13664                    recovery_cfg: None,
13665                },
13666            ));
13667            std::future::poll_fn(|cx| {
13668                use std::future::Future;
13669                assert!(
13670                    drain.as_mut().poll(cx).is_pending(),
13671                    "--once must wait for {operation} to release its queue claim"
13672                );
13673                std::task::Poll::Ready(())
13674            })
13675            .await;
13676            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
13677
13678            // An answer arrives while the service still owns the claim. A
13679            // fresh scheduling pass must apply it before declaring idle.
13680            let questions = Questions::at(home.join("questions"));
13681            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
13682            questions.put(&mut q).unwrap();
13683            drop(claim);
13684            // Model services that took longer than their cadence, without a
13685            // wall-clock sleep. The final scans must not respawn them even
13686            // though their receipts now permit another periodic invocation.
13687            let expired =
13688                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
13689            for service in [operation, "housekeeping"] {
13690                std::fs::write(
13691                    home.join("service-ticks").join(format!("daemon-{service}")),
13692                    &expired,
13693                )
13694                .unwrap();
13695            }
13696            job.status = crate::worker::Status::Finished;
13697            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
13698            drop(lease);
13699            tokio::time::timeout(Duration::from_secs(2), drain)
13700                .await
13701                .expect("the settled service must allow the drain to finish")
13702                .unwrap();
13703            let after = queue.get(&task.id).unwrap();
13704            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
13705            assert!(after.action_applied(&q.id));
13706            for service in [operation, "housekeeping"] {
13707                assert_eq!(
13708                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
13709                        .unwrap(),
13710                    expired,
13711                    "the final once rescan must not restart {service}"
13712                );
13713            }
13714        }
13715    }
13716
13717    #[test]
13718    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
13719        let stop = Stop::new();
13720        stop.busy.store(1, Ordering::SeqCst);
13721        assert!(
13722            !stop.finishing(),
13723            "a busy loop nobody has asked to stop is just running"
13724        );
13725
13726        stop.stop();
13727        assert!(
13728            stop.finishing(),
13729            "a stop asked for mid-run has not landed until the run is settled"
13730        );
13731
13732        stop.busy.store(0, Ordering::SeqCst);
13733        assert!(
13734            !stop.finishing(),
13735            "once the run is settled the stop has landed and there is nothing to finish"
13736        );
13737    }
13738
13739    #[test]
13740    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
13741        let stop = Stop::new();
13742        stop.busy.store(2, Ordering::SeqCst);
13743        stop.stop();
13744        assert!(stop.finishing(), "two runs still in flight");
13745
13746        stop.busy.store(1, Ordering::SeqCst);
13747        assert!(
13748            stop.finishing(),
13749            "one run finished, but a sibling is still working"
13750        );
13751
13752        stop.busy.store(0, Ordering::SeqCst);
13753        assert!(
13754            !stop.finishing(),
13755            "the last run out is what actually lands the stop"
13756        );
13757    }
13758
13759    #[tokio::test]
13760    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
13761        let dir = tempfile::tempdir().unwrap();
13762        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13763        let stop = Stop::new();
13764        stop.stop();
13765
13766        let began = std::time::Instant::now();
13767        tokio::time::timeout(
13768            Duration::from_secs(2),
13769            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13770        )
13771        .await
13772        .expect("a stopped loop must return, not sit out its poll interval")
13773        .expect("the loop's own setup and teardown must not fail");
13774        assert!(
13775            began.elapsed() < opts.poll,
13776            "returned only after {:?}, which is a poll interval, not a stop",
13777            began.elapsed()
13778        );
13779    }
13780
13781    #[tokio::test]
13782    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
13783        let dir = tempfile::tempdir().unwrap();
13784        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13785        let stop = Stop::new();
13786
13787        // Asked for after the loop is already parked on its empty queue, which
13788        // is the case an operator tapping stop on a phone actually hits.
13789        let asker = {
13790            let stop = stop.clone();
13791            tokio::spawn(async move {
13792                tokio::time::sleep(Duration::from_millis(20)).await;
13793                stop.stop();
13794            })
13795        };
13796
13797        let began = std::time::Instant::now();
13798        tokio::time::timeout(
13799            Duration::from_secs(2),
13800            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13801        )
13802        .await
13803        .expect("a stop asked for while idle must wake the wait")
13804        .expect("the loop's own setup and teardown must not fail");
13805        asker.await.unwrap();
13806        assert!(
13807            began.elapsed() < opts.poll,
13808            "returned only after {:?}, so the stop waited on the sleep",
13809            began.elapsed()
13810        );
13811    }
13812
13813    #[tokio::test]
13814    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
13815        let dir = tempfile::tempdir().unwrap();
13816        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
13817        let stop = Stop::new();
13818        stop.stop();
13819
13820        tokio::time::timeout(
13821            Duration::from_secs(2),
13822            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
13823        )
13824        .await
13825        .expect("a stopped loop must return")
13826        .expect("the loop's own setup and teardown must not fail");
13827
13828        assert!(
13829            home.is_dir(),
13830            "the loop did publish a status file, so its removal is the teardown and not an absence"
13831        );
13832        assert!(
13833            !status_file.exists(),
13834            "a stopped loop clears its status file"
13835        );
13836        assert!(
13837            read_status(&home).is_none(),
13838            "a reader must see no daemon at all, not a heartbeat that merely stopped"
13839        );
13840    }
13841
13842    #[tokio::test]
13843    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
13844        let dir = tempfile::tempdir().unwrap();
13845        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
13846
13847        let mut settled = RunState::new(
13848            dir.path().join("repo"),
13849            "main".to_owned(),
13850            "abc1234".to_owned(),
13851            "fixture".to_owned(),
13852            Config::default(),
13853        );
13854        settled.status = RunStatus::Ready;
13855        let run_dir = home.join("runs").join(&settled.id);
13856        std::fs::create_dir_all(&run_dir).unwrap();
13857        std::fs::write(
13858            run_dir.join("run.json"),
13859            serde_json::to_string_pretty(&settled).unwrap(),
13860        )
13861        .unwrap();
13862        let questions = Questions::at(home.join("questions"));
13863        let mut question = ask::Question::new(
13864            settled.id.clone(),
13865            "review".to_owned(),
13866            "reviewer-1".to_owned(),
13867            "Continue?".to_owned(),
13868            String::new(),
13869            Vec::new(),
13870        );
13871        questions.put(&mut question).unwrap();
13872
13873        run_service_worker(
13874            &home,
13875            serde_json::to_value(ServiceWorker {
13876                opts,
13877                queue: queue.root().to_path_buf(),
13878                worktrees_root: worktrees,
13879                operation: "housekeeping".to_owned(),
13880            })
13881            .unwrap(),
13882        )
13883        .await
13884        .unwrap();
13885
13886        assert_eq!(
13887            questions.get(&question.id).unwrap().status,
13888            ask::QuestionStatus::Abandoned,
13889            "the independent housekeeping worker settles ended-run questions"
13890        );
13891    }
13892
13893    #[test]
13894    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
13895        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13896
13897        assert!(
13898            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
13899            "never checked before: due at once"
13900        );
13901
13902        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
13903        assert!(
13904            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
13905            "well inside the interval: not due yet"
13906        );
13907
13908        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
13909        assert!(
13910            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
13911            "exactly at the edge: not yet due, same convention as `clean::due`"
13912        );
13913
13914        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13915        assert!(
13916            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
13917            "past the interval: due again"
13918        );
13919    }
13920
13921    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
13922    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
13923    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
13924    /// and the congestion test below both need, and must not drift apart.
13925    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
13926        let config = dir.join("magi.toml");
13927        // A literal (single-quoted) TOML string, not a basic one: the cache
13928        // path is a Windows path full of backslashes, and a basic string
13929        // would have TOML try to interpret `\U` (from `\Users\...`) as a
13930        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
13931        // `{{ vars.cache }}` rendering documents.
13932        std::fs::write(
13933            &config,
13934            format!(
13935                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
13936                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
13937                cache_dir.display()
13938            ),
13939        )
13940        .unwrap();
13941        Opts {
13942            config: Some(config),
13943            repo: dir.join("repo"),
13944            ..Opts::default()
13945        }
13946    }
13947
13948    #[tokio::test]
13949    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
13950        let dir = tempfile::tempdir().unwrap();
13951        let home = dir.path().join("home");
13952        let cache_dir = dir.path().join("cache");
13953        std::fs::create_dir_all(&cache_dir).unwrap();
13954        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
13955        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
13956
13957        // Nobody has asked this daemon to stop, which is the ordinary case;
13958        // the skip that a stop buys is asserted by its own test below.
13959        let running = Stop::new();
13960        let mut last_checked = None;
13961        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
13962        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
13963            .await;
13964        assert_eq!(
13965            crate::disk::dir_size(&cache_dir),
13966            0,
13967            "over the cap on the first check ever: pruned at once, no idle queue required"
13968        );
13969        assert_eq!(last_checked, Some(t0));
13970
13971        // A fresh oversized file lands, but the next check is not due yet.
13972        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
13973        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
13974        maybe_prune_cache_between_runs(
13975            &opts.repo,
13976            &opts,
13977            &home,
13978            &running,
13979            &mut last_checked,
13980            too_soon,
13981        )
13982        .await;
13983        assert_eq!(
13984            crate::disk::dir_size(&cache_dir),
13985            10,
13986            "too soon since the last check: left alone rather than rescanned every call"
13987        );
13988        assert_eq!(
13989            last_checked,
13990            Some(t0),
13991            "an idle check does not reset the clock"
13992        );
13993
13994        // Once the interval elapses, the same oversized cache is caught again.
13995        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
13996        maybe_prune_cache_between_runs(
13997            &opts.repo,
13998            &opts,
13999            &home,
14000            &running,
14001            &mut last_checked,
14002            due_again,
14003        )
14004        .await;
14005        assert_eq!(
14006            crate::disk::dir_size(&cache_dir),
14007            0,
14008            "due again: pruned back under the cap"
14009        );
14010    }
14011
14012    /// A stop must not queue behind housekeeping. The prune below is a
14013    /// synchronous walk of the whole cache with no await point in it, so a
14014    /// loop that entered it could not get back to its own `stopped()` test
14015    /// until the walk finished - and because no run is in flight at this
14016    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
14017    /// the stop had already landed. The idle branch has always made this same
14018    /// check before reaching `janitor`; the between-runs path makes it too.
14019    #[tokio::test]
14020    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
14021        let dir = tempfile::tempdir().unwrap();
14022        let home = dir.path().join("home");
14023        let cache_dir = dir.path().join("cache");
14024        std::fs::create_dir_all(&cache_dir).unwrap();
14025        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
14026        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
14027
14028        let stop = Stop::new();
14029        stop.stop();
14030        assert!(
14031            !stop.finishing(),
14032            "no run is in flight at a between-runs boundary, so nothing else \
14033             would tell the operator this stop had not taken effect yet"
14034        );
14035
14036        let mut last_checked = None;
14037        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
14038        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
14039            .await;
14040        assert_eq!(
14041            crate::disk::dir_size(&cache_dir),
14042            10,
14043            "over its cap, and due for the first check ever, but a stop outranks \
14044             it: the cap is a standing policy the next start measures again"
14045        );
14046        assert_eq!(
14047            last_checked, None,
14048            "a check that never happened must not claim the interval"
14049        );
14050    }
14051
14052    /// A backlog must not starve cache pruning. The finite cache worker runs
14053    /// independently of queue drain and must not consume any task attempts.
14054    #[tokio::test]
14055    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
14056        let dir = tempfile::tempdir().unwrap();
14057        let cache_dir = dir.path().join("cache");
14058        std::fs::create_dir_all(&cache_dir).unwrap();
14059        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
14060
14061        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
14062        opts.poll = Duration::from_millis(20);
14063        opts.max_attempts = 1_000;
14064
14065        let queue = Queue::at(dir.path().join("queue"));
14066        for i in 0..128 {
14067            let mut task = Task::new(
14068                format!("queued work {i}"),
14069                format!("queued work {i}"),
14070                opts.repo.clone(),
14071                Source::Human,
14072            );
14073            queue.put(&mut task).unwrap();
14074        }
14075
14076        let home = dir.path().join("home");
14077        let worktrees = dir.path().join("wt");
14078        run_service_worker(
14079            &home,
14080            serde_json::to_value(ServiceWorker {
14081                opts,
14082                queue: queue.root().to_path_buf(),
14083                worktrees_root: worktrees,
14084                operation: "cache".to_owned(),
14085            })
14086            .unwrap(),
14087        )
14088        .await
14089        .unwrap();
14090        let after = queue.list();
14091        assert_eq!(after.len(), 128);
14092        assert!(
14093            after
14094                .iter()
14095                .all(|task| task.status.runnable() && task.attempts == 0)
14096        );
14097
14098        assert_eq!(
14099            crate::disk::dir_size(&cache_dir),
14100            0,
14101            "an oversized cache must not be left to grow unboundedly just because the \
14102             queue kept the loop busy the whole time"
14103        );
14104    }
14105
14106    #[test]
14107    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
14108        let dir = tempfile::tempdir().unwrap();
14109        let queue = Queue::at(dir.path().join("queue"));
14110        let questions = Questions::at(dir.path().join("questions"));
14111        let mut task = task();
14112        queue.put(&mut task).unwrap();
14113
14114        let mut task_question = ask::Question::new(
14115            task.id.clone(),
14116            crate::conduct::NODE.to_owned(),
14117            "conduct".to_owned(),
14118            "Which backend?".to_owned(),
14119            String::new(),
14120            Vec::new(),
14121        );
14122        questions.put(&mut task_question).unwrap();
14123        task.block(vec![task_question.id.clone()], None);
14124        queue.put(&mut task).unwrap();
14125
14126        let mut run_question = ask::Question::new(
14127            "20260101-000000-run1".to_owned(),
14128            "review".to_owned(),
14129            "reviewer-1".to_owned(),
14130            "Run question".to_owned(),
14131            String::new(),
14132            Vec::new(),
14133        );
14134        questions.put(&mut run_question).unwrap();
14135
14136        // A question from another node whose `run` happens to equal this
14137        // task's id — the same field, filled in for an unrelated reason. Only
14138        // `crate::conduct::NODE` questions use `run` as a task id; this one
14139        // must never be touched by this reconciliation, even after release.
14140        let mut coincidental = ask::Question::new(
14141            task.id.clone(),
14142            "review".to_owned(),
14143            "reviewer-1".to_owned(),
14144            "Unrelated review question".to_owned(),
14145            String::new(),
14146            Vec::new(),
14147        );
14148        questions.put(&mut coincidental).unwrap();
14149
14150        reconcile_task_questions(&queue, &questions);
14151        assert!(questions.get(&task_question.id).unwrap().status.open());
14152        assert!(questions.get(&run_question.id).unwrap().status.open());
14153        assert!(questions.get(&coincidental.id).unwrap().status.open());
14154
14155        task.release();
14156        queue.put(&mut task).unwrap();
14157        reconcile_task_questions(&queue, &questions);
14158        assert_eq!(
14159            questions.get(&task_question.id).unwrap().status,
14160            ask::QuestionStatus::Abandoned
14161        );
14162        assert!(
14163            questions.get(&run_question.id).unwrap().status.open(),
14164            "run questions remain the run janitor's responsibility"
14165        );
14166        assert!(
14167            questions.get(&coincidental.id).unwrap().status.open(),
14168            "a non-conductor question must not be abandoned just because its \
14169             run id coincides with a task id"
14170        );
14171    }
14172
14173    #[test]
14174    fn a_freshly_started_running_task_is_never_stalled() {
14175        let dir = tempfile::tempdir().unwrap();
14176        let mut t = task();
14177        t.start("run-1".to_owned());
14178        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
14179        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
14180        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
14181    }
14182
14183    #[test]
14184    fn a_long_running_task_with_no_live_daemon_is_stalled() {
14185        let dir = tempfile::tempdir().unwrap();
14186        let mut t = task();
14187        t.start("run-1".to_owned());
14188        t.updated_at = Timestamp::now()
14189            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14190        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
14191        assert_eq!(
14192            stalled_tasks(
14193                &Queue::at(dir.path().join("q")),
14194                dir.path(),
14195                Timestamp::now()
14196            )
14197            .len(),
14198            0,
14199            "the task was never written to this queue"
14200        );
14201    }
14202
14203    #[test]
14204    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
14205        let dir = tempfile::tempdir().unwrap();
14206        let mut t = task();
14207        t.id = "20260903-080340-0167".to_owned();
14208        t.start("20260903-080619-01c2".to_owned());
14209        t.updated_at = Timestamp::now()
14210            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
14211
14212        let mut status = Status::new();
14213        status.current = vec![Current {
14214            worker: None,
14215            task: t.id.clone(),
14216            run: "20260903-080619-01c2".to_owned(),
14217        }];
14218        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
14219
14220        assert!(
14221            !is_stalled(&t, dir.path(), Timestamp::now()),
14222            "a live daemon's own heartbeat rules out stalled, however long the task has run"
14223        );
14224    }
14225
14226    /// Rewrite a task's `updated_at` on disk directly, bypassing
14227    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
14228    /// a fixture look like it has genuinely been `running` for a while.
14229    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
14230        let path = queue.path_of(id);
14231        let body = std::fs::read_to_string(&path).unwrap();
14232        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
14233        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
14234        v["updated_at"] = serde_json::Value::String(old.to_string());
14235        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
14236    }
14237
14238    #[test]
14239    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
14240        // The realistic `poll()` ordering, not `is_stalled` in isolation:
14241        // `reclaim_orphaned_running` runs first, on every poll, and settles
14242        // any `running` task whose claim it can actually take. For most
14243        // crashes that is immediate - a dead pid is proof enough for
14244        // `sweep_stale_claims` to drop the lock the same tick, and the very
14245        // next claim attempt succeeds. But a lock whose pid cannot be parsed
14246        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
14247        // `sweep_stale_claims`'s own doc), so the lock - and the claim
14248        // failure behind it - can legitimately outlive many polls. This is
14249        // exactly the gap `stalled_tasks` exists to surface well before that
14250        // six-hour sweep would: reclaim leaves the task `running`, and it
14251        // must still reach the conductor as stalled.
14252        let dir = tempfile::tempdir().unwrap();
14253        let queue = Queue::at(dir.path().join("queue"));
14254        let home = dir.path().join("home");
14255
14256        let mut t = task();
14257        t.id = "20260101-000001-lock".to_owned();
14258        t.start("run-1".to_owned());
14259        queue.put(&mut t).unwrap();
14260        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14261        std::fs::write(
14262            dir.path().join("queue").join(format!("{}.lock", t.id)),
14263            "not a pid",
14264        )
14265        .unwrap();
14266
14267        let now = Timestamp::now();
14268        assert!(
14269            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
14270            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
14271             and reclaim must leave the task alone"
14272        );
14273        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
14274
14275        let stalled = stalled_tasks(&queue, &home, now);
14276        assert_eq!(
14277            stalled.len(),
14278            1,
14279            "reclaim's inability to claim it yet must not hide it from the conductor"
14280        );
14281        assert_eq!(stalled[0].id, t.id);
14282    }
14283
14284    #[test]
14285    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
14286        let dir = tempfile::tempdir().unwrap();
14287        crate::run::set_home(dir.path().join("run-home"));
14288        let queue = Queue::at(dir.path().join("queue"));
14289        let home = dir.path().join("home");
14290        let questions = Questions::at(dir.path().join("questions"));
14291
14292        let mut t = task();
14293        t.id = "20260101-000003-dead".to_owned();
14294        t.start("missing-run".to_owned());
14295        queue.put(&mut t).unwrap();
14296        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
14297
14298        // This is the real poll ordering: retain the deterministic stalled
14299        // input before a claim proves the owner is gone and reclaims it.
14300        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14301        assert_eq!(
14302            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
14303            [&t.id]
14304        );
14305        assert_eq!(
14306            reclaim_orphaned_running(&queue, 2, &Default::default()),
14307            [t.id.clone()]
14308        );
14309        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
14310
14311        // Reclaim drops its guard before conductor decisions are applied, so
14312        // the decision for the captured stalled input has a real write path.
14313        crate::conduct::apply(
14314            &queue,
14315            &questions,
14316            &crate::conduct::Verdict {
14317                decisions: vec![crate::conduct::Decision {
14318                    id: t.id.clone(),
14319                    recovery: Some(crate::conduct::Recovery::Requeue),
14320                    ..crate::conduct::Decision::default()
14321                }],
14322            },
14323        )
14324        .unwrap();
14325        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
14326    }
14327
14328    #[test]
14329    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
14330        let dir = tempfile::tempdir().unwrap();
14331        let queue = Queue::at(dir.path().join("queue"));
14332        let home = dir.path().join("home");
14333
14334        let mut fresh = task();
14335        fresh.id = "20260101-000001-aaaa".to_owned();
14336        fresh.start("run-1".to_owned());
14337        queue.put(&mut fresh).unwrap();
14338
14339        let mut old = task();
14340        old.id = "20260101-000002-bbbb".to_owned();
14341        old.start("run-2".to_owned());
14342        queue.put(&mut old).unwrap();
14343        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
14344
14345        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
14346        assert_eq!(stalled.len(), 1);
14347        assert_eq!(stalled[0].id, old.id);
14348    }
14349
14350    #[test]
14351    fn queued_and_finished_task_views_partition_by_status() {
14352        let dir = tempfile::tempdir().unwrap();
14353        let queue = Queue::at(dir.path().join("queue"));
14354
14355        let mut queued = task();
14356        queued.id = "20260101-000001-aaaa".to_owned();
14357        queue.put(&mut queued).unwrap();
14358
14359        let mut failed = task();
14360        failed.id = "20260101-000002-bbbb".to_owned();
14361        failed.start("run-1".to_owned());
14362        failed.fail("gate red", 5);
14363        queue.put(&mut failed).unwrap();
14364
14365        let mut held = task();
14366        held.id = "20260101-000003-cccc".to_owned();
14367        held.hold_machine(None);
14368        queue.put(&mut held).unwrap();
14369
14370        let mut running = task();
14371        running.id = "20260101-000004-dddd".to_owned();
14372        running.start("run-2".to_owned());
14373        queue.put(&mut running).unwrap();
14374
14375        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
14376        assert_eq!(queued_ids, [queued.id.clone()]);
14377
14378        let mut finished_ids: Vec<String> =
14379            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
14380        finished_ids.sort_unstable();
14381        let mut want = vec![failed.id.clone(), held.id.clone()];
14382        want.sort_unstable();
14383        assert_eq!(finished_ids, want);
14384    }
14385
14386    #[test]
14387    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
14388        for short in [false, true] {
14389            let dir = tempfile::tempdir().unwrap();
14390            let queue = Queue::at(dir.path().join("queue"));
14391            let questions = ask::Questions::at(dir.path().join("questions"));
14392            let mut running = task();
14393            running.id = "20261013-192213-feb2".into();
14394            running.start("existing-run".into());
14395            queue.put(&mut running).unwrap();
14396            let mut middle = task();
14397            middle.id = "20261013-193611-ca5b".into();
14398            middle.block(
14399                vec![if short {
14400                    "feb2".into()
14401                } else {
14402                    running.id.clone()
14403                }],
14404                None,
14405            );
14406            queue.put(&mut middle).unwrap();
14407            let mut waiting = task();
14408            waiting.id = "20261013-202849-ee37".into();
14409            waiting.block(
14410                vec![if short {
14411                    "ca5b".into()
14412                } else {
14413                    middle.id.clone()
14414                }],
14415                Some("wait for implementation".into()),
14416            );
14417            queue.put(&mut waiting).unwrap();
14418            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
14419            let inv = crate::blockers::Inventory::load(&queue, &questions);
14420            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
14421            assert!(inv.stuck().is_empty());
14422            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14423            assert!(report.quarantined.is_empty());
14424            assert!(report.asked.is_empty());
14425            resolve_blockers(&queue, &questions);
14426            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14427            assert!(questions.list().is_empty());
14428            // Finishing the transitive prerequisite alone does not satisfy
14429            // the task's direct dependency.
14430            running.succeed(CompletionContext::new(
14431                CompletionActor::DaemonSettle,
14432                None,
14433                dir.path(),
14434                &running,
14435            ));
14436            queue.put(&mut running).unwrap();
14437            resolve_blockers(&queue, &questions);
14438            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
14439            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14440            middle = queue.get(&middle.id).unwrap();
14441            middle.succeed(CompletionContext::new(
14442                CompletionActor::DaemonSettle,
14443                None,
14444                dir.path(),
14445                &middle,
14446            ));
14447            queue.put(&mut middle).unwrap();
14448            resolve_blockers(&queue, &questions);
14449            let after = queue.get(&waiting.id).unwrap();
14450            assert_eq!(after.status, TaskStatus::Queued);
14451            assert!(after.blocked_by.is_empty());
14452            assert_eq!(after.instruction, waiting.instruction);
14453        }
14454    }
14455
14456    #[test]
14457    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
14458        for future_schema in [false, true] {
14459            let name = "20261013-193611-ca5b";
14460            let mut future = task();
14461            future.id = name.into();
14462            future.schema = crate::queue::SCHEMA + 1;
14463            let contents = if future_schema {
14464                serde_json::to_string(&future).unwrap()
14465            } else {
14466                "corrupt".into()
14467            };
14468            let dir = tempfile::tempdir().unwrap();
14469            let queue = Queue::at(dir.path().join("queue"));
14470            let questions = ask::Questions::at(dir.path().join("questions"));
14471            let mut waiting = task();
14472            waiting.id = "20261013-202849-ee37".into();
14473            waiting.block(vec!["ca5b".into()], None);
14474            queue.put(&mut waiting).unwrap();
14475            std::fs::write(queue.path_of(name), contents).unwrap();
14476            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
14477            assert!(
14478                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
14479            );
14480            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14481            assert!(report.asked.is_empty());
14482            resolve_blockers(&queue, &questions);
14483            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14484            assert!(questions.list().is_empty());
14485        }
14486        let dir = tempfile::tempdir().unwrap();
14487        let queue = Queue::at(dir.path().join("queue"));
14488        let questions = ask::Questions::at(dir.path().join("questions"));
14489        let mut waiting = task();
14490        waiting.id = "20261013-202849-ee37".into();
14491        waiting.block(vec!["ca5b".into()], None);
14492        queue.put(&mut waiting).unwrap();
14493        let mut done = task();
14494        done.id = "20261013-193611-ca5b".into();
14495        done.succeed(CompletionContext::new(
14496            CompletionActor::Cli,
14497            None,
14498            dir.path(),
14499            &done,
14500        ));
14501        queue.put(&mut done).unwrap();
14502        // An unreadable second match must not disappear from uniqueness
14503        // checks just because Queue::list skips it.
14504        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
14505        assert!(queue.get("ca5b").is_err());
14506        assert_eq!(
14507            crate::queue::dependency(&queue, &questions, "ca5b"),
14508            crate::queue::Dependency::Ambiguous
14509        );
14510        resolve_blockers(&queue, &questions);
14511        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
14512        assert!(report.asked.is_empty());
14513        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
14514        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
14515    }
14516
14517    #[test]
14518    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
14519        for held in [false, true] {
14520            for question in [false, true] {
14521                for reference in ["ca5b", "20261013-193611-ca5b"] {
14522                    let dir = tempfile::tempdir().unwrap();
14523                    let queue = Queue::at(dir.path().join("queue"));
14524                    let questions = ask::Questions::at(dir.path().join("questions"));
14525                    let mut prerequisite = task();
14526                    prerequisite.id = "20261013-193611-ca5b".into();
14527                    prerequisite.start("existing-run".into());
14528                    queue.put(&mut prerequisite).unwrap();
14529                    let mut waiting = task();
14530                    waiting.id = "20261013-202849-ee37".into();
14531                    if held {
14532                        waiting.hold_machine(Some("waiting for separate consent".into()));
14533                    }
14534                    queue.put(&mut waiting).unwrap();
14535                    let reason = "Deleting saved data requires separate owner consent";
14536                    crate::conduct::apply(
14537                        &queue,
14538                        &questions,
14539                        &crate::conduct::Verdict {
14540                            decisions: vec![crate::conduct::Decision {
14541                                id: waiting.id.clone(),
14542                                blocked_by: vec![reference.into()],
14543                                question: question.then(|| "May the saved data be deleted?".into()),
14544                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
14545                                reason: Some(reason.into()),
14546                                ..crate::conduct::Decision::default()
14547                            }],
14548                        },
14549                    )
14550                    .unwrap();
14551                    let before = queue.get(&waiting.id).unwrap();
14552                    if question {
14553                        assert_eq!(before.status, TaskStatus::Blocked);
14554                        let q = questions.get(&before.blocked_by[0]).unwrap();
14555                        assert_eq!(q.summary, "May the saved data be deleted?");
14556                        assert!(q.status.open());
14557                    } else {
14558                        assert_eq!(before.status, TaskStatus::Held);
14559                        let recorded_reason = before.hold_reason.as_deref().unwrap();
14560                        assert!(recorded_reason.starts_with(reason));
14561                        if held {
14562                            assert!(recorded_reason.contains("waiting for separate consent"));
14563                        }
14564                    }
14565                    prerequisite.succeed(CompletionContext::new(
14566                        CompletionActor::DaemonSettle,
14567                        None,
14568                        dir.path(),
14569                        &prerequisite,
14570                    ));
14571                    queue.put(&mut prerequisite).unwrap();
14572                    resolve_blockers(&queue, &questions);
14573                    let after = queue.get(&waiting.id).unwrap();
14574                    assert_eq!(after.status, before.status);
14575                    assert_eq!(after.blocked_by, before.blocked_by);
14576                    assert_eq!(after.hold_reason, before.hold_reason);
14577                    assert_eq!(after.instruction, waiting.instruction);
14578                    if question {
14579                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
14580                    }
14581                    assert!(
14582                        queue.next_runnable().is_none(),
14583                        "dependency completion is not consent"
14584                    );
14585                }
14586            }
14587        }
14588    }
14589
14590    #[test]
14591    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
14592        let dir = tempfile::tempdir().unwrap();
14593        let queue = Queue::at(dir.path().join("queue"));
14594        let questions = ask::Questions::at(dir.path().join("questions"));
14595
14596        let mut dep = task();
14597        dep.id = "20260101-000001-dep0".to_owned();
14598        dep.succeed(CompletionContext::new(
14599            CompletionActor::DaemonSettle,
14600            None,
14601            dir.path(),
14602            &dep,
14603        ));
14604        queue.put(&mut dep).unwrap();
14605
14606        let mut still_going = task();
14607        still_going.id = "20260101-000002-dep1".to_owned();
14608        queue.put(&mut still_going).unwrap();
14609
14610        let mut blocked = task();
14611        blocked.id = "20260101-000003-main".to_owned();
14612        blocked.block(
14613            vec![dep.id.clone(), still_going.id.clone()],
14614            Some("waits on both".to_owned()),
14615        );
14616        queue.put(&mut blocked).unwrap();
14617
14618        resolve_blockers(&queue, &questions);
14619
14620        let after = queue.get(&blocked.id).unwrap();
14621        assert_eq!(
14622            after.status,
14623            TaskStatus::Blocked,
14624            "one dependency is still outstanding"
14625        );
14626        assert_eq!(after.blocked_by, [still_going.id.clone()]);
14627    }
14628
14629    #[test]
14630    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
14631        let dir = tempfile::tempdir().unwrap();
14632        let queue = Queue::at(dir.path().join("queue"));
14633        let questions = ask::Questions::at(dir.path().join("questions"));
14634
14635        let mut q = crate::ask::Question::new(
14636            "20260101-000001-main".to_owned(),
14637            crate::conduct::NODE.to_owned(),
14638            "conduct".to_owned(),
14639            "Which backend?".to_owned(),
14640            String::new(),
14641            Vec::new(),
14642        );
14643        questions.put(&mut q).unwrap();
14644        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
14645            .unwrap();
14646        questions.put(&mut q).unwrap();
14647
14648        let mut blocked = task();
14649        blocked.id = "20260101-000001-main".to_owned();
14650        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
14651        queue.put(&mut blocked).unwrap();
14652
14653        resolve_blockers(&queue, &questions);
14654
14655        let after = queue.get(&blocked.id).unwrap();
14656        assert_eq!(
14657            after.status,
14658            TaskStatus::Queued,
14659            "the only blocker resolved"
14660        );
14661        assert_eq!(after.answers.len(), 1);
14662        assert_eq!(after.answers[0].question, "Which backend?");
14663        assert_eq!(after.answers[0].answer, "SQLite");
14664
14665        // And the run this task starts next is told about it.
14666        let instruction = instruction_for(&after);
14667        assert!(instruction.contains("Which backend?"));
14668        assert!(instruction.contains("SQLite"));
14669    }
14670
14671    #[test]
14672    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
14673        let dir = tempfile::tempdir().unwrap();
14674        let queue = Queue::at(dir.path().join("queue"));
14675        let questions = ask::Questions::at(dir.path().join("questions"));
14676
14677        let mut q = crate::ask::Question::new(
14678            "20260101-000001-main".to_owned(),
14679            crate::conduct::NODE.to_owned(),
14680            "conduct".to_owned(),
14681            "Is the setup done?".to_owned(),
14682            String::new(),
14683            Vec::new(),
14684        );
14685        q.abandon("no answer within 60s of asking");
14686        questions.put(&mut q).unwrap();
14687
14688        let mut blocked = task();
14689        blocked.id = "20260101-000001-main".to_owned();
14690        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
14691        queue.put(&mut blocked).unwrap();
14692
14693        resolve_blockers(&queue, &questions);
14694
14695        let after = queue.get(&blocked.id).unwrap();
14696        assert_eq!(
14697            after.status,
14698            TaskStatus::Held,
14699            "never left blocked on nothing"
14700        );
14701        assert!(!after.operator_held(), "a machine hold, for triage");
14702        assert!(
14703            after
14704                .hold_reason
14705                .as_deref()
14706                .unwrap_or_default()
14707                .contains("went unanswered")
14708        );
14709    }
14710
14711    #[test]
14712    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
14713        // Reproduces the reported bug (task 3958): a task held out of
14714        // attempts, blocked on a `crate::conduct` follow-up question, must
14715        // come back `held` once that question is answered - never `queued`,
14716        // whatever the answer said - or it silently re-enters the
14717        // competition queue with its attempts already exhausted.
14718        let dir = tempfile::tempdir().unwrap();
14719        let queue = Queue::at(dir.path().join("queue"));
14720        let questions = ask::Questions::at(dir.path().join("questions"));
14721
14722        let mut q = crate::ask::Question::new(
14723            "20260101-000001-main".to_owned(),
14724            crate::conduct::NODE.to_owned(),
14725            "conduct".to_owned(),
14726            "How should this be handled?".to_owned(),
14727            String::new(),
14728            Vec::new(),
14729        );
14730        questions.put(&mut q).unwrap();
14731        q.answer(crate::ask::Answer::Text(
14732            "leave it held, a human will look at it later".to_owned(),
14733        ))
14734        .unwrap();
14735        questions.put(&mut q).unwrap();
14736
14737        let mut held = task();
14738        held.id = "20260101-000001-main".to_owned();
14739        held.hold_machine(Some("out of attempts".to_owned()));
14740        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
14741        queue.put(&mut held).unwrap();
14742
14743        resolve_blockers(&queue, &questions);
14744
14745        let after = queue.get(&held.id).unwrap();
14746        assert_eq!(after.status, TaskStatus::Held);
14747        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
14748        assert_eq!(
14749            after.answers[0].answer,
14750            "leave it held, a human will look at it later"
14751        );
14752    }
14753
14754    #[test]
14755    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
14756        let dir = tempfile::tempdir().unwrap();
14757        let queue = Queue::at(dir.path().join("queue"));
14758        let questions = ask::Questions::at(dir.path().join("questions"));
14759        let mut dep = task();
14760        dep.id = "20260101-000001-gone".to_owned();
14761        queue.put(&mut dep).unwrap();
14762        let mut blocked = task();
14763        blocked.id = "20260101-000003-main".to_owned();
14764        blocked.block(vec![dep.id.clone()], None);
14765        queue.put(&mut blocked).unwrap();
14766
14767        // Claimed, so `remove` cannot rewrite it and the resolver must.
14768        let claim = queue.claim(&blocked.id).unwrap();
14769        queue.remove(&dep.id, false, &questions).unwrap();
14770        drop(claim);
14771        resolve_blockers(&queue, &questions);
14772
14773        let after = queue.get(&blocked.id).unwrap();
14774        assert_eq!(after.status, TaskStatus::Queued);
14775        assert!(after.blocked_by.is_empty());
14776    }
14777
14778    #[test]
14779    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
14780        // Reproduces the reported bug: a task blocked on a task id that was
14781        // removed (`magi task rm`, or deleted by hand) can never see that id
14782        // reach `Done`, so the ordinary per-id loop has nothing to notice and
14783        // would otherwise leave the task `blocked` forever with no way for an
14784        // operator to find out why.
14785        let dir = tempfile::tempdir().unwrap();
14786        let queue = Queue::at(dir.path().join("queue"));
14787        let questions = ask::Questions::at(dir.path().join("questions"));
14788
14789        let mut still_going = task();
14790        still_going.id = "20260101-000002-dep1".to_owned();
14791        queue.put(&mut still_going).unwrap();
14792
14793        let mut blocked = task();
14794        blocked.id = "20260101-000003-main".to_owned();
14795        blocked.block(
14796            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
14797            Some("waits on both".to_owned()),
14798        );
14799        queue.put(&mut blocked).unwrap();
14800
14801        resolve_blockers(&queue, &questions);
14802
14803        let after = queue.get(&blocked.id).unwrap();
14804        assert_eq!(
14805            after.status,
14806            TaskStatus::Held,
14807            "a missing dependency must not leave the task blocked forever"
14808        );
14809        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
14810        assert!(after.blocked_by.is_empty());
14811        let reason = after.hold_reason.as_deref().unwrap_or_default();
14812        assert!(
14813            reason.contains("20260101-000001-gone"),
14814            "the missing id must be named so an operator can tell what happened: {reason}"
14815        );
14816        assert!(
14817            reason.contains(&still_going.id),
14818            "the still-valid dependency must not silently vanish from the record: {reason}"
14819        );
14820    }
14821
14822    #[test]
14823    fn instruction_for_is_unchanged_without_any_answers() {
14824        let t = task();
14825        assert_eq!(instruction_for(&t), t.instruction);
14826    }
14827
14828    #[test]
14829    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
14830        let dir = tempfile::tempdir().unwrap();
14831        let q = Queue::at(dir.path().join("queue"));
14832        let src = dir.path().join("shot.png");
14833        std::fs::write(&src, "x").unwrap();
14834        let mut t = task();
14835        q.attach(&mut t, &[src]).unwrap();
14836        let paths = task_attachments(&q, &t).unwrap();
14837        assert_eq!(paths.len(), 1);
14838        assert!(paths[0].is_absolute() && paths[0].is_file());
14839        std::fs::remove_file(&paths[0]).unwrap();
14840        let err = task_attachments(&q, &t).unwrap_err().to_string();
14841        assert!(err.contains("shot.png"), "{err}");
14842    }
14843
14844    #[tokio::test]
14845    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
14846        let dir = tempfile::tempdir().unwrap();
14847        let queue_path = dir.path().join("queue");
14848        let queue = Queue::at(queue_path.clone());
14849        let mut t = task();
14850        t.source = Source::Agent {
14851            run: "originating-chat".into(),
14852            node: crate::queue::CHAT_NODE.into(),
14853        };
14854        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
14855            stage: "config-fetch",
14856            target: "origin/main".into(),
14857        });
14858        record_config_failure(&mut t, &fetch);
14859        t.hold_machine(Some(format!("{fetch:#}")));
14860        let fetch_key = t.chat_notice_due().unwrap();
14861        t.chat_notices.push(fetch_key.clone());
14862        queue.put(&mut t).unwrap();
14863
14864        let queue = Queue::at(queue_path);
14865        let mut t = queue.get(&t.id).unwrap();
14866        let a = dir.path().join("a.toml");
14867        let b = dir.path().join("b.toml");
14868        for (path, text, new_cause) in [
14869            (&a, "[graph", true),
14870            (&a, "[verify", false),
14871            (&a, "[graph]\nimplementers = 'invalid-type'", true),
14872            (&b, "[graph]\nimplementers = 'invalid-type'", true),
14873        ] {
14874            t.release_operator("test", None);
14875            std::fs::write(path, text).unwrap();
14876            let error = Config::discover_fetched(dir.path(), Some(path))
14877                .await
14878                .unwrap_err();
14879            record_config_failure(&mut t, &error);
14880            t.hold_machine(Some(format!("{error:#}")));
14881            let due = t.chat_notice_due();
14882            assert_eq!(due.is_some(), new_cause, "{error:#}");
14883            if let Some(key) = due {
14884                assert_ne!(key, fetch_key);
14885                t.chat_notices.push(key);
14886            }
14887        }
14888        t.succeed(CompletionContext::new(
14889            CompletionActor::DaemonSettle,
14890            None,
14891            dir.path(),
14892            &t,
14893        ));
14894        assert_eq!(
14895            t.chat_notice_due(),
14896            Some(format!(
14897                "done:{}",
14898                t.completion_history.last().unwrap().occurrence
14899            ))
14900        );
14901    }
14902
14903    #[test]
14904    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
14905        let dir = tempfile::tempdir().unwrap();
14906        let queue_path = dir.path().join("queue");
14907        let queue = Queue::at(queue_path.clone());
14908        let mut t = task();
14909        t.source = crate::queue::Source::Agent {
14910            run: "originating-chat".into(),
14911            node: crate::queue::CHAT_NODE.into(),
14912        };
14913        let a = dir.path().join("a.png");
14914        let b = dir.path().join("b.png");
14915        std::fs::write(&a, "a").unwrap();
14916        std::fs::write(&b, "b").unwrap();
14917        queue.attach(&mut t, &[a, b]).unwrap();
14918        let paths = task_attachments(&queue, &t).unwrap();
14919        for path in &paths {
14920            std::fs::remove_file(path).unwrap();
14921        }
14922        let missing = task_attachments(&queue, &t).unwrap_err();
14923        t.attempts += 1;
14924        let reason = missing.to_string();
14925        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14926        let first = t.chat_notice_due().expect("first attachment notice");
14927        t.chat_notices.push(first.clone());
14928        queue.put(&mut t).unwrap();
14929
14930        let queue = Queue::at(queue_path.clone());
14931        let mut t = queue.get(&t.id).unwrap();
14932        assert!(t.chat_notice_due().is_none(), "restart does not replay");
14933        t.release_operator("test", None);
14934        t.attempts += 1;
14935        let missing = task_attachments(&queue, &t).unwrap_err();
14936        t.fail_startup_target(
14937            "startup-attachments",
14938            missing.name,
14939            "same missing attachment with regenerated wording",
14940            1,
14941        );
14942        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
14943
14944        std::fs::write(&paths[0], "restored").unwrap();
14945        t.release_operator("test", None);
14946        t.attempts += 1;
14947        let missing = task_attachments(&queue, &t).unwrap_err();
14948        let reason = missing.to_string();
14949        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
14950        let second = t
14951            .chat_notice_due()
14952            .expect("different attachment must notify");
14953        assert_ne!(first, second);
14954        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
14955    }
14956
14957    #[test]
14958    fn resumed_instruction_is_unchanged_without_any_answers() {
14959        let t = task();
14960        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
14961    }
14962
14963    #[test]
14964    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
14965        let mut t = task();
14966        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14967        // The run's own instruction on disk predates the answer: it is the
14968        // plain original text `Runner::start` saved before the operator was
14969        // ever asked anything.
14970        let old = t.instruction.clone();
14971
14972        let refreshed = resumed_instruction(&old, &t);
14973        assert!(refreshed.starts_with(&old), "the original text is kept");
14974        assert!(refreshed.contains("Which backend?"));
14975        assert!(refreshed.contains("SQLite"));
14976    }
14977
14978    #[test]
14979    fn resumed_instruction_keeps_an_original_answers_heading() {
14980        let mut t = task();
14981        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
14982        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
14983
14984        let refreshed = resumed_instruction(&t.instruction, &t);
14985
14986        assert!(
14987            refreshed.starts_with(&t.instruction),
14988            "an answers heading in the original instruction is not the appended block"
14989        );
14990        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
14991        assert!(refreshed.contains("Which backend?"));
14992        assert!(refreshed.contains("SQLite"));
14993
14994        let repeated = resumed_instruction(&refreshed, &t);
14995        assert_eq!(
14996            repeated, refreshed,
14997            "only the final appended block is refreshed"
14998        );
14999    }
15000
15001    #[test]
15002    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
15003        let mut t = task();
15004        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
15005
15006        // A first resume appends the block; a second resume of the same run,
15007        // with no new answer in between, must reproduce exactly the same
15008        // text rather than appending the block a second time.
15009        let once = resumed_instruction(&t.instruction, &t);
15010        let twice = resumed_instruction(&once, &t);
15011        assert_eq!(once, twice);
15012        assert_eq!(once.matches("Which backend?").count(), 1);
15013
15014        // A later answer replaces the block wholesale rather than growing it.
15015        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
15016        let refreshed = resumed_instruction(&once, &t);
15017        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
15018        assert!(refreshed.contains("Which backend?"));
15019        assert!(refreshed.contains("Which cache?"));
15020    }
15021
15022    #[test]
15023    fn prepare_instruction_covers_all_three_starters() {
15024        let mut t = task();
15025        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
15026
15027        // Start: a fresh run gets the task text plus every answer so far —
15028        // exactly `instruction_for`.
15029        assert_eq!(
15030            prepare_instruction(&Starter::Start, None, &t),
15031            Some(instruction_for(&t))
15032        );
15033
15034        // Resume: the run's prior instruction is refreshed with the answer,
15035        // not discarded and not left stale.
15036        let old = t.instruction.clone();
15037        assert_eq!(
15038            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
15039            Some(resumed_instruction(&old, &t))
15040        );
15041
15042        // Review: a review-only pass builds its own instruction from the
15043        // branch's history in `crate::graph`, with no task statement at all -
15044        // this boundary must leave it alone.
15045        assert_eq!(
15046            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
15047            None
15048        );
15049    }
15050
15051    #[test]
15052    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
15053        assert_eq!(
15054            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
15055            Starter::Review("magi/eba2/A".to_owned())
15056        );
15057    }
15058
15059    #[test]
15060    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
15061        assert_eq!(
15062            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
15063            Starter::Start,
15064            "a vanished review branch must not fall back to resuming the old run either"
15065        );
15066    }
15067
15068    #[test]
15069    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
15070        let mut t = task();
15071        t.start("old-run".to_owned());
15072        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
15073        t.release();
15074        let branch = t.review_branch.take();
15075        assert_eq!(
15076            choose_starter(branch.as_deref(), true, Some("old-run")),
15077            Starter::Review("magi/eba2/A".to_owned()),
15078            "a review wins over resuming the old run"
15079        );
15080    }
15081
15082    #[test]
15083    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
15084        assert_eq!(
15085            choose_starter(None, false, Some("some-run")),
15086            Starter::Resume("some-run".to_owned())
15087        );
15088        assert_eq!(choose_starter(None, false, None), Starter::Start);
15089    }
15090
15091    #[test]
15092    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
15093        let mut released = task();
15094        released.start("stalled-run".to_owned());
15095        released.requeue();
15096        let unfinished = (!released.fresh_start)
15097            .then(|| Some("stalled-run".to_owned()))
15098            .flatten();
15099        assert_eq!(
15100            choose_starter(None, false, unfinished.as_deref()),
15101            Starter::Start,
15102            "release keeps run history but must not resume it"
15103        );
15104        assert_eq!(released.runs, ["stalled-run"]);
15105    }
15106
15107    #[test]
15108    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
15109        let dir = tempfile::tempdir().unwrap();
15110        let queue = Queue::at(dir.path().join("queue"));
15111        let mut state = run_state(RunStatus::Blocked);
15112        state.merge_decision = Some(crate::merge_decision::Decision {
15113            question: "hold-inquiry".into(),
15114            target: crate::merge_decision::Target {
15115                pr: "https://example.test/pull/1".into(),
15116                head: "reviewed-head".into(),
15117                language: "en".into(),
15118            },
15119            choice: land::HOLD.into(),
15120            closed: false,
15121            replacement_run: None,
15122            replacement_pr: None,
15123        });
15124        let mut t = task();
15125        t.start(state.id.clone());
15126        settle_and_diagnose(
15127            &mut t,
15128            Verdict {
15129                status: RunStatus::Blocked,
15130                left_pr: true,
15131                quota_hit: false,
15132                parked: false,
15133                no_viable_candidates: false,
15134            },
15135            "held",
15136            2,
15137            &state,
15138        );
15139        queue.put(&mut t).unwrap();
15140        t.release_operator("chat", None);
15141        t.edit("revised".into(), "revised instruction".into())
15142            .unwrap();
15143        queue.put(&mut t).unwrap();
15144        drop(state);
15145        assert_eq!(
15146            queue
15147                .get(&t.id)
15148                .unwrap()
15149                .decision_effects
15150                .get("hold-inquiry"),
15151            Some(&format!("decision: {}", land::HOLD))
15152        );
15153    }
15154
15155    fn stopped_public_run(status: RunStatus) -> RunState {
15156        let mut state = run_state(status);
15157        state.driver_exited = true;
15158        state.config.graph.land = true;
15159        state.config.graph.review_rounds = 1;
15160        state.reviews = vec![review_round(1)];
15161        state.merge = Some(crate::run::MergeOutcome {
15162            mode: MergeMode::Pr,
15163            ok: false,
15164            detail: "landing stopped".into(),
15165            empty: false,
15166        });
15167        state.pr = Some(crate::run::PrRecord {
15168            url: "https://example.test/pull/1".into(),
15169            number: 1,
15170            state: "open".into(),
15171            checks: "red".into(),
15172            round: 1,
15173            rounds: 1,
15174            red_at_merge: Vec::new(),
15175        });
15176        state
15177    }
15178
15179    #[test]
15180    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
15181        for status in [RunStatus::Blocked, RunStatus::Gating] {
15182            let home = tempfile::tempdir().unwrap();
15183            let mut state = stopped_public_run(status);
15184            state.save_under(home.path()).unwrap();
15185            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
15186            assert!(!exhausted_review_budget(&state));
15187            let mut task = held_task_with(&state.id);
15188            task.release();
15189            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15190            assert_eq!(
15191                choose_starter(None, false, unfinished.as_deref()),
15192                Starter::Resume(state.id.clone())
15193            );
15194            let question = action_question(&state.id, resume_action(&state.id));
15195            assert_eq!(
15196                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15197                    state.clone()
15198                )),
15199                ActionDecision::Resume(state.id.clone())
15200            );
15201            // The control-plane command uses this same preflight before pinning.
15202            assert_eq!(
15203                crate::resume::validate(home.path(), &state.id).unwrap().id,
15204                state.id
15205            );
15206            let queue = Queue::at(home.path().join("queue"));
15207            let mut controlled = Task::new(
15208                "resume land".into(),
15209                state.instruction.clone(),
15210                state.repo.clone(),
15211                Source::Agent {
15212                    run: "talk".into(),
15213                    node: crate::queue::CHAT_NODE.into(),
15214                },
15215            );
15216            controlled.runs.push(state.id.clone());
15217            controlled.hold_machine(Some("land stopped".into()));
15218            queue.put(&mut controlled).unwrap();
15219            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15220            assert_eq!(resumed.status, TaskStatus::Queued);
15221            assert_eq!(
15222                resumed.resume_override.unwrap().pinned_run,
15223                Some(state.id.clone())
15224            );
15225            assert_eq!(resumed.attempts, 0);
15226        }
15227    }
15228
15229    #[test]
15230    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
15231        for review_rounds in [0, 1] {
15232            let home = tempfile::tempdir().unwrap();
15233            let mut state = run_state(RunStatus::Blocked);
15234            state.config.graph.review_rounds = review_rounds;
15235            if review_rounds > 0 {
15236                let mut review = review_round(1);
15237                review.clean = true;
15238                state.reviews = vec![review];
15239            }
15240            state.gate_ran = true;
15241            state.gate = vec![crate::run::CommandOutcome {
15242                command: "verify".into(),
15243                code: Some(1),
15244                output_tail: "gate failed after repair budget exhausted".into(),
15245                duration_ms: 0,
15246                resource_blocked: false,
15247                ..Default::default()
15248            }];
15249            state.save_under(home.path()).unwrap();
15250            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15251            assert!(exhausted_review_budget(&state));
15252            let mut task = held_task_with(&state.id);
15253            task.release();
15254            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
15255            let question = action_question(&state.id, resume_action(&state.id));
15256            assert_ne!(
15257                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15258                    state.clone()
15259                )),
15260                ActionDecision::Resume(state.id.clone())
15261            );
15262            let error = crate::resume::validate(home.path(), &state.id)
15263                .unwrap_err()
15264                .to_string();
15265            assert!(!error.contains("review budget exhausted"), "{error}");
15266            assert!(
15267                error.contains(if review_rounds == 0 {
15268                    "review is disabled"
15269                } else {
15270                    "gate already ran"
15271                }),
15272                "{error}"
15273            );
15274
15275            // An unexecuted gate still has work to do with or without reviews.
15276            state.gate_ran = false;
15277            state.gate.clear();
15278            assert!(!exhausted_review_budget(&state));
15279            assert_eq!(
15280                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
15281                Some(state.id)
15282            );
15283        }
15284    }
15285
15286    #[test]
15287    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
15288        let home = tempfile::tempdir().unwrap();
15289        let mut state = run_state(RunStatus::Blocked);
15290        state.config.graph.review_rounds = 1;
15291        let mut unresolved = review_round(1);
15292        unresolved.blocking = 1;
15293        unresolved.e2e.push(crate::run::CommandOutcome {
15294            command: "verify".into(),
15295            code: Some(1),
15296            output_tail: "previous verification failed".into(),
15297            ..Default::default()
15298        });
15299        state.reviews.push(unresolved);
15300        state.base_sync = Some(crate::run::BaseSync {
15301            tip: "base".into(),
15302            behind: 1,
15303            attempts: 0,
15304            conflict: None,
15305            already_in: None,
15306        });
15307        state.reserve_base_operation("winner", "base");
15308        state.resource_block = Some(crate::run::ResourceBlock {
15309            cause: crate::run::ResourceBlockCause::Other,
15310            node: "rebase".into(),
15311            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
15312            detail: "recording exec failed".into(),
15313            at: jiff::Timestamp::now(),
15314        });
15315        state.save_under(home.path()).unwrap();
15316        assert_eq!(
15317            crate::resume::validate(home.path(), &state.id).unwrap().id,
15318            state.id
15319        );
15320        assert_eq!(
15321            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
15322            crate::repair_budget::legacy::Class::SequencerInfrastructure
15323        );
15324        state.finish_base_operation(None);
15325        state.save_under(home.path()).unwrap();
15326        assert!(crate::resume::validate(home.path(), &state.id).is_err());
15327    }
15328
15329    #[test]
15330    fn resource_blocked_verification_resumes_the_same_run() {
15331        for (kind, stage) in [
15332            ("cache", "clean"),
15333            ("coordination", "clean"),
15334            ("cache", "review-e2e"),
15335            ("coordination", "no-reviews"),
15336            ("coordination", "handoff"),
15337        ] {
15338            let home = tempfile::tempdir().unwrap();
15339            let mut state = run_state(RunStatus::Blocked);
15340            state.config.graph.review_rounds = 1;
15341            let mut review = review_round(1);
15342            review.clean = true;
15343            state.reviews = vec![review];
15344            if stage == "review-e2e" {
15345                let review = &mut state.reviews[0];
15346                review.clean = false;
15347                review.blocking = 1;
15348                review.e2e = vec![crate::run::CommandOutcome {
15349                    command: "verify".into(),
15350                    code: None,
15351                    output_tail: "resource wait expired".into(),
15352                    duration_ms: 0,
15353                    resource_blocked: true,
15354                    ..Default::default()
15355                }];
15356            } else if stage == "no-reviews" {
15357                state.config.graph.review_rounds = 0;
15358                state.reviews.clear();
15359            } else if stage == "handoff" {
15360                // A completed final verification can hand off to the gate
15361                // even when the review still carries contested findings.
15362                let review = &mut state.reviews[0];
15363                review.clean = false;
15364                review.blocking = 1;
15365                review.e2e = vec![crate::run::CommandOutcome {
15366                    command: "verify".into(),
15367                    code: Some(0),
15368                    output_tail: String::new(),
15369                    duration_ms: 0,
15370                    resource_blocked: false,
15371                    ..Default::default()
15372                }];
15373            }
15374            state.gate_ran = false;
15375            state.resource_block = Some(crate::run::ResourceBlock {
15376                cause: crate::run::ResourceBlockCause::Other,
15377                node: if stage == "review-e2e" {
15378                    "review"
15379                } else {
15380                    "gate"
15381                }
15382                .into(),
15383                kind: kind.into(),
15384                detail: "resource wait expired".into(),
15385                at: jiff::Timestamp::now(),
15386            });
15387            state.save_under(home.path()).unwrap();
15388            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
15389            assert!(!exhausted_review_budget(&state));
15390            let mut task = held_task_with(&state.id);
15391            task.release();
15392            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
15393            assert_eq!(
15394                choose_starter(None, false, unfinished.as_deref()),
15395                Starter::Resume(state.id.clone())
15396            );
15397            let question = action_question(&state.id, resume_action(&state.id));
15398            assert_eq!(
15399                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
15400                    state.clone()
15401                )),
15402                ActionDecision::Resume(state.id.clone())
15403            );
15404            assert_eq!(
15405                crate::resume::validate(home.path(), &state.id).unwrap().id,
15406                state.id
15407            );
15408            let queue = Queue::at(home.path().join("queue"));
15409            let mut controlled = Task::new(
15410                "resume verification".into(),
15411                state.instruction.clone(),
15412                state.repo.clone(),
15413                Source::Agent {
15414                    run: "talk".into(),
15415                    node: crate::queue::CHAT_NODE.into(),
15416                },
15417            );
15418            controlled.runs.push(state.id.clone());
15419            controlled.hold_machine(Some("verification resource unavailable".into()));
15420            queue.put(&mut controlled).unwrap();
15421            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
15422            assert_eq!(resumed.status, TaskStatus::Queued);
15423            assert_eq!(
15424                resumed.resume_override.unwrap().pinned_run,
15425                Some(state.id.clone())
15426            );
15427            assert_eq!(resumed.attempts, 0);
15428
15429            // A genuinely unresolved final review still exhausts the budget.
15430            state.config.graph.review_rounds = 1;
15431            let mut unresolved = review_round(1);
15432            unresolved.blocking = 1;
15433            state.reviews = vec![unresolved];
15434            state.resource_block = None;
15435            state.save_under(home.path()).unwrap();
15436            assert!(exhausted_review_budget(&state));
15437            assert!(crate::resume::validate(home.path(), &state.id).is_err());
15438        }
15439    }
15440
15441    #[tokio::test]
15442    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
15443        if !crate::standalone_test(
15444            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
15445        ) {
15446            return;
15447        }
15448        let home = tempfile::tempdir().unwrap();
15449        let mut owner = stopped_public_run(RunStatus::Blocked);
15450        owner.save_under(home.path()).unwrap();
15451        let history = vec![owner.id.clone()];
15452        let repo = owner.repo.clone();
15453        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
15454        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
15455        let initial =
15456            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
15457        assert!(
15458            initial.is_pending(),
15459            "a busy record must not hold or resume the task"
15460        );
15461        owner.retired_to = Some("20260101-000001-bbbb".into());
15462        owner.save_under(home.path()).unwrap();
15463        drop(lock);
15464        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
15465            .await
15466            .expect("ownership lock released")
15467            .expect("read settled owner");
15468        assert!(
15469            result.is_none(),
15470            "the retired owner must not be resumed from a stale read"
15471        );
15472    }
15473
15474    #[tokio::test]
15475    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
15476        if !crate::standalone_test(
15477            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
15478        ) {
15479            return;
15480        }
15481        let home = tempfile::tempdir().unwrap();
15482        let mut owner = stopped_public_run(RunStatus::Blocked);
15483        let repo = tempfile::tempdir().unwrap();
15484        crate::git::git(repo.path(), &["init"]).await.unwrap();
15485        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
15486        owner.id = "20260101-000001-bbbb".into();
15487        owner.save_under(home.path()).unwrap();
15488        let mut successor = run_state(RunStatus::Blocked);
15489        successor.id = "20260101-000002-cccc".into();
15490        successor.save_under(home.path()).unwrap();
15491        let pruned = "20260101-000000-aaaa".to_owned();
15492        let pruned_dir = home.path().join("runs").join(&pruned);
15493        let nonowners = vec![pruned.clone(), successor.id.clone()];
15494        assert!(
15495            public_resume_owner(home.path(), &nonowners, &owner.repo)
15496                .await
15497                .unwrap()
15498                .is_none()
15499        );
15500        assert!(!pruned_dir.exists());
15501
15502        let lock_path = home
15503            .path()
15504            .join("runs")
15505            .join(&successor.id)
15506            .join("pr-owner.lock");
15507        std::fs::remove_file(&lock_path).unwrap();
15508        std::fs::create_dir(&lock_path).unwrap();
15509        let error = public_resume_owner(home.path(), &nonowners, &owner.repo)
15510            .await
15511            .expect_err("an invalid lock path must stop the scan");
15512        assert!(error.downcast_ref::<std::io::Error>().is_some());
15513        std::fs::remove_dir(lock_path).unwrap();
15514
15515        let runs = vec![pruned, owner.id.clone(), successor.id.clone()];
15516        assert_eq!(
15517            public_resume_owner(home.path(), &runs, &owner.repo)
15518                .await
15519                .unwrap()
15520                .unwrap()
15521                .id,
15522            owner.id
15523        );
15524        let subdir = owner.repo.join("nested");
15525        std::fs::create_dir(&subdir).unwrap();
15526        assert_eq!(
15527            public_resume_owner(home.path(), &runs, &subdir)
15528                .await
15529                .unwrap()
15530                .unwrap()
15531                .id,
15532            owner.id
15533        );
15534        #[cfg(unix)]
15535        {
15536            let alias = home.path().join("repo-alias");
15537            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
15538            assert_eq!(
15539                public_resume_owner(home.path(), &runs, &alias.join("nested"))
15540                    .await
15541                    .unwrap()
15542                    .unwrap()
15543                    .id,
15544                owner.id
15545            );
15546        }
15547        let different = tempfile::tempdir().unwrap();
15548        crate::git::git(different.path(), &["init"]).await.unwrap();
15549        assert!(
15550            public_resume_owner(home.path(), &runs, different.path())
15551                .await
15552                .is_err()
15553        );
15554        let mut other_owner = owner.clone();
15555        other_owner.id = "20260101-000003-dddd".into();
15556        other_owner.save_under(home.path()).unwrap();
15557        let mut multiple = runs.clone();
15558        multiple.push(other_owner.id);
15559        assert!(
15560            public_resume_owner(home.path(), &multiple, &owner.repo)
15561                .await
15562                .unwrap_err()
15563                .to_string()
15564                .contains("multiple retained public owners")
15565        );
15566        // Explicit retirement leaves the historical approval on disk but
15567        // removes the predecessor from public-delivery admission.
15568        owner.status = RunStatus::Superseded;
15569        owner.pr.as_mut().unwrap().state = "closed".into();
15570        owner.save_under(home.path()).unwrap();
15571        assert!(
15572            public_resume_owner(home.path(), &runs, &owner.repo)
15573                .await
15574                .unwrap()
15575                .is_none()
15576        );
15577        std::fs::remove_file(
15578            home.path()
15579                .join("runs")
15580                .join(&successor.id)
15581                .join("run.json"),
15582        )
15583        .unwrap();
15584        assert!(
15585            public_resume_owner(home.path(), &runs, &owner.repo)
15586                .await
15587                .is_err()
15588        );
15589    }
15590
15591    #[test]
15592    fn an_ordinary_release_keeps_a_resumable_run_available() {
15593        let mut released = task();
15594        released.start("stalled-run".to_owned());
15595        released.release();
15596        let unfinished = (!released.fresh_start)
15597            .then(|| Some("stalled-run".to_owned()))
15598            .flatten();
15599        assert_eq!(
15600            choose_starter(None, false, unfinished.as_deref()),
15601            Starter::Resume("stalled-run".to_owned()),
15602            "manual release must preserve the normal resume path"
15603        );
15604    }
15605
15606    #[test]
15607    fn resume_refusals_explain_admission_without_changing_task_or_run() {
15608        use crate::handover::{ResumeRefusal, resume_refusal_under};
15609        let home = tempfile::tempdir().unwrap();
15610        let mut exhausted = run_state(RunStatus::Blocked);
15611        exhausted.driver_exited = true;
15612        exhausted.config.graph.review_rounds = 3;
15613        exhausted.reviews = (1..=3).map(review_round).collect();
15614        for refusal in [
15615            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
15616            ResumeRefusal::Status(RunStatus::Ready),
15617            ResumeRefusal::Released("20261022-000000-aaaa".into()),
15618            ResumeRefusal::Retired("retirement-successor".into()),
15619            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
15620        ] {
15621            let mut state = exhausted.clone();
15622            let expected = match refusal {
15623                ResumeRefusal::Status(_) => {
15624                    state.status = RunStatus::Ready;
15625                    "status `ready`"
15626                }
15627                ResumeRefusal::Released(ref target) => {
15628                    state.released_to = Some(target.clone());
15629                    "execution was released"
15630                }
15631                ResumeRefusal::Retired(ref target) => {
15632                    state.retired_to = Some(target.clone());
15633                    "execution was retired"
15634                }
15635                ResumeRefusal::OwnershipTransferred(ref target) => {
15636                    state.pr_taken_over_by = Some(target.clone());
15637                    "PR ownership was transferred"
15638                }
15639                _ => "review budget exhausted (3/3 rounds used)",
15640            };
15641            assert_eq!(
15642                resume_refusal_under(&state, Some(home.path())),
15643                Some(refusal.clone())
15644            );
15645            assert_eq!(
15646                refusal.successor(),
15647                state
15648                    .released_to
15649                    .as_deref()
15650                    .or(state.retired_to.as_deref())
15651                    .or(state.pr_taken_over_by.as_deref())
15652            );
15653            state.save_under(home.path()).unwrap();
15654            let queue = Queue::at(home.path().join("queue"));
15655            let mut task = Task::new(
15656                "retained implementation".into(),
15657                state.instruction.clone(),
15658                state.repo.clone(),
15659                Source::Agent {
15660                    run: "talk".into(),
15661                    node: crate::queue::CHAT_NODE.into(),
15662                },
15663            );
15664            task.runs.push(state.id.clone());
15665            task.hold_machine(Some("stopped".into()));
15666            queue.put(&mut task).unwrap();
15667            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
15668            let before_run = serde_json::to_value(&state).unwrap();
15669            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
15670                .unwrap_err()
15671                .to_string();
15672            assert!(error.contains(expected), "{error}");
15673            assert!(!error.contains("only a stalled or blocked"), "{error}");
15674            if matches!(refusal, ResumeRefusal::Status(_)) {
15675                assert!(
15676                    error.contains("is final; there is nothing left to resume"),
15677                    "{error}"
15678                );
15679            }
15680            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
15681                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
15682                assert!(error.contains("review-only successor with a new review budget"));
15683                assert!(error.contains("does not resume this run"));
15684            }
15685            for target in [
15686                &state.released_to,
15687                &state.retired_to,
15688                &state.pr_taken_over_by,
15689            ]
15690            .into_iter()
15691            .flatten()
15692            {
15693                let short = if state.retired_to.as_ref() == Some(target) {
15694                    target.as_str()
15695                } else {
15696                    crate::run::short_of(target)
15697                };
15698                assert!(
15699                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
15700                    "{error}"
15701                );
15702                if short != target {
15703                    assert!(!error.contains(target), "full successor id leaked: {error}");
15704                }
15705            }
15706            assert_eq!(
15707                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
15708                before_task
15709            );
15710            assert_eq!(
15711                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
15712                    .unwrap(),
15713                before_run
15714            );
15715            let question = action_question(&state.id, resume_action(&state.id));
15716            for phrases in [&PHRASES_EN, &PHRASES_JA] {
15717                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
15718                    RunState::load_under(id, home.path())
15719                });
15720                let ActionDecision::Refuse(detail) = decision else {
15721                    panic!(
15722                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
15723                        state.id,
15724                        home.path().display()
15725                    );
15726                };
15727                assert!(detail.contains(expected), "{detail}");
15728            }
15729        }
15730        // Preserve predicate ordering, while keeping every recorded destination visible.
15731        exhausted.status = RunStatus::Ready;
15732        exhausted.released_to = Some("released".into());
15733        exhausted.retired_to = Some("retired".into());
15734        exhausted.pr_taken_over_by = Some("owner".into());
15735        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
15736        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
15737        let detail = reason.diagnostic(&exhausted);
15738        for target in ["released", "retired", "owner"] {
15739            assert!(detail.contains(&format!("magi show {target}")));
15740        }
15741    }
15742
15743    #[test]
15744    fn resume_action_ignores_question_checkpoints_in_another_home() {
15745        crate::run::pin_test_home();
15746        let home = tempfile::tempdir().unwrap();
15747        let mut state = run_state(RunStatus::Blocked);
15748        // The private directory reserves this fixture's identity even while
15749        // other tests write questions into the process-wide store.
15750        state.id = format!(
15751            "resume-context-{}",
15752            home.path().file_name().unwrap().to_str().unwrap()
15753        );
15754        state.driver_exited = true;
15755        state.config.graph.review_rounds = 1;
15756        state.reviews = vec![review_round(1)];
15757        state.save_under(home.path()).unwrap();
15758        let task = held_task_with(&state.id);
15759        let answer = action_question(&state.id, resume_action(&state.id));
15760        let mut checkpoint = approval_question(&state.id);
15761        let foreign = Questions::open();
15762        foreign.put(&mut checkpoint).unwrap();
15763        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
15764        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15765            RunState::load_under(id, home.path())
15766        });
15767        let matching: Vec<_> = foreign
15768            .list()
15769            .into_iter()
15770            .filter(|q| q.run == state.id && q.status.open())
15771            .collect();
15772        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
15773        assert!(
15774            matches!(decision, ActionDecision::Refuse(_)),
15775            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
15776            state.id,
15777            home.path().display(),
15778            crate::run::test_home().display()
15779        );
15780        assert_eq!(
15781            refusal,
15782            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
15783        );
15784        let local = Questions::at(home.path().join("questions"));
15785        for status in [
15786            ask::QuestionStatus::Open,
15787            ask::QuestionStatus::Answered,
15788            ask::QuestionStatus::Abandoned,
15789        ] {
15790            let mut question = checkpoint.clone();
15791            match status {
15792                ask::QuestionStatus::Open => {}
15793                ask::QuestionStatus::Answered => {
15794                    question
15795                        .answer(ask::Answer::Choice(question.choices[0].clone()))
15796                        .unwrap();
15797                }
15798                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
15799            }
15800            local.put(&mut question).unwrap();
15801            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
15802                RunState::load_under(id, home.path())
15803            });
15804            if status.open() {
15805                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
15806            } else {
15807                assert!(
15808                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
15809                    "status={status:?}, decision={decision:?}"
15810                );
15811            }
15812        }
15813    }
15814
15815    #[test]
15816    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
15817        let home = tempfile::tempdir().unwrap();
15818        let mut state = run_state(RunStatus::Stalled);
15819        state.id = format!(
15820            "resume-driver-{}",
15821            home.path().file_name().unwrap().to_str().unwrap()
15822        );
15823        state.driver_claimed = Some(false);
15824        state.save_under(home.path()).unwrap();
15825        let task = held_task_with(&state.id);
15826        let question = action_question(&state.id, resume_action(&state.id));
15827        let decide = || {
15828            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
15829                RunState::load_under(id, home.path())
15830            })
15831        };
15832        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
15833        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
15834        let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
15835        match decide() {
15836            ActionDecision::Refuse(detail) => {
15837                assert!(
15838                    detail.starts_with("run already has a live driver: "),
15839                    "{detail}"
15840                );
15841                assert!(
15842                    detail.contains(&expected_lock.display().to_string()),
15843                    "{detail}"
15844                );
15845            }
15846            other => panic!("expected live driver refusal, got {other:?}"),
15847        }
15848        drop(lease);
15849        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
15850    }
15851
15852    #[test]
15853    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
15854        let home = tempfile::tempdir().unwrap();
15855        let mut state = run_state(RunStatus::Blocked);
15856        state.driver_exited = true;
15857        state.config.graph.review_rounds = 1;
15858        state.reviews = vec![review_round(1)];
15859        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
15860        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
15861            let mut saved = state.clone();
15862            match checkpoint {
15863                "publication" => saved.pr_publication_pending = true,
15864                "approval" => {
15865                    saved.land_approval = Some(crate::run::LandApproval {
15866                        question: "approval".into(),
15867                        head: "head".into(),
15868                    })
15869                }
15870                "armed" => saved.land_armed_head = Some("head".into()),
15871                "landing" => saved.status = RunStatus::Landing,
15872                _ => {
15873                    let mut question = ask::Question::new(
15874                        saved.id.clone(),
15875                        "review".into(),
15876                        "review-1".into(),
15877                        "continue?".into(),
15878                        String::new(),
15879                        vec!["continue".into()],
15880                    );
15881                    ask::Questions::at(home.path().join("questions"))
15882                        .put(&mut question)
15883                        .unwrap();
15884                }
15885            }
15886            saved.save_under(home.path()).unwrap();
15887            assert!(
15888                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
15889                "{checkpoint}"
15890            );
15891            assert!(
15892                crate::resume::validate(home.path(), &saved.id).is_ok(),
15893                "{checkpoint}"
15894            );
15895        }
15896    }
15897
15898    #[test]
15899    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
15900        let mut state = run_state(RunStatus::Blocked);
15901        state.config.graph.review_rounds = 3;
15902        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
15903        assert!(exhausted_review_budget(&state));
15904
15905        // One round still unused: resuming can still ask a reviewer something.
15906        state.reviews.pop();
15907        assert!(!exhausted_review_budget(&state));
15908
15909        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
15910        // count: only a `Blocked` run re-enters the review loop on resume.
15911        let mut stalled = run_state(RunStatus::Stalled);
15912        stalled.config.graph.review_rounds = 1;
15913        stalled.reviews = vec![review_round(1)];
15914        assert!(!exhausted_review_budget(&stalled));
15915    }
15916
15917    fn review_round(round: usize) -> crate::run::ReviewRound {
15918        crate::run::ReviewRound {
15919            round,
15920            head: "deadbeef".to_owned(),
15921            verified_head: None,
15922            verified_at: None,
15923            reviews: Vec::new(),
15924            e2e: Vec::new(),
15925            verify_retried: false,
15926            e2e_deferred: false,
15927            e2e_defer_reason: None,
15928            fix: None,
15929            blocking: 0,
15930            answered: 1,
15931            expected: 1,
15932            clean: false,
15933            progressed: true,
15934            vote_split: false,
15935            reconsideration: Vec::new(),
15936            verdict: None,
15937        }
15938    }
15939
15940    #[test]
15941    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
15942        let mut run = RunState::new(
15943            PathBuf::from("/repo"),
15944            "main".to_owned(),
15945            "abc1234def".to_owned(),
15946            "add retries".to_owned(),
15947            Config::default(),
15948        );
15949        run.status = RunStatus::Judging;
15950        run.parked = true;
15951        let mut task = Task::new(
15952            "add retries".to_owned(),
15953            "add retries".to_owned(),
15954            PathBuf::from("/repo"),
15955            crate::queue::Source::Human,
15956        );
15957        task.status = TaskStatus::Failed;
15958        task.runs = vec![run.id.clone()];
15959        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
15960        assert!(with(&task, &run), "parked after judging is the case");
15961        let mut parked_task = task.clone();
15962        parked_task.status = TaskStatus::Parked;
15963        assert!(with(&parked_task, &run), "the Parked status is the case");
15964
15965        let mut not_parked = run.clone();
15966        not_parked.parked = false;
15967        not_parked.status = RunStatus::Stalled;
15968        assert!(!with(&task, &not_parked), "a stall is the conductor's");
15969
15970        let mut fresh = task.clone();
15971        fresh.fresh_start = true;
15972        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
15973
15974        let mut review = task.clone();
15975        review.review_branch = Some("magi/x/A".to_owned());
15976        assert!(!with(&review, &run), "review is ranked before resume");
15977
15978        let mut held = task.clone();
15979        held.status = TaskStatus::Held;
15980        assert!(!with(&held, &run), "a hold stays visible to the conductor");
15981
15982        let mut released = run.clone();
15983        released.released_to = Some("20260901-000000-new1".to_owned());
15984        assert!(!with(&task, &released), "nothing left to resume into");
15985
15986        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
15987            "unreadable"
15988        )));
15989    }
15990
15991    #[test]
15992    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
15993        let mut released = RunState::new(
15994            PathBuf::from("/repo"),
15995            "main".to_owned(),
15996            "abc1234def".to_owned(),
15997            "add retries".to_owned(),
15998            Config::default(),
15999        );
16000        released.status = RunStatus::Blocked;
16001        assert_eq!(
16002            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
16003            Some(released.id.clone())
16004        );
16005        released.released_to = Some("20260901-000000-new1".to_owned());
16006        assert_eq!(
16007            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
16008            None,
16009            "there is nothing left to resume it into"
16010        );
16011    }
16012
16013    #[test]
16014    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
16015        // Mirrors the failure this exists to close: a task's last run ended
16016        // `Blocked` with the review budget spent, `crate::conduct` chose
16017        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
16018        // evidence), and without this check `attempt` would go on treating
16019        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
16020        // review loop iterates zero times over an already-spent budget, so
16021        // the resumed run settles right back to `Blocked` having asked nobody
16022        // anything, and `Requeue`'s promised fresh competition never happens.
16023        let mut exhausted = RunState::new(
16024            PathBuf::from("/repo"),
16025            "main".to_owned(),
16026            "abc1234def".to_owned(),
16027            "add retries".to_owned(),
16028            Config::default(),
16029        );
16030        exhausted.status = RunStatus::Blocked;
16031        exhausted.config.graph.review_rounds = 1;
16032        exhausted.reviews = vec![review_round(1)];
16033
16034        assert_eq!(
16035            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
16036            None,
16037            "an exhausted `Blocked` run must not be offered as resumable"
16038        );
16039
16040        // A `Blocked` run with rounds still unused is genuinely worth
16041        // resuming, and must still be found.
16042        let mut has_budget_left = RunState::new(
16043            PathBuf::from("/repo"),
16044            "main".to_owned(),
16045            "abc1234def".to_owned(),
16046            "add retries".to_owned(),
16047            Config::default(),
16048        );
16049        has_budget_left.status = RunStatus::Blocked;
16050        has_budget_left.config.graph.review_rounds = 3;
16051        has_budget_left.reviews = vec![review_round(1)];
16052
16053        assert_eq!(
16054            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
16055                Ok(has_budget_left.clone())
16056            }),
16057            Some(has_budget_left.id.clone())
16058        );
16059    }
16060
16061    #[test]
16062    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
16063        let mut run = RunState::new(
16064            PathBuf::from("/repo"),
16065            "main".to_owned(),
16066            "abc1234def".to_owned(),
16067            "add retries".to_owned(),
16068            Config::default(),
16069        );
16070        run.status = RunStatus::Blocked;
16071        run.config.graph.review_rounds = 1;
16072        run.reviews = vec![review_round(1)];
16073        run.pr_publication_pending = true;
16074        assert_eq!(
16075            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
16076            Some(run.id.clone()),
16077            "a spent review budget must not turn a failed publication into a re-competition"
16078        );
16079    }
16080
16081    #[test]
16082    fn retained_attempt_load_ignores_only_missing_run_directories() {
16083        let home = tempfile::tempdir().unwrap();
16084        let mut run = run_state(RunStatus::Ready);
16085        let dir = home.path().join("runs").join(&run.id);
16086        assert!(
16087            load_retained_attempt(home.path(), &run.id)
16088                .unwrap()
16089                .is_none()
16090        );
16091        run.save_under(home.path()).unwrap();
16092        assert_eq!(
16093            load_retained_attempt(home.path(), &run.id)
16094                .unwrap()
16095                .unwrap()
16096                .id,
16097            run.id
16098        );
16099        std::fs::remove_file(dir.join("run.json")).unwrap();
16100        assert!(load_retained_attempt(home.path(), &run.id).is_err());
16101        std::fs::write(dir.join("run.json"), "invalid").unwrap();
16102        assert!(load_retained_attempt(home.path(), &run.id).is_err());
16103        std::fs::remove_dir_all(&dir).unwrap();
16104        std::fs::write(&dir, "not a directory").unwrap();
16105        assert!(load_retained_attempt(home.path(), &run.id).is_err());
16106    }
16107
16108    #[test]
16109    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
16110        let mut task = Task::new(
16111            "recover work".into(),
16112            "recover work".into(),
16113            PathBuf::from("/repo"),
16114            crate::queue::Source::Human,
16115        );
16116        let mut history = std::collections::BTreeMap::new();
16117        for index in 0..8 {
16118            let mut run = run_state(RunStatus::Blocked);
16119            run.id = format!("20260101-000000-{index:04}");
16120            run.base_commit = format!("upstream-{index}");
16121            // Seven empty newer attempts must not erase the old recovery owner.
16122            if index > 0 {
16123                run.candidates.clear();
16124            }
16125            task.runs.extend([run.id.clone(), run.id.clone()]);
16126            history.insert(run.id.clone(), run);
16127            task.requeue();
16128        }
16129        let check = |task: &Task, starter: &Starter, limit| {
16130            retained_attempt_hold(task, starter, limit, |id| Ok(history.get(id).cloned()))
16131        };
16132        task.runs.push("20260101-000001-aaaa".into());
16133        assert!(
16134            check(&task, &Starter::Start, 8)
16135                .unwrap()
16136                .contains("8 unretired")
16137        );
16138        assert!(check(&task, &Starter::Start, 9).is_none());
16139        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
16140        task.release_operator("owner", None);
16141        assert_eq!(task.attempts, 0);
16142        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
16143        assert!(check(&restored, &Starter::Start, 8).is_some());
16144        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
16145        assert!(check(&restored, &Starter::Start, 0).is_none());
16146    }
16147
16148    #[test]
16149    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
16150        let tmp = tempfile::tempdir().unwrap();
16151        let mut task = Task::new(
16152            "recover selected PR".into(),
16153            "preserve implementation".into(),
16154            tmp.path().join("repo"),
16155            crate::queue::Source::Human,
16156        );
16157        let mut failed = run_state(RunStatus::Failed);
16158        failed.id = "20260101-000000-fail".into();
16159        failed.candidates.clear();
16160        failed.prep_complete = Some(false);
16161        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
16162        failed.startup = Some(crate::run::Startup {
16163            kind: "pr-recovery".into(),
16164            branch: Some("selected-public-head".into()),
16165            stage: "worktree-setup".into(),
16166            complete: false,
16167            failure: Some("setup modified a tracked file and failed".into()),
16168        });
16169        // Setup may fail before a candidate is recorded; its dirty worktree
16170        // still needs protection and consumes the independent retained bound.
16171        let worktree = failed.worktree_root().join("under-review");
16172        std::fs::create_dir_all(&worktree).unwrap();
16173        let retained_edit = worktree.join("implementation");
16174        std::fs::write(&retained_edit, "retained setup edit").unwrap();
16175        task.record_startup_failure(crate::run::StartupFailure {
16176            run: failed.id.clone(),
16177            stage: "worktree-setup".into(),
16178        });
16179        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
16180        assert!(task.runs.is_empty() && task.passes.is_empty());
16181        assert_eq!(task.attempts, 0);
16182        let starter = Starter::Review("selected-public-head".into());
16183        assert!(
16184            retained_attempt_hold(&task, &starter, 1, |_| Ok(Some(failed.clone())))
16185                .unwrap()
16186                .contains("1 unretired")
16187        );
16188        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(Some(failed.clone()))).is_none());
16189        assert!(
16190            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
16191                .unwrap()
16192                .contains("Cannot verify")
16193        );
16194        assert!(
16195            retained_attempt_hold(&task, &starter, 2, |_| Ok(None))
16196                .unwrap()
16197                .contains("Cannot verify")
16198        );
16199        // Older or mixed writers can link the same reservation in both lists.
16200        let mut mixed = task.clone();
16201        mixed.runs.push(failed.id.clone());
16202        mixed
16203            .startup_failures
16204            .push(task.startup_failures[0].clone());
16205        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(Some(failed.clone()))).is_none());
16206        assert!(
16207            retained_attempt_hold(&mixed, &starter, 2, |_| Ok(None))
16208                .unwrap()
16209                .contains("Cannot verify")
16210        );
16211        failed.retired_to = Some("verified-recovery-owner".into());
16212        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(Some(failed.clone()))).is_none());
16213        assert!(
16214            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
16215                panic!("resuming the existing owner must not allocate a new attempt")
16216            })
16217            .is_none()
16218        );
16219        assert_eq!(
16220            std::fs::read_to_string(retained_edit).unwrap(),
16221            "retained setup edit"
16222        );
16223        assert!(task.runs.is_empty() && task.passes.is_empty());
16224        assert_eq!(task.attempts, 0);
16225    }
16226
16227    #[test]
16228    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
16229        let mut task = Task::new(
16230            "recover work".into(),
16231            "recover work".into(),
16232            PathBuf::from("/repo"),
16233            crate::queue::Source::Human,
16234        );
16235        let mut run = run_state(RunStatus::Superseded);
16236        run.candidates.clear();
16237        task.runs.push(run.id.clone());
16238        assert!(
16239            retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(Some(run.clone()))).is_some()
16240        );
16241        run.retired_to = Some("authority".into());
16242        assert!(
16243            retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(Some(run.clone()))).is_none()
16244        );
16245        run.retired_to = None;
16246        run.released_to = Some("authority".into());
16247        assert!(
16248            retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(Some(run.clone()))).is_none()
16249        );
16250        assert!(
16251            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
16252                .unwrap()
16253                .contains("Cannot verify")
16254        );
16255        // Resuming an existing owner needs no new inventory or worktree budget.
16256        assert!(
16257            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
16258                panic!("resume must not load historical attempts")
16259            })
16260            .is_none()
16261        );
16262    }
16263
16264    #[test]
16265    fn retired_resume_requires_a_valid_same_repository_authority() {
16266        let mut source = run_state(RunStatus::Blocked);
16267        let mut empty = run_state(RunStatus::Blocked);
16268        empty.retired_to = Some(source.id.clone());
16269        let runs = vec![source.id.clone(), empty.id.clone()];
16270        let resolve = |source: &RunState, empty: &RunState| {
16271            unfinished_run_with(&runs, "fixture", |id| {
16272                if id == source.id {
16273                    Ok(source.clone())
16274                } else if id == empty.id {
16275                    Ok(empty.clone())
16276                } else {
16277                    bail!("unreadable authority")
16278                }
16279            })
16280        };
16281        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
16282        assert_eq!(
16283            choose_starter(None, false, resolve(&source, &empty).as_deref()),
16284            Starter::Resume(source.id.clone())
16285        );
16286        source.retired_to = Some(empty.id.clone());
16287        assert!(
16288            resolve(&source, &empty).is_none(),
16289            "cycles do not revive obsolete runs"
16290        );
16291        source.retired_to = None;
16292        source.repo = PathBuf::from("/another-repository");
16293        assert!(resolve(&source, &empty).is_none());
16294        source.repo = empty.repo.clone();
16295        source.released_to = Some("later".into());
16296        assert!(resolve(&source, &empty).is_none());
16297        empty.retired_to = Some("unlisted-run".into());
16298        assert!(resolve(&source, &empty).is_none());
16299    }
16300
16301    #[test]
16302    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
16303        // A task whose history holds an *older* run that still looks
16304        // resumable (say, a competition `Runner::review` was started
16305        // alongside after that older run went `Stalled`) and a *newest* run
16306        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
16307        // on this task must mean a fresh competition — falling back to the
16308        // stale, superseded `Stalled` run instead would resurrect history
16309        // nothing asked to revisit and silently defeat the requeue.
16310        let mut older_stalled = RunState::new(
16311            PathBuf::from("/repo"),
16312            "main".to_owned(),
16313            "abc1234def".to_owned(),
16314            "add retries".to_owned(),
16315            Config::default(),
16316        );
16317        older_stalled.status = RunStatus::Stalled;
16318
16319        let mut newest_exhausted = RunState::new(
16320            PathBuf::from("/repo"),
16321            "main".to_owned(),
16322            "abc1234def".to_owned(),
16323            "add retries".to_owned(),
16324            Config::default(),
16325        );
16326        newest_exhausted.status = RunStatus::Blocked;
16327        newest_exhausted.config.graph.review_rounds = 1;
16328        newest_exhausted.reviews = vec![review_round(1)];
16329
16330        assert_eq!(
16331            unfinished_run_with(
16332                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
16333                "t",
16334                |_| Ok(newest_exhausted.clone())
16335            ),
16336            None,
16337            "the newest run is exhausted, so nothing here is worth resuming - \
16338             least of all the older, already-superseded run"
16339        );
16340    }
16341
16342    #[test]
16343    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
16344        assert_eq!(
16345            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
16346                Err(anyhow::anyhow!("fixture is absent"))
16347            }),
16348            None
16349        );
16350    }
16351
16352    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
16353        let mut q = ask::Question::new(
16354            run.to_owned(),
16355            "implement".to_owned(),
16356            "impl-A".to_owned(),
16357            "continue?".to_owned(),
16358            String::new(),
16359            vec!["resume で続行する".to_owned(), "other".to_owned()],
16360        );
16361        q.actions.insert("resume で続行する".to_owned(), action);
16362        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
16363            .unwrap();
16364        q
16365    }
16366
16367    fn held_task_with(run: &str) -> Task {
16368        let mut t = task();
16369        t.runs = vec![run.to_owned()];
16370        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
16371        t
16372    }
16373
16374    fn resume_action(run: &str) -> ask::ChoiceAction {
16375        ask::ChoiceAction::Resume { run: run.into() }
16376    }
16377
16378    #[test]
16379    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
16380        let home = crate::run::test_home();
16381        for parked in [false, true] {
16382            let mut t = task();
16383            t.start("A".into());
16384            t.start("B".into());
16385            assert_eq!(t.runs, vec!["A", "B"]);
16386            t.start("A".into());
16387            let mut resumed = run_state(RunStatus::Blocked);
16388            resumed.id = "A".into();
16389            resumed.parked = parked;
16390            resumed.driver_exited = true;
16391            t.hold_machine(Some("resumed run stopped".into()));
16392            let q = action_question("A", resume_action("A"));
16393            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16394            assert_eq!(
16395                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
16396                    assert_eq!(id, "A");
16397                    Ok(resumed.clone())
16398                }),
16399                ActionDecision::Resume("A".into())
16400            );
16401            assert_eq!(
16402                action_standing(&t, &action_question("B", resume_action("B"))),
16403                ActionStanding::Stale
16404            );
16405            t.release_operator("cli", None);
16406            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
16407                assert_eq!(id, "A");
16408                Ok(resumed.clone())
16409            });
16410            assert_eq!(
16411                choose_starter(None, false, unfinished.as_deref()),
16412                Starter::Resume("A".into())
16413            );
16414            assert_eq!(t.runs, vec!["B", "A"]);
16415        }
16416    }
16417
16418    #[test]
16419    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
16420        let home = crate::run::test_home();
16421        let mut state = crate::land::tests::repair_state(true, true);
16422        state.status = RunStatus::Landing;
16423        state.parked = true;
16424        state.driver_exited = true;
16425        let mut q = ask::Question::new(
16426            state.id.clone(),
16427            land::APPROVAL_NODE.into(),
16428            "land".into(),
16429            "Merge?".into(),
16430            String::new(),
16431            vec![land::APPROVE.into(), land::HOLD.into()],
16432        );
16433        q.id = state.id.clone();
16434        state.land_approval = Some(crate::run::LandApproval {
16435            question: q.id.clone(),
16436            head: "current-head".into(),
16437        });
16438        assert!(land::upgrade_repair_choice(&mut q, &state));
16439        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16440        let mut task = held_task_with(&state.id);
16441        task.status = TaskStatus::Parked;
16442        assert_eq!(
16443            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16444            ActionDecision::Resume(state.id.clone())
16445        );
16446        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16447        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
16448        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
16449        assert_eq!(
16450            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
16451            ActionDecision::Resume(state.id.clone()),
16452            "a repair answer newer than the manual hold resumes the existing owner"
16453        );
16454        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16455        for answered_at in [q.answered_at, None] {
16456            let mut older = q.clone();
16457            older.answered_at = answered_at;
16458            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| Ok(state.clone()));
16459            let ActionDecision::Refuse(reason) = refused else {
16460                panic!("expected an actionable refusal, got {refused:?}");
16461            };
16462            assert!(reason.contains("later operator decision"));
16463            assert!(reason.contains(&format!("magi task release {}", task.id)));
16464        }
16465        let mut revised = state.clone();
16466        crate::instruction_revision_control::adopt_into_run(
16467            &mut revised,
16468            "cli/revision",
16469            "revision-repair",
16470            "new task",
16471            1,
16472            "current-head",
16473            "pr",
16474        );
16475        task.status = TaskStatus::Queued;
16476        assert_eq!(
16477            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(revised.clone())),
16478            ActionDecision::Stale
16479        );
16480        let mut stop = q.clone();
16481        stop.status = ask::QuestionStatus::Open;
16482        stop.answer = None;
16483        let choice = crate::merge_decision::WITHDRAW;
16484        stop.choices.push(choice.into());
16485        stop.actions.insert(choice.into(), resume_action(&state.id));
16486        stop.answer(ask::Answer::Choice(choice.into())).unwrap();
16487        stop.answered_at = q.answered_at;
16488        assert_eq!(
16489            decide_action(&home, &task, &stop, &PHRASES_EN, |_| Ok(revised)),
16490            ActionDecision::Stale
16491        );
16492        task.status = TaskStatus::Parked;
16493        task.operator_decided_at = None;
16494        let mut superseded = state.clone();
16495        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
16496        assert_eq!(
16497            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
16498            ActionDecision::Stale
16499        );
16500        for case in 1..4 {
16501            let mut changed = state.clone();
16502            match case {
16503                1 => changed.status = RunStatus::Blocked,
16504                2 => changed.released_to = Some("new-owner".into()),
16505                _ => changed.land_approval.as_mut().unwrap().head.clear(),
16506            }
16507            assert!(matches!(
16508                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
16509                ActionDecision::Refuse(_)
16510            ));
16511        }
16512        assert!(matches!(
16513            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
16514                "missing owner"
16515            )),
16516            ActionDecision::Refuse(_)
16517        ));
16518        task.runs.push("replacement".into());
16519        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
16520        assert_eq!(
16521            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
16522                "old owner must not load"
16523            )),
16524            ActionDecision::Stale
16525        );
16526    }
16527
16528    #[test]
16529    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
16530        let mut state = crate::land::tests::repair_state(true, true);
16531        state.status = RunStatus::Landing;
16532        state.parked = true;
16533        state.driver_exited = true;
16534        let mut q = ask::Question::new(
16535            state.id.clone(),
16536            land::APPROVAL_NODE.into(),
16537            "land".into(),
16538            "Merge?".into(),
16539            String::new(),
16540            vec![land::APPROVE.into(), land::HOLD.into()],
16541        );
16542        q.id = state.id.clone();
16543        state.land_approval = Some(crate::run::LandApproval {
16544            question: q.id.clone(),
16545            head: "current-head".into(),
16546        });
16547        state.save().unwrap();
16548        land::upgrade_repair_choice(&mut q, &state);
16549        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16550        Questions::open().put(&mut q).unwrap();
16551        let tmp = tempfile::tempdir().unwrap();
16552        let queue = Queue::at(tmp.path().join("queue"));
16553        let mut task = held_task_with(&state.id);
16554        task.status = TaskStatus::Parked;
16555        queue.put(&mut task).unwrap();
16556        let empty = Arc::new(tokio::sync::Semaphore::new(0));
16557        let free = Arc::new(tokio::sync::Semaphore::new(1));
16558        assert!(matches!(
16559            claim_dispatch(&queue, &task, false, &empty, &free),
16560            Err(SkipReason::OrdinaryCapacity)
16561        ));
16562        assert!(matches!(
16563            claim_dispatch(&queue, &task, true, &free, &free),
16564            Err(SkipReason::CoolingDown)
16565        ));
16566        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
16567        assert!(claim.permit.is_some());
16568        assert!(matches!(
16569            claim_dispatch(&queue, &task, false, &free, &free),
16570            Err(SkipReason::ClaimUnavailable)
16571        ));
16572        drop(claim);
16573        Questions::open()
16574            .update(&q.id, |q| {
16575                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
16576                Ok(())
16577            })
16578            .unwrap();
16579        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
16580        assert!(claim.permit.is_none());
16581        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
16582    }
16583
16584    #[test]
16585    fn decide_action_resumes_only_the_latest_resumable_run() {
16586        let home = crate::run::test_home();
16587        let t = held_task_with("r1");
16588        let q = action_question("r1", resume_action("r1"));
16589        let load = |s: RunState| move |_: &str| Ok(s);
16590        assert_eq!(
16591            decide_action(
16592                &home,
16593                &t,
16594                &q,
16595                &PHRASES_EN,
16596                load(run_state(RunStatus::Blocked))
16597            ),
16598            ActionDecision::Resume("r1".into())
16599        );
16600        // Not the latest run of the task.
16601        let q_other = action_question("r1", resume_action("r0"));
16602        assert!(matches!(
16603            decide_action(
16604                &home,
16605                &t,
16606                &q_other,
16607                &PHRASES_EN,
16608                load(run_state(RunStatus::Blocked))
16609            ),
16610            ActionDecision::Refuse(_)
16611        ));
16612        // A finished run cannot make progress.
16613        assert!(matches!(
16614            decide_action(
16615                &home,
16616                &t,
16617                &q,
16618                &PHRASES_EN,
16619                load(run_state(RunStatus::Ready))
16620            ),
16621            ActionDecision::Refuse(_)
16622        ));
16623        // A released one either.
16624        let mut released = run_state(RunStatus::Blocked);
16625        released.released_to = Some("elsewhere".into());
16626        assert!(matches!(
16627            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
16628            ActionDecision::Refuse(_)
16629        ));
16630        // Unreadable state is a refusal, never a fresh competition.
16631        assert!(matches!(
16632            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
16633            ActionDecision::Refuse(_)
16634        ));
16635    }
16636
16637    #[test]
16638    fn decide_action_ignores_a_question_about_an_earlier_run() {
16639        let home = crate::run::test_home();
16640        let mut t = held_task_with("r1");
16641        t.runs.push("r2".to_owned());
16642        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16643        assert_eq!(
16644            decide_action(
16645                &home,
16646                &t,
16647                &action_question("r1", ask::ChoiceAction::Done),
16648                &PHRASES_EN,
16649                never
16650            ),
16651            ActionDecision::Stale
16652        );
16653    }
16654
16655    #[test]
16656    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
16657        let home = crate::run::test_home();
16658        let mut t = held_task_with("r1");
16659        let never = |_: &str| -> Result<RunState> { bail!("not read") };
16660        assert_eq!(
16661            decide_action(
16662                &home,
16663                &t,
16664                &action_question("r1", ask::ChoiceAction::Requeue),
16665                &PHRASES_EN,
16666                never
16667            ),
16668            ActionDecision::Requeue
16669        );
16670        let done_q = action_question("r1", ask::ChoiceAction::Done);
16671        assert_eq!(
16672            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16673            ActionDecision::Done
16674        );
16675        t.mark_action_applied(&done_q.id);
16676        assert_eq!(
16677            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
16678            ActionDecision::Skip
16679        );
16680
16681        // A plain answer (no action for that label) does nothing.
16682        let mut plain = action_question("r1", ask::ChoiceAction::Done);
16683        plain.actions.clear();
16684        assert_eq!(
16685            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
16686            ActionDecision::Skip
16687        );
16688        // A running task is left alone.
16689        let mut running = held_task_with("r1");
16690        running.status = TaskStatus::Running;
16691        assert_eq!(
16692            decide_action(
16693                &home,
16694                &running,
16695                &action_question("r1", ask::ChoiceAction::Done),
16696                &PHRASES_EN,
16697                never
16698            ),
16699            ActionDecision::Skip
16700        );
16701    }
16702
16703    #[test]
16704    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
16705        crate::run::pin_test_home();
16706        for legacy in [false, true] {
16707            let dir = tempfile::tempdir().unwrap();
16708            let queue = Queue::at(dir.path().join("queue"));
16709            let questions = Questions::at(dir.path().join("questions"));
16710            let run = "20260101-000000-hold";
16711            let mut task = held_task_with(run);
16712            task.status = TaskStatus::Parked;
16713            let mut q = ask::Question::new(
16714                run.into(),
16715                land::APPROVAL_NODE.into(),
16716                "land".into(),
16717                "Repair?".into(),
16718                String::new(),
16719                vec![land::REPAIR.into()],
16720            );
16721            q.actions.insert(land::REPAIR.into(), resume_action(run));
16722            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
16723            // Deterministically order the answer before the actual manual hold.
16724            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
16725            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
16726            questions.put(&mut q).unwrap();
16727            task.hold_manual(Some("Keep this PR paused".into()));
16728            if legacy {
16729                task.hold_source = None;
16730            }
16731            queue.put(&mut task).unwrap();
16732
16733            apply_task_choice_actions(&queue, &questions, dir.path());
16734            let after = queue.get(&task.id).unwrap();
16735            assert!(after.operator_held());
16736            assert_eq!(after.hold_source, task.hold_source);
16737            assert_eq!(after.operator_decided_at, task.operator_decided_at);
16738            assert_eq!(after.runs, task.runs);
16739            assert_eq!(after.instruction, task.instruction);
16740            assert!(after.resume_override.is_none());
16741            assert!(after.action_applied(&q.id));
16742            let reason = after.hold_reason.as_deref().unwrap();
16743            assert!(reason.starts_with("Keep this PR paused"));
16744            assert!(reason.contains("later operator decision"));
16745            assert!(reason.contains(&format!("magi task release {}", task.id)));
16746
16747            for recovery in [
16748                crate::conduct::Recovery::Review,
16749                crate::conduct::Recovery::Requeue,
16750            ] {
16751                crate::conduct::apply(
16752                    &queue,
16753                    &questions,
16754                    &crate::conduct::Verdict {
16755                        decisions: vec![crate::conduct::Decision {
16756                            id: task.id.clone(),
16757                            recovery: Some(recovery),
16758                            ..Default::default()
16759                        }],
16760                    },
16761                )
16762                .unwrap();
16763            }
16764            // Reconciliation is idempotent, and automatic recovery cannot
16765            // reopen this owner after it observes the rejected repair answer.
16766            apply_task_choice_actions(&queue, &questions, dir.path());
16767            let still_held = queue.get(&task.id).unwrap();
16768            assert!(still_held.operator_held());
16769            assert_eq!(still_held.hold_reason, after.hold_reason);
16770            assert_eq!(still_held.runs, task.runs);
16771            assert!(still_held.review_branch.is_none());
16772            assert!(!still_held.fresh_start);
16773            assert!(queue.next_runnable().is_none());
16774        }
16775    }
16776
16777    #[test]
16778    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
16779        for held in [false, true] {
16780            for retry in [false, true] {
16781                let dir = tempfile::tempdir().unwrap();
16782                let queue = Queue::at(dir.path().join("queue"));
16783                let questions = Questions::at(dir.path().join("questions"));
16784                let home = dir.path().join("home");
16785                let mut t = task();
16786                if held {
16787                    t.hold_machine(Some("driver state unknown".into()));
16788                }
16789                queue.put(&mut t).unwrap();
16790                let verdict = serde_json::from_value(serde_json::json!({
16791                    "decisions": [{
16792                        "id": t.id,
16793                        "question": "Driver state unknown; retry the checks or hold?",
16794                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
16795                        "actions": {
16796                            "daemon: recheck and retry": {"do": "requeue"},
16797                            "daemon: hold the task": {"do": "hold"}
16798                        }
16799                    }]
16800                }))
16801                .unwrap();
16802                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
16803                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16804                let mut q = questions.list().pop().unwrap();
16805                let choice = if retry {
16806                    "daemon: recheck and retry"
16807                } else {
16808                    "daemon: hold the task"
16809                };
16810                assert_eq!(q.actions.len(), 2);
16811                q.answer(ask::Answer::Choice(choice.into())).unwrap();
16812                questions.put(&mut q).unwrap();
16813
16814                // A Web answer does not remove the deputy's fresh lease.
16815                questions.beat(&q.id, ask::WaiterKind::Deputy);
16816                for _ in 0..2 {
16817                    resolve_blockers(&queue, &questions);
16818                    apply_task_choice_actions(&queue, &questions, &home);
16819                    let waiting = queue.get(&t.id).unwrap();
16820                    assert_eq!(waiting.status, TaskStatus::Blocked);
16821                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
16822                    assert!(waiting.answers.is_empty());
16823                    assert!(!waiting.action_applied(&q.id));
16824                    assert!(runnable(&queue).is_empty());
16825                    let free = Arc::new(tokio::sync::Semaphore::new(1));
16826                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
16827                }
16828                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16829
16830                // Releasing the blocker and applying the operation share one save.
16831                resolve_blockers(&queue, &questions);
16832                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
16833                apply_task_choice_actions(&queue, &questions, &home);
16834                let after = queue.get(&t.id).unwrap();
16835                assert_eq!(
16836                    after.status,
16837                    if retry {
16838                        TaskStatus::Queued
16839                    } else {
16840                        TaskStatus::Held
16841                    }
16842                );
16843                assert!(after.action_applied(&q.id));
16844                assert_eq!(after.operator_held(), !retry);
16845                assert_eq!(after.answers.len(), 1);
16846
16847                // A later operator decision must not replay this answer.
16848                let mut changed = after;
16849                if retry {
16850                    changed.hold_manual(Some("later hold".into()));
16851                } else {
16852                    changed.release_operator("test", None);
16853                }
16854                let expected = changed.status;
16855                queue.put(&mut changed).unwrap();
16856                apply_task_choice_actions(&queue, &questions, &home);
16857                assert_eq!(queue.get(&t.id).unwrap().status, expected);
16858            }
16859        }
16860    }
16861
16862    #[test]
16863    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
16864        let dir = tempfile::tempdir().unwrap();
16865        let queue = Queue::at(dir.path().join("queue"));
16866        let questions = Questions::at(dir.path().join("questions"));
16867        let home = dir.path().join("home");
16868        let mut state = run_state(RunStatus::Blocked);
16869        state.id = "20260101-000000-act1".to_owned();
16870        state.save_under(&home).unwrap();
16871
16872        let mut t = held_task_with(&state.id);
16873        queue.put(&mut t).unwrap();
16874        let mut q = action_question(&state.id, resume_action(&state.id));
16875        questions.put(&mut q).unwrap();
16876
16877        apply_task_choice_actions(&queue, &questions, &home);
16878        let after = queue.get(&t.id).unwrap();
16879        assert_eq!(after.status, TaskStatus::Queued);
16880        assert!(!after.fresh_start);
16881        assert!(after.action_applied(&q.id));
16882        let pin = after.resume_override.clone().unwrap();
16883        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
16884        assert!(pin.forced);
16885
16886        // Held again later: the same answer does not release it a second time.
16887        let mut again = queue.get(&t.id).unwrap();
16888        again.hold_machine(Some("later".into()));
16889        queue.put(&mut again).unwrap();
16890        apply_task_choice_actions(&queue, &questions, &home);
16891        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16892    }
16893
16894    #[test]
16895    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
16896        let dir = tempfile::tempdir().unwrap();
16897        let home = dir.path();
16898        let queue = Queue::at(home.join("queue"));
16899        let questions = Questions::at(home.join("questions"));
16900        let mut state = run_state(RunStatus::Blocked);
16901        state.save_under(home).unwrap();
16902        let mut task = held_task_with(&state.id);
16903        queue.put(&mut task).unwrap();
16904        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
16905        questions.put(&mut question).unwrap();
16906
16907        apply_task_choice_actions(&queue, &questions, home);
16908
16909        let after = queue.get(&task.id).unwrap();
16910        assert_eq!(after.status, TaskStatus::Held);
16911        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
16912        assert_eq!(after.runs, task.runs);
16913        assert!(after.completion_history.is_empty());
16914        assert!(!after.decision_effects.contains_key(&question.id));
16915        assert_eq!(
16916            RunState::load_under(&state.id, home).unwrap().status,
16917            RunStatus::Blocked
16918        );
16919    }
16920
16921    #[test]
16922    fn a_delivered_answer_is_still_acted_on_exactly_once() {
16923        let dir = tempfile::tempdir().unwrap();
16924        let queue = Queue::at(dir.path().join("queue"));
16925        let questions = Questions::at(dir.path().join("questions"));
16926        let home = dir.path().join("home");
16927        let mut state = run_state(RunStatus::Blocked);
16928        state.id = "20260101-000000-act2".to_owned();
16929        state.save_under(&home).unwrap();
16930
16931        let mut t = held_task_with(&state.id);
16932        queue.put(&mut t).unwrap();
16933        let mut q = action_question(&state.id, resume_action(&state.id));
16934        q.answer_delivered = true;
16935        questions.put(&mut q).unwrap();
16936
16937        // Delivered, and the agent then died: the task is still held, so the
16938        // chosen action applies.
16939        apply_task_choice_actions(&queue, &questions, &home);
16940        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16941        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
16942
16943        // Held again: the same answer does nothing a second time.
16944        let mut again = queue.get(&t.id).unwrap();
16945        again.hold_machine(Some("later".into()));
16946        queue.put(&mut again).unwrap();
16947        apply_task_choice_actions(&queue, &questions, &home);
16948        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16949    }
16950
16951    #[test]
16952    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
16953        let dir = tempfile::tempdir().unwrap();
16954        let queue = Queue::at(dir.path().join("queue"));
16955        let questions = Questions::at(dir.path().join("questions"));
16956        let home = dir.path().join("home");
16957        let mut state = run_state(RunStatus::Blocked);
16958        state.id = "20260101-000000-act3".to_owned();
16959        state.save_under(&home).unwrap();
16960        let mut t = held_task_with(&state.id);
16961        queue.put(&mut t).unwrap();
16962        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
16963        questions.put(&mut q).unwrap();
16964
16965        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
16966        apply_task_choice_actions(&queue, &questions, &home);
16967        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
16968
16969        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
16970        apply_task_choice_actions(&queue, &questions, &home);
16971        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
16972    }
16973
16974    #[test]
16975    fn action_standing_tells_the_reasons_apart() {
16976        let mut t = held_task_with("r1");
16977        let q = action_question("r1", ask::ChoiceAction::Requeue);
16978        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
16979        let mut plain = q.clone();
16980        plain.actions.clear();
16981        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
16982
16983        // Applied wins over everything, even a running task.
16984        t.mark_action_applied(&q.id);
16985        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
16986
16987        // A newer attempt running: the old question is Stale, not Busy.
16988        let mut t = held_task_with("r1");
16989        t.start("r2".to_owned());
16990        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
16991        // The same question about the latest run just waits.
16992        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
16993        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16994        t.status = TaskStatus::Blocked;
16995        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
16996
16997        // A conductor question is keyed by the task, never stale.
16998        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
16999        c.node = crate::conduct::NODE.to_owned();
17000        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
17001        assert!(!ActionStanding::Busy.daemon_owns());
17002    }
17003
17004    #[test]
17005    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
17006        let dir = tempfile::tempdir().unwrap();
17007        let queue = Queue::at(dir.path().join("queue"));
17008        let questions = Questions::at(dir.path().join("questions"));
17009        let home = dir.path().join("home");
17010        // Execution finished before task settlement; Done is not a discard.
17011        let mut state = run_state(RunStatus::Merged);
17012        state.merge = Some(crate::run::MergeOutcome {
17013            mode: MergeMode::Pr,
17014            ok: true,
17015            detail: "confirmed merge".into(),
17016            empty: false,
17017        });
17018        state.id = "20260101-000000-act4".to_owned();
17019        state.save_under(&home).unwrap();
17020        let mut t = held_task_with(&state.id);
17021        t.status = TaskStatus::Running;
17022        queue.put(&mut t).unwrap();
17023        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
17024        q.cwd = Some(dir.path().display().to_string());
17025        questions.put(&mut q).unwrap();
17026
17027        // While the task runs the daemon will not act, so the waiter still
17028        // delivers the word to the dead asker's seat ...
17029        let running = queue.get(&t.id).unwrap();
17030        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
17031        assert!(matches!(
17032            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
17033            crate::waiter::Action::Deliver(_)
17034        ));
17035        // ... and the daemon waits while the task runs, then applies once.
17036        apply_task_choice_actions(&queue, &questions, &home);
17037        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
17038        let mut back = queue.get(&t.id).unwrap();
17039        back.hold_machine(Some("later".into()));
17040        queue.put(&mut back).unwrap();
17041        apply_task_choice_actions(&queue, &questions, &home);
17042        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
17043        let mut again = queue.get(&t.id).unwrap();
17044        again.hold_machine(Some("again".into()));
17045        queue.put(&mut again).unwrap();
17046        apply_task_choice_actions(&queue, &questions, &home);
17047        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
17048    }
17049
17050    #[test]
17051    fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
17052     {
17053        let dir = tempfile::tempdir().unwrap();
17054        let home = dir.path();
17055        let queue = Queue::at(home.join("queue"));
17056        let mut state = run_state(RunStatus::Blocked);
17057        state.id = "20261125-084544-669a".to_owned();
17058        state.driver_exited = true;
17059        state.driver_pid = None;
17060        state.driver_started_at = None;
17061        state.save_under(home).unwrap();
17062
17063        let mut t = held_task_with(&state.id);
17064        queue.put(&mut t).unwrap();
17065
17066        // Simulate a task worker that finished and was archived to results/,
17067        // while daemon.json still has a fresh heartbeat referencing that worker.
17068        let worker_id = "fc769e65-0000-4000-8000-000000000001";
17069        let retained_dir = home.join("workers").join("results").join(worker_id);
17070        std::fs::create_dir_all(&retained_dir).unwrap();
17071        let finished_job = crate::worker::Job {
17072            id: worker_id.to_owned(),
17073            sequence: 1,
17074            kind: "task".to_owned(),
17075            key: format!("task:{}", t.id),
17076            payload: serde_json::json!({
17077                "queue": home.join("queue"),
17078                "task": t.id,
17079                "opts": Opts::default(),
17080                "standalone": false,
17081            }),
17082            generation: "a".repeat(64),
17083            version: Some("0.260.0".to_owned()),
17084            status: crate::worker::Status::Finished,
17085            result: Some("completed".to_owned()),
17086            pid: Some(37456),
17087            created_at: 1,
17088            finished_at: Some(2),
17089        };
17090        std::fs::write(
17091            retained_dir.join("job.json"),
17092            serde_json::to_vec(&finished_job).unwrap(),
17093        )
17094        .unwrap();
17095
17096        let now = Timestamp::now();
17097        let mut status = Status::new();
17098        status.updated_at = now;
17099        status.current = vec![Current {
17100            worker: Some(worker_id.to_owned()),
17101            task: t.id.clone(),
17102            run: state.id.clone(),
17103        }];
17104        write_status_to(&home.join("daemon.json"), &status).unwrap();
17105
17106        assert!(
17107            claim_for_run(home, &state.id, now).is_none(),
17108            "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
17109        );
17110        assert!(crate::resume::validate(home, &state.id).is_ok());
17111
17112        // Legacy heartbeat without worker id remains protected.
17113        status.current = vec![Current {
17114            worker: None,
17115            task: t.id.clone(),
17116            run: state.id.clone(),
17117        }];
17118        write_status_to(&home.join("daemon.json"), &status).unwrap();
17119        let legacy_err = crate::resume::validate(home, &state.id)
17120            .unwrap_err()
17121            .to_string();
17122        assert!(
17123            legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
17124            "{legacy_err}"
17125        );
17126        assert!(legacy_err.contains("worker=none"), "{legacy_err}");
17127
17128        // Heartbeat naming a missing/unreadable worker record remains protected.
17129        let missing_id = "fc769e65-0000-4000-8000-000000000002";
17130        status.current = vec![Current {
17131            worker: Some(missing_id.to_owned()),
17132            task: t.id.clone(),
17133            run: state.id.clone(),
17134        }];
17135        write_status_to(&home.join("daemon.json"), &status).unwrap();
17136        let missing_err = crate::resume::validate(home, &state.id)
17137            .unwrap_err()
17138            .to_string();
17139        assert!(
17140            missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
17141            "{missing_err}"
17142        );
17143        assert!(missing_err.contains(missing_id), "{missing_err}");
17144        assert!(missing_err.contains("status=unknown"), "{missing_err}");
17145
17146        // Heartbeat naming a Running (non-terminal) worker whose lease is not held
17147        // still remains protected conservatively until fenced to a terminal status.
17148        let running_id = "fc769e65-0000-4000-8000-000000000003";
17149        let running_dir = home.join("workers").join("jobs").join(running_id);
17150        std::fs::create_dir_all(&running_dir).unwrap();
17151        let running_job = crate::worker::Job {
17152            id: running_id.to_owned(),
17153            status: crate::worker::Status::Running,
17154            pid: Some(42424),
17155            finished_at: None,
17156            result: None,
17157            ..finished_job
17158        };
17159        std::fs::write(
17160            running_dir.join("job.json"),
17161            serde_json::to_vec(&running_job).unwrap(),
17162        )
17163        .unwrap();
17164        std::fs::write(running_dir.join("live.lock"), b"").unwrap();
17165        status.current = vec![Current {
17166            worker: Some(running_id.to_owned()),
17167            task: t.id.clone(),
17168            run: state.id.clone(),
17169        }];
17170        write_status_to(&home.join("daemon.json"), &status).unwrap();
17171        let running_err = crate::resume::validate(home, &state.id)
17172            .unwrap_err()
17173            .to_string();
17174        assert!(
17175            running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
17176            "{running_err}"
17177        );
17178        assert!(running_err.contains(running_id), "{running_err}");
17179        assert!(running_err.contains("pid=42424"), "{running_err}");
17180        assert!(running_err.contains("status=running"), "{running_err}");
17181    }
17182
17183    #[test]
17184    fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
17185        let dir = tempfile::tempdir().unwrap();
17186        let home = dir.path();
17187        let queue = Queue::at(home.join("queue"));
17188        let mut state = run_state(RunStatus::Blocked);
17189        state.id = "20261125-090000-evid".to_owned();
17190        state.driver_exited = true;
17191        state.save_under(home).unwrap();
17192        let mut t = held_task_with(&state.id);
17193        queue.put(&mut t).unwrap();
17194
17195        // 1. Live task worker holding live.lock.
17196        let payload = serde_json::json!({
17197            "queue": home.join("queue"),
17198            "task": t.id,
17199            "opts": Opts::default(),
17200            "standalone": false,
17201        });
17202        let (job, lease) =
17203            crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
17204        let worker_err = crate::resume::validate(home, &state.id)
17205            .unwrap_err()
17206            .to_string();
17207        assert!(
17208            worker_err.starts_with("run already has a live driver: worker claim"),
17209            "{worker_err}"
17210        );
17211        assert!(worker_err.contains(&job.id), "{worker_err}");
17212        assert!(
17213            worker_err.contains(&format!("pid={}", std::process::id())),
17214            "{worker_err}"
17215        );
17216        assert!(worker_err.contains("status=running"), "{worker_err}");
17217        assert!(worker_err.contains("live.lock held"), "{worker_err}");
17218        drop(lease);
17219        std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
17220
17221        // 2. Unfenced Starting worker reservation.
17222        let starting_id = "fc769e65-0000-4000-8000-000000000010";
17223        let starting_dir = home.join("workers").join("jobs").join(starting_id);
17224        std::fs::create_dir_all(&starting_dir).unwrap();
17225        let starting_job = crate::worker::Job {
17226            id: starting_id.to_owned(),
17227            sequence: 2,
17228            kind: "task".to_owned(),
17229            key: format!("task:{}", t.id),
17230            payload: serde_json::json!({
17231                "queue": home.join("queue"),
17232                "task": t.id,
17233                "opts": Opts::default(),
17234                "standalone": false,
17235            }),
17236            generation: "a".repeat(64),
17237            version: None,
17238            status: crate::worker::Status::Starting,
17239            result: None,
17240            pid: None,
17241            created_at: 1,
17242            finished_at: None,
17243        };
17244        std::fs::write(
17245            starting_dir.join("job.json"),
17246            serde_json::to_vec(&starting_job).unwrap(),
17247        )
17248        .unwrap();
17249        let starting_err = crate::resume::validate(home, &state.id)
17250            .unwrap_err()
17251            .to_string();
17252        assert!(
17253            starting_err.starts_with("run already has a live driver: worker claim"),
17254            "{starting_err}"
17255        );
17256        assert!(starting_err.contains(starting_id), "{starting_err}");
17257        assert!(starting_err.contains("status=starting"), "{starting_err}");
17258        assert!(
17259            starting_err.contains("unfenced starting reservation"),
17260            "{starting_err}"
17261        );
17262        std::fs::remove_dir_all(&starting_dir).unwrap();
17263
17264        // 3. Unrelated corrupt worker triggers conservative protection with distinct wording.
17265        let corrupt_id = "bad00000-0000-4000-8000-000000000099";
17266        let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
17267        std::fs::create_dir_all(&corrupt_dir).unwrap();
17268        std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
17269        let store_err = crate::resume::validate(home, &state.id)
17270            .unwrap_err()
17271            .to_string();
17272        assert!(
17273            store_err.starts_with(
17274                "run already has a live driver: worker store observation failed (conservative protection):"
17275            ),
17276            "{store_err}"
17277        );
17278        assert!(store_err.contains(corrupt_id), "{store_err}");
17279        std::fs::remove_dir_all(&corrupt_dir).unwrap();
17280
17281        // 4. Held execution lease (driver.lock path).
17282        state.driver_exited = false;
17283        state.driver_claimed = Some(false);
17284        state.driver_pid = None;
17285        state.driver_started_at = None;
17286        state.save_under(home).unwrap();
17287        let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
17288        let lease_err = crate::resume::validate(home, &state.id)
17289            .unwrap_err()
17290            .to_string();
17291        let lock_path = home.join("runs").join(&state.id).join("driver.lock");
17292        assert!(
17293            lease_err.starts_with("run already has a live driver: execution lease held"),
17294            "{lease_err}"
17295        );
17296        assert!(
17297            lease_err.contains(&lock_path.display().to_string()),
17298            "{lease_err}"
17299        );
17300        drop(exec_lease);
17301
17302        // 5. Live process identity (pid + identity).
17303        let pid = std::process::id();
17304        let identity = crate::proc::process_started_at(pid).expect("current process identity");
17305        state.driver_claimed = None;
17306        state.driver_pid = Some(pid);
17307        state.driver_started_at = Some(identity.clone());
17308        state.save_under(home).unwrap();
17309        let pid_err = crate::resume::validate(home, &state.id)
17310            .unwrap_err()
17311            .to_string();
17312        assert!(
17313            pid_err.starts_with("run already has a live driver: live driver process"),
17314            "{pid_err}"
17315        );
17316        assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
17317        assert!(
17318            pid_err.contains(&format!("identity={identity}")),
17319            "{pid_err}"
17320        );
17321
17322        // decide_action uses the exact same refusal format for process identity too.
17323        let question = action_question(&state.id, resume_action(&state.id));
17324        let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
17325            RunState::load_under(id, home)
17326        });
17327        assert_eq!(decision, ActionDecision::Refuse(pid_err));
17328    }
17329}