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    /// Effective startup capabilities of the question recovery loops.
140    #[serde(default)]
141    pub question_recovery: Option<crate::question_delivery::Recovery>,
142    /// Independent-worker control protocol supported by this scheduler.
143    #[serde(default)]
144    pub worker_protocol: Option<u32>,
145}
146
147impl Status {
148    /// A fresh, idle status for this process.
149    #[must_use]
150    pub fn new() -> Self {
151        let now = Timestamp::now();
152        Self {
153            schema: SCHEMA,
154            pid: std::process::id(),
155            started_at: now,
156            updated_at: now,
157            idle: true,
158            current: Vec::new(),
159            completed: 0,
160            polls: 0,
161            dispatch_wait: None,
162            question_recovery: None,
163            worker_protocol: Some(1),
164        }
165    }
166}
167
168impl Default for Status {
169    fn default() -> Self {
170        Self::new()
171    }
172}
173
174/// How the loop should behave.
175#[derive(Debug, Clone, Serialize, Deserialize)]
176#[serde(default)]
177pub struct Opts {
178    /// Repository used by tasks that name none.
179    pub repo: PathBuf,
180    /// Explicit `magi.toml`, instead of the discovered layer stack.
181    pub config: Option<PathBuf>,
182    /// Queue poll interval.
183    pub poll: Duration,
184    /// Attempts a task gets before it is held for a human.
185    pub max_attempts: usize,
186    /// Drain what is runnable now, then return, instead of waiting for more.
187    pub once: bool,
188    /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
189    pub merge: Option<String>,
190    /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
191    /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
192    /// `None` resolves to [`crate::run::default_worktree_root`] - the
193    /// operator's real `~/wt/<repo>` - the same way a run with no
194    /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
195    /// that does not own that directory (a test, an embedding that manages
196    /// worktrees itself) must set this, or every idle tick reclaims worktrees
197    /// out from under whoever actually does.
198    pub worktrees_root: Option<PathBuf>,
199}
200
201impl Default for Opts {
202    fn default() -> Self {
203        Self {
204            repo: PathBuf::from("."),
205            config: None,
206            poll: POLL,
207            max_attempts: 2,
208            once: false,
209            merge: None,
210            worktrees_root: None,
211        }
212    }
213}
214
215impl Opts {
216    fn absolute(&self) -> Result<Self> {
217        let mut opts = self.clone();
218        opts.repo = std::path::absolute(&opts.repo)?;
219        opts.config = opts
220            .config
221            .as_deref()
222            .map(std::path::absolute)
223            .transpose()?;
224        opts.worktrees_root = opts
225            .worktrees_root
226            .as_deref()
227            .map(std::path::absolute)
228            .transpose()?;
229        Ok(opts)
230    }
231}
232
233/// How many runs a plain `usize` from config may drive concurrently, floored
234/// at one. A `0` in a config file would otherwise stall the loop entirely -
235/// no runnable task could ever start - which is never what an operator who
236/// wrote `0` meant.
237fn max_concurrent(n: usize) -> usize {
238    n.max(1)
239}
240
241/// Where the status file lives.
242#[must_use]
243pub fn status_path() -> PathBuf {
244    crate::run::home().join("daemon.json")
245}
246
247/// Publish the status file for this process.
248pub fn write_status(status: &Status) -> Result<()> {
249    write_status_to(&status_path(), status)
250}
251
252/// Publish a status to an explicit path.
253///
254/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
255/// on every health poll and must never see a half-written one.
256pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
257    if let Some(parent) = path.parent() {
258        std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
259    }
260    let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
261    let tmp = path.with_extension("json.tmp");
262    std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
263    std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
264    Ok(())
265}
266
267/// Delete the status file. Called on the way out so a clean exit reads as
268/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
269pub fn clear_status() {
270    clear_status_at(&status_path());
271}
272
273/// Delete a status file at an explicit path, so the loop's teardown and
274/// [`clear_status`] cannot drift apart: the loop is handed the path it
275/// published to, and a test can watch a temp file disappear.
276fn clear_status_at(path: &Path) {
277    let _ = std::fs::remove_file(path);
278}
279
280/// A cooperative stop, shared with whoever asked the loop to run.
281///
282/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
283/// Ctrl-C listener and the web UI keep others, and every clone points at the
284/// same flag. There is no channel because there is nothing to send — the only
285/// message is "stop", it is idempotent, and a flag cannot be missed by a
286/// receiver that was not listening yet.
287///
288/// A stop ends scheduler dispatch promptly. Its busy snapshot is observational:
289/// detached task workers keep their own lifetimes and ownership after this
290/// handle's scheduler exits.
291#[derive(Debug, Clone, Default)]
292pub struct Stop {
293    /// Set once, never cleared: a stop is not something an operator takes back
294    /// half way through, and a clearable flag would let a start racing a stop
295    /// resurrect a loop that is already unwinding.
296    stopped: Arc<AtomicBool>,
297    /// Live task workers observed by the scheduler's latest dispatch snapshot.
298    busy: Arc<std::sync::atomic::AtomicUsize>,
299    /// Wakes the idle wait. Without this a stop would not be seen until the
300    /// poll interval elapsed, and an operator tapping stop on a phone would
301    /// watch a button do nothing for five seconds.
302    wake: Arc<Notify>,
303    /// Handed to the run in flight, so a stop can also mean "park at the next
304    /// node boundary" instead of "finish the whole competition first".
305    pause: crate::graph::Pause,
306}
307
308impl Stop {
309    /// A stop nobody has asked for yet.
310    #[must_use]
311    pub fn new() -> Self {
312        Self::default()
313    }
314
315    /// Ask the loop to stop. Idempotent, and safe to call before the loop
316    /// starts: the flag is checked before the first poll.
317    pub fn stop(&self) {
318        self.stopped.store(true, Ordering::SeqCst);
319        // `notify_one` rather than `notify_waiters` because the loop may not be
320        // parked yet: this stores a permit, so a wait that registers a moment
321        // later returns at once instead of sleeping out the whole interval.
322        self.wake.notify_one();
323    }
324
325    /// Has a stop been asked for?
326    #[must_use]
327    pub fn stopped(&self) -> bool {
328        self.stopped.load(Ordering::SeqCst)
329    }
330
331    /// Whether a requested scheduler retirement still has an active snapshot.
332    /// Workers continue independently after the scheduler has retired.
333    #[must_use]
334    pub fn finishing(&self) -> bool {
335        self.stopped() && self.busy_now()
336    }
337
338    /// Ask the loop to stop *and* the run in flight to park at its next node
339    /// boundary.
340    ///
341    /// Unlike plain stop, explicit park asks workers to checkpoint at their
342    /// existing safe boundaries. Binary replacement never needs a park.
343    pub fn park(&self, cause: crate::run::ParkCause) {
344        self.pause.park_for(cause);
345        self.stop();
346    }
347
348    /// Has a park been asked for?
349    #[must_use]
350    pub fn parking(&self) -> bool {
351        self.pause.parked()
352    }
353
354    /// The pause handle to give a runner.
355    #[must_use]
356    pub fn pause(&self) -> crate::graph::Pause {
357        self.pause.clone()
358    }
359
360    /// Whether the scheduler's latest snapshot contains active task workers.
361    #[must_use]
362    pub fn busy_now(&self) -> bool {
363        self.busy.load(Ordering::SeqCst) > 0
364    }
365
366    /// Wait out one poll interval, returning early once a stop is asked for.
367    async fn idle(&self, poll: Duration) {
368        tokio::select! {
369            () = tokio::time::sleep(poll) => {}
370            () = self.wake.notified() => {}
371        }
372    }
373}
374
375/// The daemon's published state, read permissively.
376///
377/// This mirrors [`Status`], but is a separate declaration on purpose: every
378/// field defaults, so a status file from an older or newer magi still yields
379/// a usable reading — one this build has never heard of — instead of a parse
380/// error that hides the daemon entirely.
381#[derive(Debug, Clone, Default, Deserialize)]
382#[serde(default)]
383pub struct Reading {
384    /// Format version the daemon claims.
385    pub schema: u32,
386    /// Daemon process id, for an operator who wants to stop it.
387    pub pid: Option<u32>,
388    /// When that process started.
389    pub started_at: Option<Timestamp>,
390    /// Last heartbeat. Absent means the file is unusable, hence not running.
391    pub updated_at: Option<Timestamp>,
392    /// True when the queue had nothing runnable at the last poll.
393    pub idle: bool,
394    /// What the daemon is working on. Empty means idle; more than one entry
395    /// means more than one run is in flight at once.
396    ///
397    /// `deserialize_with` rather than the plain derive: a daemon started
398    /// before this field became a list is still out there writing the old
399    /// shape — a single `{"task":...,"run":...}` object, or its absence —
400    /// on every heartbeat until it is restarted, and a live process reading
401    /// that file during the rollout must still see it as running rather than
402    /// as absent. A bare type change here would fail the whole struct's
403    /// deserialization on a type mismatch, defeating the permissiveness this
404    /// type exists for.
405    #[serde(deserialize_with = "de_current")]
406    pub current: Vec<Current>,
407    /// Tasks this daemon process has finished.
408    pub completed: u64,
409    /// Queue polls this daemon process has made.
410    pub polls: u64,
411    /// Last no-start scan, retaining unknown reason keys from newer writers.
412    pub dispatch_wait: Option<DispatchWait>,
413    /// Effective startup capabilities of the question recovery loops.
414    #[serde(default)]
415    pub question_recovery: Option<crate::question_delivery::Recovery>,
416    /// Independent-worker control protocol, absent on legacy embedded loops.
417    pub worker_protocol: Option<u32>,
418}
419
420/// Accept the old single-`Current`-or-absent shape as well as the current
421/// list, so a reader never has to know which build wrote the file.
422fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
423where
424    D: serde::Deserializer<'de>,
425{
426    #[derive(Deserialize)]
427    #[serde(untagged)]
428    enum Shape {
429        Many(Vec<Current>),
430        One(Current),
431    }
432    Ok(
433        Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
434            Shape::Many(v) => v,
435            Shape::One(c) => vec![c],
436        }),
437    )
438}
439
440impl Reading {
441    /// Seconds since the last heartbeat, or `None` when there has never been
442    /// one.
443    #[must_use]
444    pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
445        self.updated_at
446            .map(|at| (now.as_second() - at.as_second()).max(0))
447    }
448
449    /// Whether the loop counts as running: a heartbeat no older than
450    /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
451    /// progress hours after the daemon that owned it was killed.
452    #[must_use]
453    pub fn running(&self, now: Timestamp) -> bool {
454        self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
455    }
456}
457
458/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
459/// usable there.
460///
461/// Missing, half-written and unparseable all collapse to `None`, because the
462/// only question a reader asks is whether a daemon is alive, and a file it
463/// cannot read is not evidence that one is.
464#[must_use]
465pub fn read_status(home: &Path) -> Option<Reading> {
466    let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
467    serde_json::from_str(&body).ok()
468}
469
470struct ClaimObservation {
471    current: Current,
472    evidence: crate::run::LivenessEvidence,
473}
474
475fn observe_current_work(home: &Path, now: Timestamp) -> Vec<ClaimObservation> {
476    let mut observed: Vec<ClaimObservation> = Vec::new();
477    let reading = read_status(home).filter(|reading| reading.running(now));
478    let daemon_pid = reading.as_ref().and_then(|r| r.pid);
479    let heartbeat_age_secs = reading.as_ref().and_then(|r| r.age_secs(now));
480    if let Some(reading) = reading {
481        for claim in reading.current {
482            let task = (!claim.task.is_empty()).then(|| claim.task.clone());
483            let (worker_pid, worker_status, worker_lookup_error) = match claim.worker.as_deref() {
484                Some(worker_id) => match crate::worker::get(home, worker_id) {
485                    Ok(job)
486                        if matches!(
487                            job.status,
488                            crate::worker::Status::Finished | crate::worker::Status::Failed
489                        ) =>
490                    {
491                        // The worker positively reached a terminal status, so
492                        // this heartbeat snapshot is stale until the next poll.
493                        continue;
494                    }
495                    Ok(job) => (job.pid, Some(job.status), None),
496                    Err(error) => (None, None, Some(format!("{error:#}"))),
497                },
498                None => (None, None, None),
499            };
500            let evidence = crate::run::LivenessEvidence::DaemonHeartbeat {
501                daemon_pid,
502                heartbeat_age_secs,
503                worker_id: claim.worker.clone(),
504                worker_pid,
505                worker_status,
506                worker_lookup_error,
507                task,
508            };
509            observed.push(ClaimObservation {
510                current: claim,
511                evidence,
512            });
513        }
514    }
515    let workers = crate::worker::observe_active_detailed(home).and_then(|jobs| {
516        jobs.into_iter()
517            .filter(|entry| entry.job.kind == "task")
518            .map(|entry| {
519                let job = entry.job;
520                let request: TaskWorker = serde_json::from_value(job.payload).map_err(|_| {
521                    anyhow::anyhow!("invalid task worker payload metadata for worker {}", job.id)
522                })?;
523                let run = Queue::at(request.queue)
524                    .get(&request.task)
525                    .ok()
526                    .and_then(|task| task.execution_runs().last().cloned())
527                    .unwrap_or_default();
528                let task_label = (!request.task.is_empty()).then(|| request.task.clone());
529                let current = Current {
530                    worker: Some(job.id.clone()),
531                    task: request.task,
532                    run,
533                };
534                let evidence = crate::run::LivenessEvidence::WorkerClaim {
535                    worker_id: job.id,
536                    pid: job.pid,
537                    status: job.status,
538                    reason: entry.reason,
539                    task: task_label,
540                    daemon_pid: None,
541                };
542                Ok(ClaimObservation { current, evidence })
543            })
544            .collect::<Result<Vec<_>>>()
545    });
546    match workers {
547        Ok(workers) => {
548            for mut worker in workers {
549                if let Some(existing) = observed.iter_mut().find(|claim| {
550                    claim.current.task == worker.current.task
551                        && claim.current.run == worker.current.run
552                        && claim.current.worker == worker.current.worker
553                }) {
554                    if let crate::run::LivenessEvidence::WorkerClaim {
555                        daemon_pid: ref mut target_daemon_pid,
556                        ..
557                    } = worker.evidence
558                    {
559                        *target_daemon_pid = daemon_pid;
560                    }
561                    existing.evidence = worker.evidence;
562                } else {
563                    observed.push(worker);
564                }
565            }
566        }
567        Err(error) => {
568            // This API gates destructive cleanup. Unknown worker ownership
569            // protects every known task/run instead of pretending it is idle.
570            let detail = format!("{error:#}");
571            tracing::error!("cannot determine active workers: {detail}");
572            let evidence = crate::run::LivenessEvidence::WorkerStoreUnreadable { error: detail };
573            observed.extend(
574                Queue::at(home.join("queue"))
575                    .list()
576                    .into_iter()
577                    .map(|task| ClaimObservation {
578                        current: Current {
579                            worker: None,
580                            task: task.id.clone(),
581                            run: task.execution_runs().last().cloned().unwrap_or_default(),
582                        },
583                        evidence: evidence.clone(),
584                    }),
585            );
586            observed.extend(
587                crate::run::list_ids_in(&home.join("runs"))
588                    .into_iter()
589                    .map(|run| ClaimObservation {
590                        current: Current {
591                            worker: None,
592                            task: String::new(),
593                            run,
594                        },
595                        evidence: evidence.clone(),
596                    }),
597            );
598        }
599    }
600    observed
601}
602
603/// Read-only evidence of runs owned by a live daemon or independent worker.
604///
605/// CLI, sandboxed conversation controls and Web cleanup share this observation.
606/// A stale daemon heartbeat does not invalidate a worker's OS-held lease.
607/// Starting reservations and unknown worker state remain protected; observing
608/// them never creates, reconciles or archives files in the worker store.
609/// Callers interested in one identity use [`is_working_on`] or
610/// [`is_working_on_task`].
611#[must_use]
612pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
613    observe_current_work(home, now)
614        .into_iter()
615        .map(|entry| entry.current)
616        .collect()
617}
618
619/// Structured evidence for a live daemon or worker claim on `run`, if any.
620#[must_use]
621pub fn claim_for_run(
622    home: &Path,
623    run: &str,
624    now: Timestamp,
625) -> Option<crate::run::LivenessEvidence> {
626    observe_current_work(home, now)
627        .into_iter()
628        .find(|entry| entry.current.run == run)
629        .map(|entry| entry.evidence)
630}
631
632/// Whether a live daemon is working on this run at this moment.
633#[must_use]
634pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
635    claim_for_run(home, run, now).is_some()
636}
637
638/// Admission may ignore only this process's confirmed worker reservation.
639/// Keep anonymous/legacy daemon claims and every other worker, even for the
640/// same task. The run's execution lease and process identity are checked by
641/// the caller under the owner lock as well.
642pub(crate) fn is_working_on_other(home: &Path, run: &str, now: Timestamp) -> Result<bool> {
643    Ok(other_claim_for_run(home, run, now)?.is_some())
644}
645
646/// Same exclusion rule as [`is_working_on_other`], returning the concrete claim
647/// evidence when another owner (or conservative protection) claims `run`.
648pub(crate) fn other_claim_for_run(
649    home: &Path,
650    run: &str,
651    now: Timestamp,
652) -> Result<Option<crate::run::LivenessEvidence>> {
653    // A helper or test may inherit an identity from a different run store.
654    // That identity grants no exception here; retain all ownership evidence.
655    let same_home = std::env::var_os("MAGI_WORKER_HOME")
656        .is_some_and(|worker_home| Path::new(&worker_home) == home);
657    let caller = if same_home {
658        crate::worker::current_job(home)?
659    } else {
660        None
661    }
662    .filter(|job| {
663        job.kind == "task"
664            && job.status == crate::worker::Status::Running
665            && job.pid == Some(std::process::id())
666    });
667    let caller_id = caller.as_ref().map(|job| job.id.as_str());
668    Ok(observe_current_work(home, now)
669        .into_iter()
670        .find(|entry| {
671            entry.current.run == run
672                && !(caller_id.is_some() && entry.current.worker.as_deref() == caller_id)
673        })
674        .map(|entry| entry.evidence))
675}
676
677#[cfg(test)]
678fn other_claims_run(claims: &[Current], run: &str, caller: Option<&str>) -> bool {
679    claims
680        .iter()
681        .any(|claim| claim.run == run && !(caller.is_some() && claim.worker.as_deref() == caller))
682}
683
684/// Whether a live daemon is working on a run whose short id is this one.
685///
686/// For a worktree that has no run record to compare against at all -
687/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
688/// id is not available to hand to [`is_working_on`]. The short id is: a run's
689/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
690/// and it is exactly the gap between the daemon claiming a task and
691/// `RunState::new` saving the first `run.json` that this exists to protect -
692/// a run genuinely in flight but invisible to a scan of `runs/`.
693#[must_use]
694pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
695    current_work(home, now)
696        .iter()
697        .any(|c| crate::run::short_of(&c.run) == short)
698}
699
700/// Whether a live daemon is working on this task at this moment.
701#[must_use]
702pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
703    current_work(home, now).iter().any(|c| c.task == task)
704}
705
706/// Remove claim files whose owner is provably dead, or that have simply
707/// outlived `older_than`, and return the task ids swept.
708///
709/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
710/// destructor, and the orphaned `.lock` file would make its task permanently
711/// unclaimable — the backlog would stop for good at exactly the task that was
712/// in flight when the machine went down.
713///
714/// The pid recorded in the lock is the authority whenever it can be read at
715/// all; age is only a fallback for when it cannot be.
716///
717/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
718///   full stop — dead sweeps the lock immediately, regardless of age; alive
719///   protects it, regardless of age. This is what lets a lock be reclaimed in
720///   seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
721///   before this daemon even started, next to a `queued` task, no longer has
722///   to sit for six hours before anything notices its owner is gone.
723/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
724///   falls back to `older_than`, since there is nothing else to check.
725///
726/// Age must never override a *positive* liveness confirmation. `sweep`
727/// polls concurrently with independently running task workers. A worker may
728/// legitimately run longer than `older_than`; its live pid must still protect
729/// its claim. Age alone must never turn that claim into a second task attempt,
730/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
731/// to a second attempt — two `Runner`s writing the same `run.json` and the
732/// same worktree at once. `pid_alive` answering "alive" for anything it
733/// cannot determine (a live process, a pid this build cannot check, one
734/// under another account) is exactly what keeps that path from ever
735/// firing on a guess.
736///
737/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
738/// output unreadable must not be license to guess, and the risk of an
739/// unparseable lock outliving a genuinely dead owner is bounded by an order
740/// of magnitude above any plausible run rather than by a positive check.
741///
742/// Runs on every poll, not only at startup — a daemon up for days must keep
743/// noticing a lock some other, now-dead, daemon left behind just as readily
744/// as one it trips over on the way up.
745pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
746    sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
747}
748
749/// [`sweep_stale_claims`] with its process-query boundary supplied by the
750/// caller. This keeps the lock policy testable where process listing is
751/// unavailable, while production still uses the platform query above.
752fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
753where
754    F: Fn(u32) -> bool,
755{
756    let this_process = std::process::id();
757    let mut swept: Vec<String> = std::fs::read_dir(queue.root())
758        .into_iter()
759        .flatten()
760        .flatten()
761        .map(|e| e.path())
762        .filter(|p| p.extension().is_some_and(|x| x == "lock"))
763        .filter(|p| {
764            match std::fs::read_to_string(p)
765                .ok()
766                .and_then(|body| body.trim().parse::<u32>().ok())
767            {
768                // This process wrote it and is asking the question right
769                // now, so it is definitionally still alive - settled without
770                // spawning a helper process at all.
771                Some(pid) if pid == this_process => false,
772                Some(pid) => !pid_alive(pid),
773                None => p
774                    .metadata()
775                    .and_then(|m| m.modified())
776                    .and_then(|t| t.elapsed().map_err(std::io::Error::other))
777                    .is_ok_and(|age| age >= older_than),
778            }
779        })
780        .filter(|p| std::fs::remove_file(p).is_ok())
781        .filter_map(|p| {
782            p.file_stem()
783                .and_then(|s| s.to_str())
784                .map(std::borrow::ToOwned::to_owned)
785        })
786        .collect();
787    swept.sort_unstable();
788    swept
789}
790
791/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
792/// no live daemon's heartbeat naming it? Deterministic — no model call, and
793/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
794/// shown.
795fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
796    task.status == TaskStatus::Running
797        && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
798        && !is_working_on_task(home, &task.id, now)
799}
800
801/// Every task [`is_stalled`] right now — "止まったタスク" in
802/// `crate::conduct`'s vocabulary.
803fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
804    queue
805        .list()
806        .into_iter()
807        .filter(|t| is_stalled(t, home, now))
808        .collect()
809}
810
811/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
812/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
813/// `Failed`-and-so-also-runnable: a task that already attempted and lost
814/// belongs in [`finished_tasks`], where the question is a recovery, not a
815/// dependency.
816fn queued_tasks(queue: &Queue) -> Vec<Task> {
817    queue
818        .list()
819        .into_iter()
820        .filter(|t| t.status == TaskStatus::Queued)
821        .collect()
822}
823
824/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
825/// タスク" in `crate::conduct`'s vocabulary.
826fn finished_tasks(queue: &Queue) -> Vec<Task> {
827    queue
828        .list()
829        .into_iter()
830        .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
831        .collect()
832}
833
834/// Deterministically resolve `Task::blocked_by`: a dependency task that
835/// reached `Done`, or a question that was answered, is removed — no model
836/// involved, on every poll. An answered question's content is copied onto
837/// the task ([`Task::record_answer`]) before its id is dropped, so it
838/// reaches the next `crate::conduct` prompt and the next run's instruction
839/// (see [`instruction_for`]) rather than only clearing the block.
840///
841/// A `blocked_by` id that names neither an existing task nor an existing
842/// question - `magi task rm` (or an operator by hand) deleted it while this
843/// task was still waiting - is caught before any of that: it can never
844/// become `Done` or `Answered`, so the ordinary loop below would otherwise
845/// leave the task `blocked` forever with nothing to notice. Such a task is
846/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
847/// which puts it in front of `crate::triage::run_once`'s own walk the next
848/// time it runs - see that module's doc for why the choice is "ask a human",
849/// never "assume the missing dependency was satisfied and unblock anyway".
850fn resolve_blockers(queue: &Queue, questions: &Questions) {
851    for listed in queue.list() {
852        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
853            continue;
854        }
855        let Ok(_claim) = queue.claim(&listed.id) else {
856            continue;
857        };
858        let Ok(mut task) = queue.get(&listed.id) else {
859            continue;
860        };
861        if task.status != TaskStatus::Blocked {
862            continue;
863        }
864        // A dependency deleted on purpose is released, not held - and before
865        // the missing check, so a pass that races the delete (or a claim that
866        // made `Queue::remove` skip this task) settles it quietly.
867        let deleted = queue.apply_deleted_blockers(&mut task, questions);
868        if !deleted.is_empty() {
869            record(queue, &mut task);
870            for id in &deleted {
871                queue.note_dependency_deleted(&task, id);
872            }
873            if task.status != TaskStatus::Blocked {
874                continue;
875            }
876        }
877        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
878        if !missing.is_empty() {
879            let language = language_of(&task, Path::new("."));
880            let mut cause = missing.clone();
881            cause.sort();
882            cause.dedup();
883            task.notice_cause(&format!("missing-blockers:{}", cause.join(",")), None, None);
884            task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
885                &task.blocked_by,
886                &missing,
887                &language,
888            )));
889            record(queue, &mut task);
890            continue;
891        }
892        // A conductor question nobody answered in time is retired by the
893        // waiter, and nothing else would ever move the task it blocks.
894        if let Some(q) = task.blocked_by.iter().find_map(|id| {
895            let crate::queue::Dependency::Question(full) =
896                crate::queue::dependency(queue, questions, id)
897            else {
898                return None;
899            };
900            questions.get_for_effects(&full).ok().filter(|q| {
901                q.node == crate::conduct::NODE && q.status == ask::QuestionStatus::Abandoned
902            })
903        }) {
904            let language = language_of(&task, Path::new("."));
905            task.notice_cause(&format!("unanswered-question:{}", q.id), None, None);
906            task.hold_machine(Some(unanswered_question_hold_reason(&q, &language)));
907            record(queue, &mut task);
908            continue;
909        }
910        let mut changed = false;
911        for id in task.blocked_by.clone() {
912            let resolved = crate::queue::dependency(queue, questions, &id);
913            if let crate::queue::Dependency::Task(full) = &resolved {
914                if queue
915                    .get(full)
916                    .is_ok_and(|dep| dep.status == TaskStatus::Done)
917                {
918                    task.unblock(&id);
919                    changed = true;
920                }
921                continue;
922            }
923            if let crate::queue::Dependency::Question(full) = resolved
924                && let Ok(q) = questions.get_for_effects(&full)
925                && q.status == ask::QuestionStatus::Answered
926            {
927                // The action sweep releases conductor blockers atomically
928                // with their selected operation. A fresh deputy lease must
929                // never leave an answered hold temporarily runnable.
930                if q.node == crate::conduct::NODE
931                    && q.chosen_action().is_some()
932                    && !task.action_applied(&q.id)
933                {
934                    continue;
935                }
936                let answer = match &q.answer {
937                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
938                    None => String::new(),
939                };
940                task.record_answer(q.summary.clone(), answer);
941                task.unblock(&id);
942                changed = true;
943            }
944        }
945        if changed {
946            record(queue, &mut task);
947        }
948    }
949}
950
951/// The `hold_reason` of a task whose conductor question went unanswered.
952fn unanswered_question_hold_reason(q: &ask::Question, language: &str) -> String {
953    if crate::lang::is_japanese(language) {
954        format!(
955            "質問 {} 「{}」 に期限内の回答がなく、取り下げられました - `magi task triage` を参照",
956            q.short(),
957            q.summary
958        )
959    } else {
960        format!(
961            "question {} \"{}\" went unanswered and was abandoned - see `magi task triage`",
962            q.short(),
963            q.summary
964        )
965    }
966}
967
968/// Where `q`'s chosen action stands for `task`. `daemon_will_act` is false
969/// for several unrelated reasons, and the waiter must not read them alike.
970#[derive(Debug, Clone, Copy, PartialEq, Eq)]
971pub(crate) enum ActionStanding {
972    /// The answer carries no action: the waiter delivers it as before.
973    NoAction,
974    /// The daemon will apply it (not applied, task idle, current attempt).
975    Pending,
976    /// Already applied (`Task::actions_applied`): the daemon has acted, so
977    /// delivering the word to the old seat would run it beside the new work.
978    Applied,
979    /// The question is about an earlier attempt than the task's latest.
980    Stale,
981    /// The task is running / blocked / done: the daemon defers for now.
982    Busy,
983}
984
985impl ActionStanding {
986    /// The daemon has acted or will act: the waiter must not deliver.
987    pub(crate) fn daemon_owns(self) -> bool {
988        matches!(self, Self::Pending | Self::Applied | Self::Stale)
989    }
990}
991
992/// Classify `q`'s chosen action against `task`. `Stale` is judged before
993/// `Busy`: a question about an earlier attempt must be stopped even while a
994/// newer competition is running.
995pub(crate) fn action_standing(task: &Task, q: &ask::Question) -> ActionStanding {
996    if task.stale_question(q) {
997        ActionStanding::Stale
998    } else if q.chosen_action().is_none() {
999        ActionStanding::NoAction
1000    } else if task.action_applied(&q.id) {
1001        ActionStanding::Applied
1002    } else if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1003        ActionStanding::Stale
1004    } else if matches!(
1005        task.status,
1006        TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1007    ) {
1008        ActionStanding::Busy
1009    } else {
1010        ActionStanding::Pending
1011    }
1012}
1013
1014/// What [`decide_action`] concluded about one answered question.
1015#[derive(Debug, Clone, PartialEq, Eq)]
1016enum ActionDecision {
1017    /// Nothing to do now (no action, already applied, or the task is busy).
1018    Skip,
1019    /// Continue the named run instead of competing again.
1020    Resume(String),
1021    /// Requeue as a fresh competition.
1022    Requeue,
1023    /// Hold the task by explicit operator choice.
1024    Hold,
1025    /// Close the task as done.
1026    Done,
1027    /// The question is about an earlier attempt than the task's latest; it
1028    /// is recorded as handled and changes nothing.
1029    Stale,
1030    /// The action cannot be carried out; hold the task and say why. Never
1031    /// falls back to something else, because the operator chose this one.
1032    Refuse(String),
1033}
1034
1035/// Decide what the choice answered on `q` means for `task`. `load` reads a
1036/// run's state, as with [`unfinished_run_with`]. `home` must name that same
1037/// store for driver leases and question checkpoints.
1038///
1039/// `Resume` only fires on the task's *latest* run, and only while that run
1040/// could actually make progress ([`RunStatus::resumable`], not released, review
1041/// budget left); an answer naming anything else is refused rather than
1042/// reinterpreted as a fresh competition.
1043fn decide_action<F>(
1044    home: &Path,
1045    task: &Task,
1046    q: &ask::Question,
1047    p: &Phrases,
1048    load: F,
1049) -> ActionDecision
1050where
1051    F: FnOnce(&str) -> Result<RunState>,
1052{
1053    if task.stale_question(q) {
1054        return ActionDecision::Stale;
1055    }
1056    let Some(action) = q.chosen_action() else {
1057        return ActionDecision::Skip;
1058    };
1059    if task.action_applied(&q.id)
1060        || matches!(
1061            task.status,
1062            TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
1063        )
1064    {
1065        return ActionDecision::Skip;
1066    }
1067    // A question about an earlier attempt must not act on a newer one. A
1068    // conductor question is keyed by the task id, not a run, so it is exempt.
1069    if q.node != crate::conduct::NODE && task.execution_runs().last() != Some(&q.run) {
1070        return ActionDecision::Stale;
1071    }
1072    let repair = q.node == land::APPROVAL_NODE && q.resolution().as_deref() == Some(land::REPAIR);
1073    let stopping = q.node == land::APPROVAL_NODE
1074        && q.resolution()
1075            .as_deref()
1076            .is_some_and(crate::merge_decision::stops);
1077    // An answer is the owner's decision as of when it was given: a manual hold
1078    // placed before it (even after the question was asked) was seen and
1079    // overruled by it, while a hold or release after it supersedes it.
1080    let decision_at = q.answered_at.unwrap_or(q.asked_at);
1081    if task.operator_decided_at.is_some_and(|at| at > decision_at) {
1082        return if repair || stopping {
1083            ActionDecision::Refuse(format!(
1084                "{} 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 {}`",
1085                if repair { "repair" } else { "stop" },
1086                q.id,
1087                q.run,
1088                task.id
1089            ))
1090        } else {
1091            ActionDecision::Stale
1092        };
1093    }
1094    match action {
1095        a if a.maintenance() => ActionDecision::Skip,
1096        ask::ChoiceAction::RecoverBase { .. }
1097        | ask::ChoiceAction::ResumeRun { .. }
1098        | ask::ChoiceAction::ReleaseTask { .. }
1099        | ask::ChoiceAction::RerunChecks { .. }
1100        | ask::ChoiceAction::AbandonRun { .. } => unreachable!(),
1101        ask::ChoiceAction::Requeue => ActionDecision::Requeue,
1102        ask::ChoiceAction::Hold => ActionDecision::Hold,
1103        ask::ChoiceAction::Done => ActionDecision::Done,
1104        ask::ChoiceAction::Resume { run } => {
1105            if task.execution_runs().last() != Some(run) {
1106                return ActionDecision::Refuse((p.resume_not_latest)(
1107                    q.short(),
1108                    ask::short_id(run),
1109                ));
1110            }
1111            match load(run) {
1112                Ok(s) if stopping => {
1113                    if s.merge_decision.as_ref().is_some_and(|d| d.closed)
1114                        || !s
1115                            .land_approval
1116                            .as_ref()
1117                            .is_some_and(|binding| binding.question == q.id)
1118                    {
1119                        ActionDecision::Stale
1120                    } else if s.liveness_under(home, false) == Liveness::Live {
1121                        ActionDecision::Skip
1122                    } else if s.status == RunStatus::Landing
1123                        && !s.released()
1124                        && s.retired_to.is_none()
1125                    {
1126                        ActionDecision::Resume(run.clone())
1127                    } else {
1128                        ActionDecision::Refuse("Owner stop decision cannot resume its original landing execution; inspect the existing run. No replacement or merge was started.".into())
1129                    }
1130                }
1131                Ok(s)
1132                    if q.node == land::APPROVAL_NODE
1133                        && q.resolution().as_deref() == Some(land::REPAIR) =>
1134                {
1135                    if s.merge_repairs.iter().any(|r| r.question == q.id)
1136                        || s.land_approval.as_ref().is_some_and(|a| a.question != q.id)
1137                    {
1138                        // A live/manual driver already consumed or superseded
1139                        // this answer. Do not hold its fresh approval wait.
1140                        ActionDecision::Stale
1141                    } else if s.liveness_under(home, false) == Liveness::Live {
1142                        ActionDecision::Skip
1143                    } else if s.status != RunStatus::Landing
1144                        || s.released()
1145                        || s.reviews.is_empty()
1146                        || !implementers_match(task, &s)
1147                        || !s
1148                            .land_approval
1149                            .as_ref()
1150                            .is_some_and(|a| a.question == q.id && !a.head.is_empty())
1151                    {
1152                        ActionDecision::Refuse(format!(
1153                            "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",
1154                            q.id, run, run
1155                        ))
1156                    } else {
1157                        ActionDecision::Resume(run.clone())
1158                    }
1159                }
1160                Ok(s) => {
1161                    let assessment = s.assess_liveness_under(home, None, Timestamp::now());
1162                    if assessment.verdict == Liveness::Live {
1163                        ActionDecision::Refuse(assessment.live_driver_refusal())
1164                    } else {
1165                        match crate::handover::resume_refusal_under(&s, Some(home)) {
1166                            None => ActionDecision::Resume(run.clone()),
1167                            Some(reason) => ActionDecision::Refuse((p.resume_cannot_progress)(
1168                                q.short(),
1169                                ask::short_id(run),
1170                                &reason.diagnostic(&s),
1171                            )),
1172                        }
1173                    }
1174                }
1175                Err(e) => ActionDecision::Refuse((p.resume_unreadable)(
1176                    q.short(),
1177                    ask::short_id(run),
1178                    &format!("{e:#}"),
1179                )),
1180            }
1181        }
1182    }
1183}
1184
1185/// The fixed prose the daemon writes into [`Task::last_error`] and
1186/// [`Task::hold_reason`], in the language of `[graph] language`. Same shape as
1187/// `triage::Wording` and `land::Words`: only English and Japanese are
1188/// translated, anything else falls back to English.
1189///
1190/// Rendered when the reason is *generated*, so a reason keeps the language it
1191/// was written in if the setting changes later. The notification frame
1192/// (`Task <id> is held:`) is not here and stays English.
1193///
1194/// Deliberately **not** translated, because other code reads them back by
1195/// string: the disk gate prefixes (`triage::is_disk_hold`), `out of attempts`
1196/// and `gate red`. IDs, node names, paths and external error text are embedded
1197/// as they are.
1198struct Phrases {
1199    /// `{}` = status label, then the detail.
1200    graph_stopped: fn(&str, &str) -> String,
1201    quorum_lost: &'static str,
1202    /// Followed by the seats' names.
1203    quota_took_out: &'static str,
1204    /// Followed by the status label.
1205    run_ended: &'static str,
1206    /// Followed by the question's short id.
1207    waiting_for_answer: &'static str,
1208    recovered_running: &'static str,
1209    no_run_to_recover: &'static str,
1210    could_not_start: &'static str,
1211    resume_not_latest: fn(&str, &str) -> String,
1212    resume_cannot_progress: fn(&str, &str, &str) -> String,
1213    resume_unreadable: fn(&str, &str, &str) -> String,
1214    /// A takeover refusal: the operator-facing text. English is the error's own
1215    /// `Display`; a translation keeps the machine detail apart in parentheses.
1216    handover_refused: fn(&crate::handover::Refused) -> String,
1217    /// Appended to a refused handover's hold reason (leading space included).
1218    handover_hint: &'static str,
1219    /// (seats that never answered, review rounds) for the review loop's
1220    /// "refusing to call it clean" stop.
1221    reviewers_never_answered: fn(usize, usize) -> String,
1222}
1223
1224const PHRASES_EN: Phrases = Phrases {
1225    graph_stopped: |status, detail| {
1226        format!("the graph stopped at `{status}` without reaching a terminal status: {detail}")
1227    },
1228    quorum_lost: "the judging panel lost its quorum",
1229    quota_took_out: "; quota took out ",
1230    run_ended: "run ended ",
1231    waiting_for_answer: " - waiting for operator answer to question ",
1232    recovered_running: "recovered a `running` task whose daemon never recorded the outcome: ",
1233    no_run_to_recover: "task was `running` with no live daemon and no readable \
1234                        run to recover; held for a human to check what happened",
1235    could_not_start: "could not start the run: ",
1236    resume_not_latest: |q, run| {
1237        format!("question {q} asked to resume run {run}, which is not this task's latest run")
1238    },
1239    resume_cannot_progress: |q, run, reason| {
1240        format!("question {q} asked to resume run {run}, which cannot make progress: {reason}")
1241    },
1242    resume_unreadable: |q, run, e| {
1243        format!("question {q} asked to resume run {run}, which could not be read: {e}")
1244    },
1245    handover_refused: |r| r.to_string(),
1246    handover_hint: " (clean up the other worktree, then release the task from the queue)",
1247    reviewers_never_answered: |missing, rounds| {
1248        format!(
1249            "{missing} reviewer seat(s) never answered after {rounds} rounds; \
1250             refusing to call it clean"
1251        )
1252    },
1253};
1254
1255const PHRASES_JA: Phrases = Phrases {
1256    graph_stopped: |status, detail| {
1257        format!("グラフが終端状態に達しないまま `{status}` で停止しました: {detail}")
1258    },
1259    quorum_lost: "審査パネルが定足数を失いました",
1260    quota_took_out: "。クォータで脱落: ",
1261    run_ended: "run 終了: ",
1262    waiting_for_answer: " - オペレーターの回答待ち: 質問 ",
1263    recovered_running: "daemon が結果を記録しないまま `running` だったタスクを回収しました: ",
1264    no_run_to_recover: "タスクは `running` でしたが、生きた daemon も回収できる run も見つかりません。\
1265                        何が起きたか人が確認するため保留にしました",
1266    could_not_start: "run を開始できませんでした: ",
1267    resume_not_latest: |q, run| {
1268        format!(
1269            "質問 {q} は run {run} の再開を求めましたが、これはタスクの最新の run ではありません"
1270        )
1271    },
1272    resume_cannot_progress: |q, run, reason| {
1273        format!("質問 {q} は run {run} の再開を求めましたが、これは進行できません: {reason}")
1274    },
1275    resume_unreadable: |q, run, e| {
1276        format!("質問 {q} は run {run} の再開を求めましたが、読み込めませんでした: {e}")
1277    },
1278    handover_refused: |r| {
1279        use crate::handover::Refused;
1280        match r {
1281            Refused::Foreign { branch, path, why } => format!(
1282                "ブランチ `{branch}` は {path} にチェックアウトされており、magi は自動では\
1283                 削除しません。不要なら `git worktree remove` でその worktree を削除して\
1284                 から、やり直してください(詳細: {why})"
1285            ),
1286            Refused::Unsafe { branch, path, why } => format!(
1287                "ブランチ `{branch}` は {path} にチェックアウトされています。そこの作業を\
1288                 コミットか破棄したうえで `git worktree remove` で worktree を削除する\
1289                 か、run を破棄してよいと伝えてから、やり直してください(詳細: {why})"
1290            ),
1291            Refused::ReleaseFailed { branch, path, run } => format!(
1292                "ブランチ `{branch}` は {path} で run {run} がチェックアウトしており、その\
1293                 worktree の解放に失敗したか、変更が見つかりました(未コミットの変更が\
1294                 ある worktree は git が削除を拒否します)。worktree はそのまま残しました"
1295            ),
1296        }
1297    },
1298    handover_hint: "(他の worktree を片付けてから、タスクをキューから解放してください)",
1299    reviewers_never_answered: |missing, rounds| {
1300        format!(
1301            "{missing} 席のレビュアーが {rounds} ラウンドの間に一度も回答しなかったため、\
1302             クリーンとは認めません"
1303        )
1304    },
1305};
1306
1307fn phrases(language: &str) -> &'static Phrases {
1308    if crate::lang::is_japanese(language) {
1309        &PHRASES_JA
1310    } else {
1311        &PHRASES_EN
1312    }
1313}
1314
1315/// The language of the repository a task belongs to, read best-effort for the
1316/// paths that have no run (and so no config of their own) to ask. An unreadable
1317/// config is English, not an error: a hold reason must still get written.
1318fn language_of(task: &Task, fallback: &Path) -> String {
1319    crate::lang::of_repo(&repo_for(task, fallback))
1320}
1321
1322/// The task an answered question speaks for: the one whose runs include the
1323/// question's run, or - for a conductor question, filed under the task's own
1324/// id - the task with that id.
1325pub(crate) fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
1326    if q.node == crate::conduct::NODE {
1327        return tasks.iter().find(|t| t.id == q.run);
1328    }
1329    tasks.iter().find(|t| t.runs.contains(&q.run))
1330}
1331
1332/// Legacy conductor prose never becomes a maintenance command by inference.
1333/// Replace unsupported open labels under the question lock before dispatch.
1334fn repair_choice_offers(questions: &Questions) {
1335    let ownership = crate::task_chat::InquiryOwnership::default();
1336    for q in questions
1337        .list_for_effects_in(&ownership)
1338        .into_iter()
1339        .filter(|q| {
1340            q.status.open()
1341                && q.node == crate::conduct::NODE
1342                && q.choices
1343                    .iter()
1344                    .any(|c| crate::choice_effect::describe(q, c).is_none())
1345        })
1346    {
1347        let _ = questions.update_in(&q.id, &ownership, |current| {
1348            if current.status.open() {
1349                crate::choice_effect::executable_conductor(current);
1350                if let Some(deputy) = &mut current.deputy {
1351                    deputy.brief = crate::deputy::brief(
1352                        &current.run,
1353                        &current.detail,
1354                        &current.choices,
1355                        &current.actions,
1356                    );
1357                }
1358            }
1359            Ok(())
1360        });
1361    }
1362}
1363
1364/// Apply answered typed choices. Only the daemon calls this in production;
1365/// deputies settle the question and never execute its actions.
1366pub async fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1367    apply_maintenance_choices(queue, questions, home).await;
1368    apply_task_choice_actions(queue, questions, home);
1369}
1370
1371/// Apply bounded maintenance effects independently of question ownership: a
1372/// release watcher need not have a queue task, and a predecessor is another run.
1373async fn apply_maintenance_choices(queue: &Queue, questions: &Questions, home: &Path) {
1374    let ownership = crate::task_chat::InquiryOwnership::default();
1375    for q in questions.list_for_effects_in(&ownership) {
1376        // Read again under the same fence used by explicit settlement.
1377        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1378            continue;
1379        };
1380        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1381            continue;
1382        };
1383        let Some(action) = q.chosen_action().filter(|a| a.maintenance()) else {
1384            continue;
1385        };
1386        // Receipt paths use question IDs, whose format is independent of run
1387        // IDs. Apply the question store's filename safety rule to both eras.
1388        if asker_may_still_read(questions, &q, home) || !ask::valid_asset_name(&q.id) {
1389            continue;
1390        }
1391        if queue.list().iter().any(|task| {
1392            (task.id == q.run
1393                || task.runs.contains(&q.run)
1394                || q.routed_task.as_deref() == Some(&task.id))
1395                && task.stale_question(&q)
1396        }) {
1397            continue;
1398        }
1399        if let ask::ChoiceAction::RecoverBase { run, stop, episode } = action {
1400            let tasks = queue.list();
1401            let owner = crate::task_chat::task_of(&q, &tasks);
1402            if let Some(owner) = owner
1403                && q.routed_task
1404                    .as_deref()
1405                    .is_none_or(|routed| routed == owner)
1406            {
1407                let result = crate::base_recovery_control::recover(
1408                    queue,
1409                    home,
1410                    crate::base_recovery_control::Request {
1411                        run: run.clone(),
1412                        head: stop.head.clone(),
1413                        actor: "decisions".into(),
1414                        request: q.id.clone(),
1415                        decision: Some((owner, q.answered_at.unwrap_or(q.asked_at))),
1416                        expected_stop: Some((stop.clone(), *episode)),
1417                        evidence_digest: None,
1418                    },
1419                )
1420                .await;
1421                if let Err(error) = result {
1422                    tracing::warn!(question = %q.id, %error, "base recovery decision refused");
1423                    notices::raise_in(home, Notice::warn(
1424                        &format!("base-recovery:{}", q.id),
1425                        format!("Base recovery decision {} was refused: {error:#}. Inspect the existing run and request; no replacement run was started.", q.id),
1426                    ).link(Link::Run { id: run.clone() }));
1427                }
1428            }
1429            continue;
1430        }
1431        let dir = home.join("choice-actions");
1432        if std::fs::create_dir_all(&dir).is_err() {
1433            continue;
1434        }
1435        let Ok(lock) = std::fs::OpenOptions::new()
1436            .create(true)
1437            .truncate(false)
1438            .write(true)
1439            .open(dir.join(format!("{}.lock", q.id)))
1440        else {
1441            continue;
1442        };
1443        if crate::pr_head::try_lock_file(&lock).is_err() {
1444            continue;
1445        }
1446        let fresh = !home
1447            .join("choice-actions")
1448            .join(format!("{}.json", q.id))
1449            .exists();
1450        let result = async {
1451            let receipt = dir.join(format!("{}.json", q.id));
1452            if receipt.exists() {
1453                let prior: serde_json::Value = serde_json::from_slice(&std::fs::read(&receipt)?)?;
1454                anyhow::ensure!(
1455                    prior.get("status").and_then(|s| s.as_str()) == Some("applied"),
1456                    "previous maintenance attempt did not confirm completion; inspect its receipt"
1457                );
1458                return Ok::<_, anyhow::Error>(());
1459            }
1460            // Never retry an uncertain external effect. The receipt is written
1461            // before calling gh, exactly like release_watch's rerun record.
1462            let record = |status: &str| -> anyhow::Result<()> {
1463                let tmp = receipt.with_extension("tmp");
1464                std::fs::write(
1465                    &tmp,
1466                    serde_json::to_vec(&serde_json::json!({
1467                        "action": action, "status": status,
1468                    }))?,
1469                )?;
1470                std::fs::rename(tmp, &receipt)?;
1471                Ok(())
1472            };
1473            let applied = async {
1474                match action {
1475                    ask::ChoiceAction::ResumeRun { run } => {
1476                        crate::resume::validate(home, run)?;
1477                        record("started")?;
1478                        let decided = q.answered_at.unwrap_or(q.asked_at);
1479                        if !crate::resume::pin_queued(queue, run, Some(decided), Some(&q.id))? {
1480                            crate::resume::validate_unqueued(home, run)?;
1481                            crate::resume::start(home, run.clone()).await?;
1482                        }
1483                    }
1484                    ask::ChoiceAction::ReleaseTask {
1485                        task,
1486                        held_at,
1487                        reason,
1488                    } => {
1489                        anyhow::ensure!(
1490                            queue.resolve_id(task)? == *task,
1491                            "task action requires an exact task ID"
1492                        );
1493                        let _claim = queue.claim(task)?;
1494                        let mut task = queue.get(task)?;
1495                        if task.action_applied(&q.id) {
1496                            return Ok(());
1497                        }
1498                        // Filing this conductor question temporarily wraps the
1499                        // original hold in a Blocked state. Restore only that
1500                        // exact blocker on the local copy before checking the
1501                        // hold binding; unrelated waits never authorize release.
1502                        if q.node == crate::conduct::NODE
1503                            && q.run == task.id
1504                            && task.status == TaskStatus::Blocked
1505                            && task.blocked_from == Some(TaskStatus::Held)
1506                            && task.blocked_by.as_slice() == [q.id.as_str()]
1507                        {
1508                            task.unblock(&q.id);
1509                        }
1510                        anyhow::ensure!(
1511                            task.status == TaskStatus::Held
1512                                && task.held_at == Some(*held_at)
1513                                && task.hold_reason.as_deref() == reason.as_deref()
1514                                && task
1515                                    .operator_decided_at
1516                                    .is_none_or(|at| at <= q.answered_at.unwrap_or(q.asked_at)),
1517                            "task no longer has the hold this question names"
1518                        );
1519                        task.release_operator("choice", Some(&q.id));
1520                        task.mark_action_applied(&q.id);
1521                        queue.put(&mut task)?;
1522                    }
1523                    ask::ChoiceAction::AbandonRun { run } => {
1524                        record("started")?;
1525                        crate::driver::abandon_proven_dead(home, run)?;
1526                    }
1527                    ask::ChoiceAction::RerunChecks {
1528                        repo,
1529                        pr,
1530                        head,
1531                        runs,
1532                    } => {
1533                        rerun_checks_once(home, &q.id, repo, pr, head, runs, || record("started"))
1534                            .await?;
1535                    }
1536                    _ => unreachable!(),
1537                }
1538                Ok::<_, anyhow::Error>(())
1539            }
1540            .await;
1541            match applied {
1542                Ok(()) => record("applied"),
1543                Err(e) => {
1544                    record(&format!("refused or failed: {e:#}"))?;
1545                    Err(e)
1546                }
1547            }
1548        }
1549        .await;
1550        // Retire the originating blocker as well as the target operation.
1551        // A foreign resume leaves its issuer held instead of competing beside
1552        // the execution just started. Other successful maintenance lets the
1553        // original task retry its normal, guarded path.
1554        if home
1555            .join("choice-actions")
1556            .join(format!("{}.json", q.id))
1557            .exists()
1558            && let Some(listed) = task_of_question(&queue.list(), &q)
1559            && !listed.action_applied(&q.id)
1560            && let Ok(_claim) = queue.claim(&listed.id)
1561            && let Ok(mut origin) = queue.get(&listed.id)
1562        {
1563            if !origin.operator_held()
1564                && origin.operator_decided_at.is_none_or(|at| at <= q.asked_at)
1565                && !matches!(origin.status, TaskStatus::Running | TaskStatus::Done)
1566            {
1567                if result.is_err() || matches!(action, ask::ChoiceAction::ResumeRun { .. }) {
1568                    origin.hold_machine(Some(format!(
1569                        "Maintenance choice {} settled; inspect its target before releasing this task",
1570                        q.id
1571                    )));
1572                } else {
1573                    origin.unblock(&q.id);
1574                }
1575            }
1576            origin.mark_action_applied(&q.id);
1577            let _ = queue.put(&mut origin);
1578        }
1579        if let Err(e) = result
1580            && fresh
1581        {
1582            notices::raise_in(
1583                home,
1584                Notice::warn(
1585                    &format!("action:{}", q.id),
1586                    format!("Choice action {} was not completed: {e:#}", q.id),
1587                )
1588                .link(if q.run_names_task() {
1589                    Link::Task { id: q.run.clone() }
1590                } else {
1591                    Link::Run { id: q.run.clone() }
1592                }),
1593            );
1594        }
1595    }
1596}
1597
1598/// Rerun the named failed workflow runs of a pull request, each at most once
1599/// per `request` (a question id, or a chat operation identity). The head,
1600/// lifecycle and failed state are re-read from the forge first; `started` is
1601/// called once those checks pass and before the first external call, and the
1602/// ledger entry is written before every `gh` call, so an uncertain result is
1603/// never repeated automatically.
1604pub(crate) async fn rerun_checks_once(
1605    home: &Path,
1606    request: &str,
1607    repo: &Path,
1608    pr: &str,
1609    head: &str,
1610    runs: &[String],
1611    started: impl FnOnce() -> anyhow::Result<()>,
1612) -> anyhow::Result<()> {
1613    use crate::release_watch::{GhForge, ReleaseForge};
1614    anyhow::ensure!(
1615        !runs.is_empty()
1616            && runs.len() <= 20
1617            && runs
1618                .iter()
1619                .all(|r| !r.is_empty() && r.bytes().all(|b| b.is_ascii_digit()))
1620            && !pr.starts_with('-'),
1621        "invalid rerun targets"
1622    );
1623    let snap = GhForge.snapshot(repo, pr).await?;
1624    anyhow::ensure!(
1625        snap.head == head && snap.state == crate::land::PrLifecycle::Open,
1626        "pull request head or lifecycle changed"
1627    );
1628    anyhow::ensure!(
1629        runs.iter().all(|r| snap
1630            .checks
1631            .iter()
1632            .any(|c| c.run.as_ref() == Some(r) && crate::release_watch::is_failed(c.verdict))),
1633        "named workflow is no longer failed on this pull request"
1634    );
1635    started()?;
1636    let dir = home.join("choice-actions");
1637    std::fs::create_dir_all(&dir)?;
1638    let rerun_lock = std::fs::OpenOptions::new()
1639        .create(true)
1640        .truncate(false)
1641        .write(true)
1642        .open(dir.join("reruns.lock"))?;
1643    crate::pr_head::try_lock_file(&rerun_lock)?;
1644    let ledger = dir.join("reruns.json");
1645    let mut recorded: std::collections::BTreeSet<String> = if ledger.exists() {
1646        serde_json::from_slice(&std::fs::read(&ledger)?)?
1647    } else {
1648        Default::default()
1649    };
1650    for run in runs {
1651        let key = serde_json::to_string(&(request, repo, pr, head, run))?;
1652        if !recorded.insert(key) {
1653            continue;
1654        }
1655        let tmp = ledger.with_extension("tmp");
1656        std::fs::write(&tmp, serde_json::to_vec(&recorded)?)?;
1657        std::fs::rename(tmp, &ledger)?;
1658        GhForge.rerun(repo, run).await?;
1659    }
1660    Ok(())
1661}
1662
1663/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
1664///
1665/// Runs on every poll before the conductor looks at the queue. The task is
1666/// re-read under its claim, so a task somebody completed or held by hand in
1667/// the meantime is judged on what it is now. `Resume` releases the task and
1668/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
1669/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
1670/// ordinary `unfinished_run` logic resumes that same run.
1671pub(crate) fn apply_task_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
1672    let tasks = queue.list();
1673    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1674    for q in questions.list_for_effects_in(&ownership) {
1675        // Read again under the same fence used by explicit settlement.
1676        let Ok(_execution) = crate::task_inquiry::Outbox::at(home).execution_claim(&q.id) else {
1677            continue;
1678        };
1679        let Ok(q) = questions.get_for_effects_in(&q.id, &ownership) else {
1680            continue;
1681        };
1682        // Dismissal is committed by the question writer, never a resume.
1683        if q.resolution().as_deref() == Some(crate::merge_decision::DISMISS) {
1684            continue;
1685        }
1686        if q.chosen_action().is_none_or(|a| a.maintenance()) {
1687            continue;
1688        }
1689        let Some(listed) = task_of_question(&tasks, &q) else {
1690            if q.node == land::APPROVAL_NODE
1691                && q.resolution().as_deref().is_some_and(|choice| {
1692                    choice == land::REPAIR || crate::merge_decision::stops(choice)
1693                })
1694            {
1695                notices::raise_in(
1696                    home,
1697                    Notice::warn(
1698                        &format!("repair-owner:{}", q.id),
1699                        format!(
1700                            "Approval action is waiting: no task owns run {}. Inspect `magi show {}` and restore its original queue owner; do not file a competing task.",
1701                            q.run, q.run
1702                        ),
1703                    ).link(Link::Run { id: q.run.clone() }),
1704                );
1705            }
1706            continue;
1707        };
1708        if listed.action_applied(&q.id) {
1709            continue;
1710        }
1711        let Ok(_claim) = queue.claim(&listed.id) else {
1712            continue;
1713        };
1714        let Ok(mut task) = queue.get(&listed.id) else {
1715            continue;
1716        };
1717        // Work only on this local copy until the action can be committed.
1718        // In particular, a fresh lease below leaves the persisted task blocked.
1719        if q.node == crate::conduct::NODE && task.status == TaskStatus::Blocked {
1720            let blockers: Vec<_> = task
1721                .blocked_by
1722                .iter()
1723                .filter(|id| {
1724                    crate::queue::dependency(queue, questions, id)
1725                        == crate::queue::Dependency::Question(q.id.clone())
1726                })
1727                .cloned()
1728                .collect();
1729            if !blockers.is_empty() {
1730                for id in blockers {
1731                    task.unblock(&id);
1732                }
1733                let answer = match &q.answer {
1734                    Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
1735                    None => String::new(),
1736                };
1737                task.record_answer(q.summary.clone(), answer);
1738            }
1739        }
1740        let language = language_of(&task, Path::new("."));
1741        let mut decision = decide_action(home, &task, &q, phrases(&language), |id| {
1742            RunState::load_under(id, home)
1743        });
1744        let completion = if matches!(decision, ActionDecision::Done) {
1745            match crate::task_completion::prepare_close(
1746                &task,
1747                home,
1748                CompletionActor::DaemonSettle,
1749                Some(format!(
1750                    "Question {}: {} — {}",
1751                    q.id,
1752                    q.summary,
1753                    q.resolution().unwrap_or_default()
1754                )),
1755                false,
1756            ) {
1757                Ok(context) => Some(context),
1758                Err(error) => {
1759                    decision = ActionDecision::Refuse(error.to_string());
1760                    None
1761                }
1762            }
1763        } else {
1764            None
1765        };
1766        let ran = matches!(
1767            decision,
1768            ActionDecision::Resume(_)
1769                | ActionDecision::Requeue
1770                | ActionDecision::Hold
1771                | ActionDecision::Done
1772        );
1773        if ran && asker_may_still_read(questions, &q, home) {
1774            // The asking process or its seat can still take the word; act
1775            // once it has gone quiet. Bound on the remaining window: the
1776            // check is not atomic with the write below, so an asker that
1777            // takes the word in between (at most one poll, never more than
1778            // `ask::LEASE_TTL`) only prints it - it never touches the task,
1779            // and `Task::actions_applied` under the claim keeps the action to
1780            // one application. The waiter does not deliver an answer that
1781            // carries an action (`waiter::decide_owned`), so it cannot race.
1782            continue;
1783        }
1784        let done = matches!(decision, ActionDecision::Done);
1785        // Resume owes an execution pass; only these task-local effects finish
1786        // in this write. Stale/refused actions never acquire an effect receipt.
1787        let completed = matches!(
1788            decision,
1789            ActionDecision::Requeue | ActionDecision::Hold | ActionDecision::Done
1790        );
1791        match decision {
1792            ActionDecision::Skip => continue,
1793            ActionDecision::Resume(run) => {
1794                task.release_operator("choice", Some(&q.id));
1795                task.resume_override = Some(crate::queue::OperatorResume {
1796                    question_id: q.id.clone(),
1797                    at: Timestamp::now(),
1798                    conductor_rehold: None,
1799                    forced: true,
1800                    pinned_run: Some(run),
1801                });
1802            }
1803            ActionDecision::Stale => {}
1804            ActionDecision::Requeue => {
1805                task.release_operator("choice-requeue", Some(&q.id));
1806                task.requeue();
1807            }
1808            ActionDecision::Hold => task.hold_manual(Some(q.summary.clone())),
1809            ActionDecision::Done => {
1810                task.succeed(completion.expect("done passed completion admission"));
1811            }
1812            ActionDecision::Refuse(why) => {
1813                let _ =
1814                    crate::task_inquiry::Outbox::at(home).update_decision(&q.id, |d| d.fail(&why));
1815                if task.operator_held() {
1816                    // A rejected answer does not release the operator's hold
1817                    // or reclassify it as recoverable by the conductor.
1818                    task.hold_reason = Some(match task.hold_reason.take() {
1819                        Some(reason) => format!("{reason}\n\n{why}"),
1820                        None => why,
1821                    });
1822                } else {
1823                    task.notice_cause(&format!("resume-refused:{}", q.id), None, None);
1824                    task.hold_machine(Some(why));
1825                }
1826                notices::raise(
1827                    Notice::warn(
1828                        &format!("action:{}", q.id),
1829                        "An answered task action could not be applied; the task stays held.",
1830                    )
1831                    .link(Link::Task {
1832                        id: task.id.clone(),
1833                    }),
1834                );
1835            }
1836        }
1837        task.mark_action_applied(&q.id);
1838        if completed {
1839            task.decision_effects.insert(
1840                q.id.clone(),
1841                format!("decision: {}", q.resolution().expect("answered action")),
1842            );
1843        }
1844        // The applied id travels with the transition, so a failed save loses
1845        // neither and the answer is acted on at the next poll.
1846        record(queue, &mut task);
1847        if done && queue.get(&task.id).is_ok_and(|t| t.action_applied(&q.id)) {
1848            supersede_prior_runs(&task, home);
1849        }
1850        // Delivery is only a note of who has read the answer; the task's own
1851        // mark above is the authority. Best effort.
1852        let _ = questions.update_in(&q.id, &ownership, |r| {
1853            r.answer_delivered = true;
1854            Ok(())
1855        });
1856    }
1857}
1858
1859/// Whether something may still read the answer to `q`: a fresh lease, or the
1860/// asking seat still listed as active in its run (its CLI can outlive the
1861/// `magi ask` that was killed).
1862fn asker_may_still_read(questions: &Questions, q: &ask::Question, home: &Path) -> bool {
1863    let now = Timestamp::now();
1864    if questions.read_lease(&q.id).is_some_and(|l| l.fresh(now)) {
1865        return true;
1866    }
1867    q.node != crate::conduct::NODE
1868        && RunState::load_under(&q.run, home).is_ok_and(|s| {
1869            s.seats_active()
1870                .any(|(k, a)| *k == q.seat && a.remaining_secs(now) > 0)
1871        })
1872}
1873
1874/// Retire an unanswered conductor question after its task no longer refers to
1875/// it. Conductor questions use the task id in `Question::run`, so run-based
1876/// cleanup cannot observe a manual release or completion.
1877///
1878/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
1879/// own question also carries a `run`, and a run id that happens to collide
1880/// with some task's id is not this loop's business — only a conductor
1881/// question actually uses the task id that way. One `Questions::list()` scan
1882/// is taken up front and matched against the in-memory task set, rather than
1883/// calling `Questions::open_for` (a full disk scan on its own) once per task.
1884fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
1885    let tasks = queue.list();
1886    let ownership = crate::task_chat::InquiryOwnership::from_tasks(&tasks);
1887    let by_id: std::collections::BTreeMap<&str, &Task> =
1888        tasks.iter().map(|t| (t.id.as_str(), t)).collect();
1889    let referenced: Vec<&str> = tasks
1890        .iter()
1891        .flat_map(|task| task.blocked_by.iter().map(String::as_str))
1892        .collect();
1893
1894    for mut question in questions.list_for_effects_in(&ownership) {
1895        if !question.status.open()
1896            || question.node != crate::conduct::NODE
1897            || questions.held_reply_in(&question.id, &ownership)
1898        {
1899            continue;
1900        }
1901        // Keep questions a task still names, including when the reference
1902        // moved to a dependent task.
1903        // Preserve even ambiguous references: retiring a possibly referenced
1904        // question is unsafe until the operator disambiguates it.
1905        if referenced
1906            .iter()
1907            .any(|id| question.id.starts_with(id) || question.id.ends_with(id))
1908        {
1909            continue;
1910        }
1911        let Some(task) = by_id.get(question.run.as_str()) else {
1912            continue;
1913        };
1914        question.abandon(format!(
1915            "task {} no longer waits for this answer",
1916            task.short()
1917        ));
1918        if let Err(e) = questions.put_in(&mut question, &ownership) {
1919            tracing::warn!(
1920                "could not retire question {} for task {}: {e:#}",
1921                question.short(),
1922                task.short()
1923            );
1924        }
1925    }
1926}
1927
1928/// What a finished run tells the queue about the task it came from.
1929///
1930/// A struct rather than a fourth and fifth boolean argument: the two flags
1931/// answer different questions about the same run, and a call site passing
1932/// `(…, true, false)` is one transposition away from refunding attempts
1933/// forever.
1934#[derive(Debug, Clone, Copy)]
1935pub struct Verdict {
1936    /// Where the graph stopped.
1937    pub status: RunStatus,
1938    /// The run opened a pull request.
1939    pub left_pr: bool,
1940    /// At least one seat was lost to a rate limit.
1941    pub quota_hit: bool,
1942    /// The run parked at a node boundary because it was asked to.
1943    pub parked: bool,
1944    /// The run never produced a single candidate a judge could look at.
1945    ///
1946    /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
1947    /// still have another candidate worth judging, in which case the loss was
1948    /// not the reason nothing came of the run. This is `true` only when the
1949    /// implement wave ended with nothing viable at all.
1950    pub no_viable_candidates: bool,
1951}
1952
1953/// Record a finished run against the task it came from.
1954///
1955/// Kept pure and separate from the loop because this mapping *is* the retry
1956/// policy, and a policy that can only be exercised by spawning a graph is a
1957/// policy nobody checks. The table:
1958///
1959/// | run status                           | task becomes        | attempt spent |
1960/// |---------------------------------------|---------------------|---------------|
1961/// | parked at a boundary                  | `Parked` (requeued) | **no**        |
1962/// | `Merged`, `Ready`                      | `Done`               | yes          |
1963/// | `AlreadyInBase`                        | `Done`, with a note  | **no**        |
1964/// | `Stalled`, quota hit                   | `Failed` (requeued) | **no**        |
1965/// | `Failed`, quota hit, no viable cand.   | `Failed` (requeued) | **no**        |
1966/// | `Stalled`, no quota                    | `Failed`, or `Held`  | yes          |
1967/// | recorded authentication/resource stop | `Held` (machine)     | **no**       |
1968/// | recorded usage-limit node stop       | `Failed` (requeued)  | **no**       |
1969/// | `Blocked` with a PR                    | `Held`               | yes          |
1970/// | `Blocked`, `Failed` otherwise          | `Failed`, or `Held`  | yes          |
1971/// | `VerifiedNoop`                          | `Held`               | yes          |
1972/// | anything non-terminal                  | `Failed`, or `Held`  | yes          |
1973///
1974/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
1975/// deliberately: every candidate agreeing there is nothing to write is not a
1976/// machine fact about a rate limit, it is an unverified claim about the
1977/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
1978/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
1979/// claim could be wrong (a misread instruction, a stale check), and closing
1980/// the task automatically on an implementer's say-so would be the exact
1981/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
1982/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
1983/// above, which settles through the same [`Task::handed_off`]: `Held` is not
1984/// `Failed`-and-requeued, so nothing retries this task on the same unverified
1985/// claim regardless of whether the one already-spent attempt is refunded, and
1986/// [`Task::release`] resets the count to zero anyway the moment a human looks
1987/// at the evidence and lets it run again.
1988///
1989/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1990/// twice, together. A quorum lost to rate limits is a property of the machine
1991/// and not of the task, so the attempt is refunded and a reset quota picks
1992/// the work up where it stopped — and that is just as true when every
1993/// implement seat lost the same race and `after_implement` bails with nothing
1994/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1995/// machine fact. The `no_viable_candidates` guard is what keeps that row
1996/// narrow: a `Failed` run that produced a real candidate which then lost for
1997/// some other reason still spends the attempt, exactly like the quorum lost
1998/// to judges that answered with the wrong shape is ordinary flakiness, and
1999/// refunding *that* takes the bound off the retry loop entirely: run e633
2000/// stalled with `quota: []` after two judges wrote unusable JSON, was
2001/// refunded, and the next attempt paid for a fresh hour-long implement wave
2002/// before it could fail the same way. `max_attempts` exists precisely so
2003/// that cannot repeat forever.
2004///
2005/// A non-terminal status means `execute` returned while the graph was still
2006/// mid-flight, which is a bug rather than a verdict; it is treated as a
2007/// failure so that a task cannot loop on it either.
2008///
2009/// `left_pr` splits the `Blocked` row, and it is the difference between a run
2010/// that failed and a run that finished into a gate. See [`Task::handed_off`].
2011pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
2012    settle_in(task, verdict, detail, max_attempts, &PHRASES_EN, None)
2013}
2014
2015/// [`settle`], with the daemon's own fixed prose in `p`'s language.
2016fn settle_in(
2017    task: &mut Task,
2018    verdict: Verdict,
2019    detail: &str,
2020    max_attempts: usize,
2021    p: &Phrases,
2022    state: Option<&RunState>,
2023) {
2024    // A parked run is the operator's own doing, and its work is intact on
2025    // disk. The task goes back in line with its attempt refunded so the next
2026    // loop resumes the same run - which `one_task` prefers over competing
2027    // again - and so that swapping the binary a few times cannot exhaust a
2028    // budget meant for agents that actually misbehaved.
2029    if verdict.parked {
2030        task.park(detail);
2031        return;
2032    }
2033    let completion = |task: &Task| match state {
2034        Some(state) => CompletionContext::from_run(
2035            CompletionActor::DaemonSettle,
2036            Some(detail.to_owned()),
2037            task,
2038            state,
2039        ),
2040        None => CompletionContext::new(
2041            CompletionActor::DaemonSettle,
2042            Some(detail.to_owned()),
2043            &crate::run::home(),
2044            task,
2045        ),
2046    };
2047    match verdict.status {
2048        RunStatus::Merged | RunStatus::Ready
2049            if task.pr_recovery.as_ref().is_some_and(|s| {
2050                s.disposition != Some(crate::pr_recovery::Disposition::Review)
2051            }) =>
2052        {
2053            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()));
2054        }
2055        RunStatus::Merged | RunStatus::Ready => task.succeed(completion(task)),
2056        RunStatus::AlreadyInBase => task.already_landed(detail, completion(task)),
2057        RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
2058        RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
2059            task.stall(detail)
2060        }
2061        RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
2062        RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
2063        RunStatus::Blocked => task.fail(detail, max_attempts),
2064        RunStatus::VerifiedNoop if state.is_none_or(RunState::all_candidates_verified_noop) => {
2065            task.handed_off(detail)
2066        }
2067        RunStatus::VerifiedNoop => task.fail(detail, max_attempts),
2068        other => task.fail((p.graph_stopped)(label(other), detail), max_attempts),
2069    }
2070}
2071
2072/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
2073/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
2074/// itself has actually finished *and* its own last attempt is provably why:
2075/// this loads that run and requires `Merged`/`Ready` before touching
2076/// anything earlier in `runs`, since `Task::succeed` can also be called
2077/// directly on a task whose last attempt never landed at all.
2078///
2079/// Called right after whatever call set `task.status` to
2080/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
2081/// `reclaim`'s, but also every other place a task can be closed by hand
2082/// without the loop ever settling it itself: `magi task done`
2083/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
2084/// (`web::queue_done`). Closing a task by hand — after confirming a manual
2085/// GitHub merge, say, exactly the workflow this repository's own
2086/// "Landing a run's winner by hand" documents — is just as much "this task's
2087/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
2088/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
2089/// forever, which is the exact backlog this status exists to clear. `pub`
2090/// for those two out-of-module callers; everything else about this stays
2091/// internal bookkeeping.
2092///
2093/// A run something is still actually driving is left alone: a
2094/// task cannot be `Done` while one of its *own* attempts is still in flight,
2095/// so a live one at this point can only be an unrelated process — a manual
2096/// `--resume` of this old, now-moot run — and rewriting under it would just
2097/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
2098/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
2099/// pair `run_report`/`run_detail` use for the same question elsewhere:
2100/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
2101/// --resume` invoked by hand outside it, which `liveness` also checks via
2102/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
2103/// (already terminal in some other way, or itself mid-run) is left untouched
2104/// too.
2105///
2106/// Best-effort, like the rest of this module's bookkeeping: a load or save
2107/// failure here is a `tracing::warn`, not a failed settle, and the next time
2108/// this same task's completion is recorded — or a daemon restart replays
2109/// `reclaim_orphaned_running` — is another chance to catch up. There is no
2110/// separate reconciliation pass; if that gap ever matters in practice, one
2111/// can be added then.
2112///
2113/// `home` is a parameter, not the process-global [`crate::run::home`], for
2114/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
2115/// calls this with `ui.home`, which is `crate::run::home()` in a real
2116/// process but a fixture's own directory under test — falling through to
2117/// the global there would read and write through whichever home some other
2118/// test in the same binary happened to pin into that `OnceLock` first, not
2119/// the run this call actually means.
2120pub fn supersede_prior_runs(task: &Task, home: &Path) {
2121    if task
2122        .completion_history
2123        .last()
2124        .is_some_and(|event| event.discard)
2125    {
2126        return;
2127    }
2128    let now = Timestamp::now();
2129    // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
2130    // right behind a `Merged`/`Ready` verdict) from one set directly by
2131    // `magi task done`/its web equivalent/the conductor on a task whose last
2132    // recorded attempt never actually landed - that requires reading the
2133    // run itself, which is exactly what this does before trusting anything
2134    // in `runs` is safe to relabel.
2135    let last_run_succeeded = task
2136        .runs
2137        .last()
2138        .and_then(|id| RunState::load_under(id, home).ok())
2139        .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
2140    for id in task.superseded_attempts(last_run_succeeded) {
2141        let mut state = match RunState::load_under(id, home) {
2142            Ok(s) => s,
2143            Err(e) => {
2144                tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
2145                continue;
2146            }
2147        };
2148        if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
2149            continue;
2150        }
2151        let daemon_claims = is_working_on(home, id, now);
2152        if state.liveness(daemon_claims) == Liveness::Live {
2153            continue;
2154        }
2155        state.status = RunStatus::Superseded;
2156        if let Err(e) = state.save_under(home) {
2157            tracing::warn!("could not mark run {id} superseded: {e:#}");
2158        }
2159    }
2160}
2161
2162/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
2163/// finish the moment it was called, because one of its earlier attempts was
2164/// still live then - a `magi run --resume` invoked by hand on an old run,
2165/// most likely.
2166///
2167/// That skip is correct at the time (rewriting under a run something is
2168/// still actively saving would just be undone), but recording a completion
2169/// does not schedule another settlement, so without this nothing would look at it
2170/// again: if that manual process later ends anywhere other than
2171/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
2172/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
2173/// backlog this status exists to clear. Called on the same idle-only
2174/// cadence as [`janitor`], next to it rather than folded into it: this
2175/// walks `queue` and `janitor` never otherwise needs one.
2176///
2177/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
2178/// more than one attempt, every pass: each call is a handful of local file
2179/// reads bounded by that task's own attempt count, the same order of cost
2180/// [`clean::fold_due`] already pays scanning every run on disk on the same
2181/// cadence, and a task already fully resolved costs one failed liveness
2182/// check turned no-op the moment its lingering attempt is no longer live.
2183fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
2184    for task in queue.list() {
2185        if task.status != TaskStatus::Done || task.runs.len() < 2 {
2186            continue;
2187        }
2188        supersede_prior_runs(&task, home);
2189    }
2190}
2191
2192/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
2193/// task ends up held.
2194///
2195/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
2196/// dead daemon never got back to) share this, so the two cannot drift into
2197/// disagreeing about which held tasks get a diagnostic.
2198fn settle_and_diagnose(
2199    task: &mut Task,
2200    verdict: Verdict,
2201    detail: &str,
2202    max_attempts: usize,
2203    state: &RunState,
2204) {
2205    let mut verdict = verdict;
2206    let mut detail = detail;
2207    if verdict.status == RunStatus::VerifiedNoop && !state.all_candidates_verified_noop() {
2208        // Never allow an inconsistent or unsupported `VerifiedNoop` run state
2209        // to bypass settlement into a no-change handoff, and never rewrite the
2210        // historical run record on disk: settle the task as an ordinary failure.
2211        verdict.status = RunStatus::Failed;
2212        verdict.quota_hit = false;
2213        detail = "no-change result lacks verified evidence";
2214    }
2215    let p = phrases(&state.config.graph.language);
2216    // Shared by normal completion and crash recovery, under the task claim.
2217    // No new attempt can own the task until the old driver has exited.
2218    if let Some(d) = &state.merge_decision {
2219        use crate::merge_decision as md;
2220        if task
2221            .execution_runs()
2222            .last()
2223            .is_some_and(|id| id != &state.id)
2224        {
2225            return;
2226        }
2227        if (d.choice == md::WITHDRAW && d.closed) || d.choice == md::DISMISS {
2228            task.succeed(CompletionContext::from_run(
2229                CompletionActor::DaemonSettle,
2230                Some(format!("Owner merge decision {}: {}", d.question, d.choice)),
2231                task,
2232                state,
2233            ));
2234        } else if let Some(agent) = md::selected_agent(&d.choice).filter(|_| d.closed) {
2235            if state.liveness(false) != Liveness::Dead {
2236                task.hold_manual(Some("Previous driver is still live; replacement held until it exits. Release the task after checking the driver.".into()));
2237                return;
2238            }
2239            let replacement = md::Replacement {
2240                question: d.question.clone(),
2241                run: state.id.clone(),
2242                pr: d.target.pr.clone(),
2243                agent: agent.to_owned(),
2244                context: format!(
2245                    "Previous PR: {}. Previous run: {}. Owner requested a new implementation.\nReview evidence:\n{}",
2246                    d.target.pr,
2247                    state.id,
2248                    serde_json::to_string(&state.reviews).unwrap_or_default()
2249                ),
2250            };
2251            task.requeue();
2252            task.pr_recovery = None;
2253            task.review_of = None;
2254            task.replacement = Some(replacement);
2255        } else {
2256            task.hold_manual(Some(if d.choice.eq_ignore_ascii_case(land::HOLD) {
2257                format!("Decision held by owner; no further repair or merge work. {}", state.merge.as_ref().map_or("", |m| m.detail.as_str()))
2258            } 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())) }));
2259        }
2260        task.mark_action_applied(&d.question);
2261        if d.choice.eq_ignore_ascii_case(land::HOLD) {
2262            task.decision_effects
2263                .insert(d.question.clone(), format!("decision: {}", d.choice));
2264        }
2265        if let Some(pass) = state.passes.last() {
2266            task.record_pass_at(
2267                &state.id,
2268                pass.index,
2269                Some(pass.started_at),
2270                task.attempts,
2271                None,
2272            );
2273        }
2274        return;
2275    }
2276    if let Some(replacement) = &task.replacement
2277        && !state.parked
2278        && state.resource_block.is_none()
2279        && (state.viable().is_empty()
2280            || (state.status == RunStatus::Blocked && state.tally.is_none()))
2281    {
2282        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)));
2283        return;
2284    }
2285    if !verdict.parked && verdict.quota_hit && state.status == RunStatus::Stalled {
2286        let mut agents: Vec<_> = state
2287            .quota
2288            .iter()
2289            .filter(|q| {
2290                q.cause == crate::agent::QuotaCause::Authentication
2291                    && state
2292                        .passes
2293                        .last()
2294                        .is_none_or(|pass| q.at >= pass.started_at)
2295            })
2296            .map(|q| q.agent.as_str())
2297            .collect();
2298        agents.sort_unstable();
2299        agents.dedup();
2300        if !agents.is_empty() {
2301            task.stall(detail);
2302            task.notice_cause("agent-authentication", None, None);
2303            task.hold_machine(Some(format!("[authentication] Agents {} cannot authenticate; re-authenticate, then resume the held task. No attempt was spent.", agents.join(", "))));
2304            return;
2305        }
2306    }
2307    let attempts_before = task.attempts;
2308    // A run that stopped because a shared resource stayed busy was never a
2309    // failure of the task or of an agent. Earlier nodes may have run; only
2310    // the blocked operation lacks a result. The attempt is
2311    // refunded and the task is held by the machine, under a reason `triage`
2312    // can re-check, so the same run resumes with the same agents once the
2313    // resource is free. A park request still wins (it is the operator's).
2314    if let Some(block) = state.resource_block.as_ref().filter(|_| !verdict.parked) {
2315        let disk_checked_at = task.disk_checked_at;
2316        task.notice_cause(
2317            &format!("resource:{}:{}", block.kind, block.node),
2318            None,
2319            None,
2320        );
2321        task.last_error = Some(detail.to_owned());
2322        task.diagnostic = None;
2323        task.attempts = task.attempts.saturating_sub(1);
2324        if block.kind == "agent authentication" {
2325            task.hold_machine(Some(format!(
2326                "[authentication] {}; no attempt was spent",
2327                block.detail
2328            )));
2329        } else if block.kind == "agent usage limit" {
2330            // Usage limits keep the existing cooldown-and-resume policy.
2331            if let Some(agent) = &state.config.graph.selected_implementer {
2332                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.")));
2333            } else {
2334                task.status = TaskStatus::Failed;
2335                task.last_error = Some(block.detail.clone());
2336            }
2337        } else if block.kind == "disk pressure" {
2338            task.hold_machine(Some(format!(
2339                "{}{}",
2340                crate::disk::RUNNING_PRESSURE,
2341                block.detail
2342            )));
2343        } else {
2344            task.hold_machine(Some(format!(
2345                "{}{}; no attempt was spent; resume to retry the affected operation",
2346                crate::cache::RESOURCE_HOLD,
2347                block.description()
2348            )));
2349        }
2350        if matches!(block.kind.as_str(), "disk pressure" | "disk admission")
2351            && matches!(block.cause, crate::run::ResourceBlockCause::Other)
2352        {
2353            task.mark_disk_capacity();
2354            task.disk_checked_at = disk_checked_at;
2355        }
2356        if let Some(pass) = state.passes.last() {
2357            task.record_pass_at(
2358                &state.id,
2359                pass.index,
2360                Some(pass.started_at),
2361                attempts_before,
2362                None,
2363            );
2364        }
2365        return;
2366    }
2367    if let Some(hold) = state.land_unrelated.as_ref().filter(|hold| {
2368        state.parked
2369            && state.status == RunStatus::Landing
2370            && state
2371                .pr_pushed_head
2372                .as_ref()
2373                .is_none_or(|h| h == &hold.head)
2374            && task.execution_runs().last() == Some(&state.id)
2375    }) {
2376        // Settlement and crash recovery share this idempotency key. A later
2377        // explicit resume is a new pass and may refund its own attempt once.
2378        let pass = state.passes.last().map_or(0, |p| p.index);
2379        if !task
2380            .passes
2381            .iter()
2382            .any(|p| p.run == state.id && p.pass_index == pass)
2383        {
2384            task.attempts = task.attempts.saturating_sub(1);
2385        }
2386        task.hold_machine(Some(format!(
2387            "[ci-unrelated] CI failure reproduced on base; owner question {}",
2388            hold.question
2389        )));
2390        task.last_error = Some(detail.to_owned());
2391        task.diagnostic = None;
2392        task.record_pass_at(
2393            &state.id,
2394            pass,
2395            state.passes.last().map(|p| p.started_at),
2396            attempts_before,
2397            Some(crate::run::ParkCause::Question),
2398        );
2399        return;
2400    }
2401    let unresolved = task.hold_notice_cause.clone();
2402    let head_e2e_stop = crate::head_e2e_stop::conclusive(state)
2403        .filter(|_| !verdict.parked && !verdict.quota_hit && task.pr_recovery.is_none());
2404    let mut reconsumed_head_e2e = false;
2405    if state.base_sync_blocked() {
2406        // No automatic retry may turn a retained sync stop into a new competition.
2407        task.hold_machine(Some(detail.to_owned()));
2408        task.last_error = Some(detail.to_owned());
2409    } else if !verdict.parked
2410        && task
2411            .pr_recovery
2412            .as_ref()
2413            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2414        && matches!(
2415            verdict.status,
2416            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2417        )
2418    {
2419        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2420            task.succeed(CompletionContext::from_run(
2421                CompletionActor::DaemonSettle,
2422                Some(detail.to_owned()),
2423                task,
2424                state,
2425            ));
2426        } else {
2427            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()));
2428        }
2429    } else if !verdict.parked
2430        && task.pr_recovery.is_some()
2431        && matches!(
2432            verdict.status,
2433            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2434        )
2435        && !verdict.quota_hit
2436    {
2437        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.")));
2438    } else if let Some(stop) = head_e2e_stop.clone() {
2439        // Conclusive current-head E2E red settles directly to one actionable
2440        // machine hold instead of cycling through runnable `Failed` passes.
2441        // Refund only when this pass provably reconsumed an earlier stop with
2442        // no new verification events, idempotently across reclaim/re-settle.
2443        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2444            reconsumed_head_e2e = true;
2445            let pass = state.passes.last().map_or(0, |p| p.index);
2446            if !task
2447                .passes
2448                .iter()
2449                .any(|p| p.run == state.id && p.pass_index == pass)
2450            {
2451                task.attempts = task.attempts.saturating_sub(1);
2452            }
2453        }
2454        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2455        task.hold_head_e2e(stop, reason, detail.to_owned());
2456    } else {
2457        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2458    }
2459    if !verdict.parked
2460        && !verdict.quota_hit
2461        && !reconsumed_head_e2e
2462        && matches!(
2463            verdict.status,
2464            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2465        )
2466    {
2467        task.recovery_failed(state);
2468    }
2469    if state.prep_failure.is_some() {
2470        // Minting a run whose candidates could not be prepared is not work
2471        // on a newly approved attempt. Keep the unresolved outcome anchor.
2472        task.hold_notice_cause = unresolved;
2473        task.startup_notice_cause("startup-candidates");
2474    }
2475    // Written here, where the refund (or not) is decided, so the history is a
2476    // fact and not a later guess from the run's status.
2477    if let Some(pass) = state.passes.last() {
2478        let parked = match &pass.end {
2479            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2480            _ => None,
2481        };
2482        task.record_pass_at(
2483            &state.id,
2484            pass.index,
2485            Some(pass.started_at),
2486            attempts_before,
2487            parked,
2488        );
2489    }
2490    if task.status == TaskStatus::Held {
2491        if state.base_sync_blocked() {
2492            task.base_sync_notice(state);
2493        } else if let Some(stop) = &head_e2e_stop {
2494            task.head_e2e_notice(stop);
2495        } else if state.prep_failure.is_none() {
2496            task.notice_cause(
2497                label(verdict.status),
2498                Some(&state.id),
2499                state.passes.last().map(|p| p.index),
2500            );
2501        }
2502        task.diagnostic = diagnostic(state);
2503        note_open_question(task, &state.id, p);
2504    }
2505}
2506
2507/// If `task` is held with a `magi ask` question still open on `run`, name the
2508/// question in [`Task::hold_reason`] rather than leaving the hold reading
2509/// only [`describe`]'s run summary.
2510///
2511/// This is the shape task 20260928-191407-05fd left underspecified: an
2512/// implementer settled a verified no-op and filed a question for the
2513/// operator, and the hold that followed said nothing about the question
2514/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2515/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2516/// marker) and must keep seeing it unchanged.
2517///
2518/// Best-effort: an unreadable question store must not stop a run from
2519/// settling, so this is a no-op rather than a propagated error when
2520/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2521fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2522    let Some(home) = crate::run::try_home() else {
2523        return;
2524    };
2525    let open = Questions::at(home.join("questions")).open_for(run);
2526    let Some(q) = open.first() else {
2527        return;
2528    };
2529    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2530    decisions.sort_unstable();
2531    task.notice_cause(
2532        &format!("questions:{}", decisions.join(",")),
2533        Some(run),
2534        None,
2535    );
2536    let base = task.hold_reason.clone().unwrap_or_default();
2537    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2538}
2539
2540/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2541/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2542/// by some other means entirely, like a manual `magi run` resume that
2543/// finishes the graph outside the queue's bookkeeping.
2544///
2545/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2546/// `settle` is separate from `attempt`: a task recovered this way must land
2547/// exactly where a live daemon would have put it — the same policy table,
2548/// not a second one that quietly drifts from it — and that is only checkable
2549/// without spawning a real run.
2550fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2551    if let Some(request) = task.sync_only.clone() {
2552        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2553        return;
2554    }
2555    match last_run {
2556        Some(state) => {
2557            let verdict = Verdict {
2558                status: state.status,
2559                left_pr: state.pr.is_some(),
2560                quota_hit: state.quota.iter().any(|loss| {
2561                    state
2562                        .passes
2563                        .last()
2564                        .is_none_or(|pass| loss.at >= pass.started_at)
2565                }),
2566                parked: state.parked,
2567                no_viable_candidates: state.viable().is_empty(),
2568            };
2569            let detail = format!(
2570                "{}{}",
2571                phrases(&state.config.graph.language).recovered_running,
2572                describe(&state)
2573            );
2574            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2575        }
2576        None => {
2577            // No run, so no config of its own: `language` is the task's
2578            // repository's setting, read by the caller.
2579            let why = phrases(language).no_run_to_recover;
2580            task.last_error = Some(why.to_owned());
2581            // The phone shows `hold_reason`, so a task held by the machine
2582            // says why there too and not only in `last_error`.
2583            task.notice_cause("missing-run", None, None);
2584            task.hold_machine(Some(why.to_owned()));
2585        }
2586    }
2587}
2588
2589/// Find every task left at `running` that no live process is actually
2590/// driving, and settle each one against whatever its last run became.
2591///
2592/// # Why a claim is proof, not a guess
2593///
2594/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2595/// `running`, and the guard is held for the task's whole time in that status:
2596/// `attempt` does not return, and the loop does not move past the scope
2597/// holding the claim, until the run has settled. So a `running` task whose
2598/// lock is gone cannot have a live owner — this process or any other —
2599/// without needing a staleness threshold or a pid check the way
2600/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2601/// task that never got as far as `running` at all. Taking the claim here is
2602/// the whole test: it either fails, because something really does hold it
2603/// and the task is left alone, or it succeeds, which is the proof — and it is
2604/// kept for the rest of the decision so nothing else can start a competing
2605/// run while this one is being written.
2606///
2607/// Called on every poll, not only at startup, for the reason
2608/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2609/// keep noticing this, not only on the one morning it happened to restart.
2610fn reclaim_orphaned_running(
2611    queue: &Queue,
2612    max_attempts: usize,
2613    live_workers: &std::collections::BTreeSet<String>,
2614) -> Vec<String> {
2615    let mut reclaimed = Vec::new();
2616    for listed in queue.list() {
2617        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2618            continue;
2619        }
2620        let Ok(_claim) = queue.claim(&listed.id) else {
2621            continue;
2622        };
2623        // Re-read under the claim: a release or an edit landed by a human
2624        // between the listing above and the claim just taken must not be
2625        // clobbered by a decision based on the stale copy.
2626        let Ok(mut task) = queue.get(&listed.id) else {
2627            continue;
2628        };
2629        if task.status != TaskStatus::Running {
2630            continue;
2631        }
2632        let last_run = task
2633            .execution_runs()
2634            .last()
2635            .and_then(|id| RunState::load(id).ok());
2636        // `execute` normally abandons a run's own open questions the moment
2637        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2638        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2639        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2640        // with the question still `open`, because the process died before
2641        // reaching that call. `reclaim` itself stays pure on purpose (see its
2642        // own doc), so the same cleanup runs here instead, against the run
2643        // this reclaim is already reading. `settle_run` costs nothing when
2644        // `execute` already got there first.
2645        if let Some(state) = &last_run
2646            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2647        {
2648            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2649        }
2650        let language = if last_run.is_none() {
2651            language_of(&task, Path::new("."))
2652        } else {
2653            String::new()
2654        };
2655        reclaim(&mut task, last_run, max_attempts, &language);
2656        if task.status == TaskStatus::Done {
2657            supersede_prior_runs(&task, &crate::run::home());
2658        }
2659        record(queue, &mut task);
2660        reclaimed.push(task.id.clone());
2661    }
2662    reclaimed
2663}
2664
2665/// Find every run whose `run.json` is provably dead — every seat it still
2666/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2667/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2668/// not merely "no daemon claims it" — and fail it, clearing the leftover
2669/// active seats so the run stops reading as `implementing` (or whichever
2670/// node) forever.
2671///
2672/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2673/// `running`, using whatever `run.json` already says — but nothing in that
2674/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2675/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2676/// never got back to sits exactly where it was left: `active` full of seats
2677/// nobody will ever answer for, `status` stuck on whatever node was in
2678/// flight. `magi show` already tells an operator this in prose (`no live
2679/// daemon claims this run right now`); this is what makes that fact durable
2680/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2681/// stay stuck once nothing is driving it.
2682///
2683/// Runs on every poll, not only at startup, for the reason
2684/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2685/// daemon up for days must keep noticing a run some other, now-dead, daemon
2686/// left behind just as readily as one it trips over on the way up.
2687///
2688/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2689/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2690/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2691/// `runs` directory instead: `home` here is a parameter precisely so a test
2692/// can point it away from the operator's real history (see [`drive`]'s own
2693/// doc), and a scan that fell through to the global home anyway would walk
2694/// whichever directory some *other* process or test pinned into that
2695/// `OnceLock` first — mutating runs this call was never handed.
2696fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2697    reclaim_abandoned_runs_with(
2698        home,
2699        now,
2700        crate::proc::pid_status,
2701        crate::proc::process_started_at,
2702    )
2703}
2704
2705/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2706/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2707/// for the identical reason: this sweep's real damage (wiping a run's active
2708/// seats and failing it) has to be provable against an injected answer in a
2709/// test, not just the real process table.
2710fn reclaim_abandoned_runs_with<F, G>(
2711    home: &Path,
2712    now: Timestamp,
2713    query: F,
2714    identity: G,
2715) -> Vec<String>
2716where
2717    F: Fn(u32) -> Option<bool>,
2718    G: Fn(u32) -> Option<String>,
2719{
2720    let mut abandoned = Vec::new();
2721    for entry in std::fs::read_dir(home.join("runs"))
2722        .into_iter()
2723        .flatten()
2724        .flatten()
2725    {
2726        let id = entry.file_name().to_string_lossy().into_owned();
2727        if !crate::run::is_run_id(&id) {
2728            continue;
2729        }
2730        // Serialize the proof and save with claims and takeover: a new
2731        // execution must not be overwritten after the liveness observation.
2732        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2733            continue;
2734        };
2735        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2736        // that module's docs for why a run this cannot parse is left alone
2737        // rather than guessed at. A different schema number is not that: this
2738        // touches only `status` and `active`, never a field whose meaning a
2739        // schema bump changed, so an old record's values serve this exactly
2740        // as well as a current one's (see `clean::read_state`'s own doc for
2741        // the same reasoning applied to folding).
2742        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2743            continue;
2744        };
2745        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2746            continue;
2747        };
2748        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2749            continue;
2750        }
2751        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2752        // it", which is also the normal, healthy shape of a manual `magi
2753        // run` / `magi review` sharing this same home — this scan walks
2754        // every run on disk, not only ones this daemon itself started. Such
2755        // a run's active seats can legitimately sit past their own timeout
2756        // for a little while (the CLI finishing up, its result still being
2757        // collected) without the process driving it having died. `liveness`
2758        // is what actually tells the two apart, by corroborating
2759        // `driver_pid` against the process it names — see its own doc. Only
2760        // its strongest, provable answer licenses wiping this run's active
2761        // seats and failing it out from under whatever is still running it.
2762        let daemon_claims = is_working_on(home, &id, now);
2763        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2764            != crate::run::Liveness::Dead
2765        {
2766            continue;
2767        }
2768        state.abandon("daemon");
2769        if let Err(e) = state.save_under(home) {
2770            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2771            continue;
2772        }
2773        // This run never passes through `Runner::execute` again, so its end
2774        // is announced here.
2775        if let Some(notice) = notices::run_ended(&state) {
2776            notices::raise_in(home, notice);
2777        }
2778        // The seat that asked is gone for good now, exactly like any other
2779        // door `graph::Runner::settle_questions` closes the moment `status`
2780        // lands somewhere non-resumable - see that method's own doc. Nothing
2781        // else reaches this one before the next `janitor()` startup pass
2782        // (`clean::abandon_settled_questions`), and a daemon that stays up
2783        // for days must not leave an open question badging the operator
2784        // until it happens to restart.
2785        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2786            tracing::warn!("abandon questions for {id}: {e:#}");
2787        }
2788        abandoned.push(id);
2789    }
2790    abandoned
2791}
2792
2793#[derive(Debug, Clone, Serialize, Deserialize)]
2794struct TaskWorker {
2795    opts: Opts,
2796    queue: PathBuf,
2797    task: String,
2798    #[serde(default)]
2799    lane: PermitKind,
2800    #[serde(default)]
2801    standalone: bool,
2802}
2803
2804#[doc(hidden)]
2805pub struct TaskWorkerLease {
2806    pub job: crate::worker::Job,
2807    dir: PathBuf,
2808    lease: Option<crate::worker::Lease>,
2809}
2810
2811impl TaskWorkerLease {
2812    pub fn release_lease(&mut self) {
2813        self.lease = None;
2814    }
2815}
2816
2817impl Drop for TaskWorkerLease {
2818    fn drop(&mut self) {
2819        self.release_lease();
2820        let _ = std::fs::remove_dir_all(&self.dir);
2821    }
2822}
2823
2824/// Reserve a task worker without launching a process, for integration tests.
2825#[doc(hidden)]
2826pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2827    let request = TaskWorker {
2828        opts: Opts::default(),
2829        queue: home.join("queue"),
2830        task: task.to_owned(),
2831        lane: PermitKind::default(),
2832        standalone: true,
2833    };
2834    let (job, lease) = crate::worker::running_fixture(
2835        home,
2836        &format!("task:{task}"),
2837        serde_json::to_value(request)?,
2838    )?;
2839    Ok(TaskWorkerLease {
2840        dir: home.join("workers").join("jobs").join(&job.id),
2841        job,
2842        lease: Some(lease),
2843    })
2844}
2845
2846fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2847    Ok(crate::worker::active(home)?
2848        .into_iter()
2849        .filter(|job| job.kind == "task")
2850        .collect())
2851}
2852
2853fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2854    task_jobs(home)?
2855        .into_iter()
2856        .filter_map(
2857            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2858                Ok(request) if !request.standalone => Some(Ok(job)),
2859                Ok(_) => None,
2860                Err(error) => Some(Err(error.into())),
2861            },
2862        )
2863        .collect()
2864}
2865
2866/// Whether an independent scheduler can be controlled without its web parent.
2867#[must_use]
2868pub fn managed(home: &Path) -> bool {
2869    match crate::worker::active(home) {
2870        Err(error) => {
2871            tracing::error!("cannot determine scheduler ownership: {error:#}");
2872            true
2873        }
2874        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2875        Ok(_) => {
2876            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2877                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2878        }
2879    }
2880}
2881
2882/// Start a detached, singleton scheduler using this executable generation.
2883pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2884    anyhow::ensure!(
2885        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2886        "the scheduler is stopping; wait for retirement before starting it again"
2887    );
2888    crate::worker::spawn(
2889        home,
2890        "scheduler",
2891        "scheduler",
2892        serde_json::to_value(opts.absolute()?)?,
2893    )
2894    .await
2895}
2896
2897fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2898    home.join("worker-parks").join(format!("{}.json", job.id))
2899}
2900
2901fn request_task_park(
2902    home: &Path,
2903    job: &crate::worker::Job,
2904    cause: crate::run::ParkCause,
2905) -> Result<()> {
2906    let path = park_request_path(home, job);
2907    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2908    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2909    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2910}
2911
2912/// Stop dispatch immediately; only an explicit park reaches existing workers.
2913pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2914    if control == crate::worker::Control::Park {
2915        for job in owned_task_jobs(home)? {
2916            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2917        }
2918    }
2919    crate::worker::request(home, "scheduler", control)
2920}
2921
2922/// Resolve what a restart would replace without signalling the scheduler.
2923pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2924    if let Some(job) = crate::worker::active(home)?
2925        .into_iter()
2926        .find(|job| job.kind == "scheduler")
2927    {
2928        return serde_json::from_value(job.payload)
2929            .context("read detached scheduler options")
2930            .map(Some);
2931    }
2932    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2933        && crate::worker::try_lease(home, "scheduler")?.is_none()
2934    {
2935        let path = home.join("scheduler-options.json");
2936        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2937        return serde_json::from_slice(&body)
2938            .context("decode detached scheduler options")
2939            .map(Some);
2940    }
2941    Ok(None)
2942}
2943
2944/// Replace the scheduler, leaving all active task and conversation jobs alone.
2945pub async fn restart_detached(home: &Path) -> Result<()> {
2946    let Some(opts) = scheduler_restart_options(home)? else {
2947        return Ok(());
2948    };
2949    request_control(home, crate::worker::Control::Stop)?;
2950    loop {
2951        let reserved = crate::worker::active(home)?
2952            .iter()
2953            .any(|job| job.kind == "scheduler");
2954        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2955            break;
2956        }
2957        tokio::time::sleep(Duration::from_millis(100)).await;
2958    }
2959    spawn_detached(home, &opts).await?;
2960    Ok(())
2961}
2962
2963/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2964pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2965    let opts: Opts = serde_json::from_value(payload)?;
2966    let _ = home;
2967    serve_until(opts, Stop::new()).await
2968}
2969
2970/// Execute and settle one task with the queue claim owned by this process.
2971pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2972    let request: TaskWorker = serde_json::from_value(payload)?;
2973    let queue = Queue::at(request.queue);
2974    let key = format!("task:{}", request.task);
2975    let job = task_jobs(home)?
2976        .into_iter()
2977        .find(|job| job.key == key)
2978        .context("task worker reservation is missing")?;
2979    let park_path = park_request_path(home, &job);
2980    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2981    // our durable reservation. Never execute before that ownership hand-off.
2982    let _claim = loop {
2983        match queue.claim(&request.task) {
2984            Ok(claim) => break claim,
2985            // Only contention (the claim file exists) is worth waiting out; an
2986            // I/O failure must end this worker instead of pinning its lane.
2987            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2988                return Err(e.context("claim the task for its worker"));
2989            }
2990            Err(_) => {
2991                sweep_stale_claims(&queue, STALE_CLAIM);
2992                tokio::time::sleep(Duration::from_millis(50)).await;
2993            }
2994        }
2995    };
2996    let mut task = queue.get(&request.task)?;
2997    if !task.status.runnable()
2998        || (!request.standalone
2999            && request.lane
3000                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
3001    {
3002        return Ok(());
3003    }
3004    let stop = Stop::new();
3005    let watcher = {
3006        let home = home.to_path_buf();
3007        let stop = stop.clone();
3008        let park_path = park_path.clone();
3009        tokio::spawn(async move {
3010            loop {
3011                if crate::worker::control(&home, &key).ok().flatten().is_some() {
3012                    let cause = std::fs::read(&park_path)
3013                        .ok()
3014                        .and_then(|body| serde_json::from_slice(&body).ok())
3015                        .unwrap_or(crate::run::ParkCause::Operator);
3016                    stop.park(cause);
3017                    return;
3018                }
3019                tokio::time::sleep(Duration::from_millis(200)).await;
3020            }
3021        })
3022    };
3023    let quota = if request.standalone {
3024        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3025    } else {
3026        let status = Arc::new(Mutex::new(Status::new()));
3027        Box::pin(attempt(
3028            &request.opts,
3029            &queue,
3030            &status,
3031            &stop,
3032            crate::graph::Pause::new(),
3033            &mut task,
3034        ))
3035        .await
3036    };
3037    watcher.abort();
3038    let _ = std::fs::remove_file(park_path);
3039    persist_cooldown(home, &quota).await?;
3040    Ok(())
3041}
3042
3043/// Launch the standalone task worker with a claim-to-reservation handoff.
3044/// Returns only after the worker owns a durable execution reservation.
3045pub async fn spawn_claimed(
3046    home: &Path,
3047    opts: &Opts,
3048    queue: &Queue,
3049    task: &Task,
3050    claim: crate::queue::Claim,
3051) -> Result<crate::worker::Job> {
3052    let request = TaskWorker {
3053        opts: opts.absolute()?,
3054        queue: std::path::absolute(queue.root())?,
3055        task: task.id.clone(),
3056        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
3057        standalone: true,
3058    };
3059    let job = crate::worker::spawn(
3060        home,
3061        "task",
3062        &format!("task:{}", task.id),
3063        serde_json::to_value(request)?,
3064    )
3065    .await?;
3066    drop(claim);
3067    Ok(job)
3068}
3069
3070/// Transfer a standalone caller's claim only after the detached worker is live,
3071/// then follow that worker to its final (non-automatically-retrying) outcome.
3072pub async fn run_detached_claimed(
3073    opts: &Opts,
3074    queue: &Queue,
3075    task: &mut Task,
3076    claim: crate::queue::Claim,
3077) -> Result<()> {
3078    let home = crate::run::home();
3079    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3080    loop {
3081        // Reconcile execution leases even without a scheduler. A dead worker
3082        // must become a reported failure, never an infinite persisted wait.
3083        crate::worker::active(&home)?;
3084        let current = crate::worker::get(&home, &job.id)?;
3085        if matches!(
3086            current.status,
3087            crate::worker::Status::Finished | crate::worker::Status::Failed
3088        ) {
3089            *task = queue.get(&task.id)?;
3090            anyhow::ensure!(
3091                current.status != crate::worker::Status::Failed,
3092                "task worker failed: {}",
3093                current.result.as_deref().unwrap_or("unknown failure")
3094            );
3095            return Ok(());
3096        }
3097        tokio::time::sleep(Duration::from_millis(200)).await;
3098    }
3099}
3100
3101async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3102    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3103        let _lease = loop {
3104            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3105                break lease;
3106            }
3107            tokio::time::sleep(Duration::from_millis(10)).await;
3108        };
3109        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3110            let path = home.join("task-quota-cooldown.json");
3111            let temporary = path.with_extension("json.tmp");
3112            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3113            std::fs::rename(temporary, path)?;
3114        }
3115    }
3116    Ok(())
3117}
3118
3119fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3120    match std::fs::read(home.join("task-quota-cooldown.json")) {
3121        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3122        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3123        Err(error) => Err(error.into()),
3124    }
3125}
3126
3127/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3128///
3129/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3130/// sets, so there is one loop body rather than two that drift apart the first
3131/// time the retry policy changes on only one of them.
3132pub async fn serve(opts: Opts) -> Result<()> {
3133    tracing::info!(
3134        "automatic update and restart requires magi web; standalone serve does not restart"
3135    );
3136    serve_until(opts, Stop::new()).await
3137}
3138
3139/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3140///
3141/// A stop retires dispatch promptly, including while a worker launch is being
3142/// acknowledged. Already reserved workers own their attempts independently and
3143/// finish with their started executable. Explicit park additionally forwards
3144/// durable park requests; neither scheduler retirement nor update does so.
3145///
3146/// While the queue is empty the stop is honoured within one wakeup rather than
3147/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3148/// caller that taps stop does not sit through the remainder of a sleep.
3149pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3150    let opts = opts.absolute()?;
3151    let home = crate::run::home();
3152    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3153        .context("another scheduler already owns this home")?;
3154    if let Some(reading) = read_status(&home)
3155        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3156    {
3157        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3158    }
3159    if !crate::worker::active(&home)?
3160        .iter()
3161        .any(|job| job.kind == "scheduler")
3162    {
3163        crate::worker::clear_control(&home, "scheduler")?;
3164    }
3165    std::fs::write(
3166        home.join("scheduler-options.json"),
3167        serde_json::to_vec(&opts)?,
3168    )?;
3169    let control = {
3170        let home = home.clone();
3171        let stop = stop.clone();
3172        tokio::spawn(async move {
3173            loop {
3174                match crate::worker::control(&home, "scheduler").ok().flatten() {
3175                    Some(crate::worker::Control::Park) => {
3176                        let _ = request_control(&home, crate::worker::Control::Park);
3177                        stop.park(crate::run::ParkCause::Operator);
3178                        break;
3179                    }
3180                    Some(crate::worker::Control::Stop) => {
3181                        stop.stop();
3182                        break;
3183                    }
3184                    None => {}
3185                }
3186                tokio::time::sleep(Duration::from_millis(100)).await;
3187            }
3188        })
3189    };
3190    let signal = {
3191        let stop = stop.clone();
3192        tokio::spawn(async move {
3193            if tokio::signal::ctrl_c().await.is_ok() {
3194                stop.stop();
3195                tracing::info!("scheduler shutdown requested; independent workers continue");
3196            }
3197        })
3198    };
3199
3200    let worktrees_root = opts
3201        .worktrees_root
3202        .clone()
3203        .unwrap_or_else(crate::run::default_worktree_root);
3204    let outcome = drive(
3205        &opts,
3206        &Queue::open(),
3207        &status_path(),
3208        &crate::run::home(),
3209        &worktrees_root,
3210        &stop,
3211    )
3212    .await;
3213
3214    signal.abort();
3215    control.abort();
3216    outcome
3217}
3218
3219/// The loop proper: setup, poll, teardown, with the queue and the status file
3220/// supplied rather than discovered.
3221///
3222/// All three of `home`, `worktrees_root` and the queue/status paths are
3223/// parameters rather than resolved here, for the same reason:
3224/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3225/// so a unit test that pinned it would fight every other test in the binary,
3226/// and a loop that resolved its own worktree bay could only be exercised
3227/// against the operator's real `~/wt/<repo>` - publishing over a live
3228/// daemon's status file, claiming tasks out of a live backlog, and, since
3229/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3230/// whatever the operator actually has on disk.
3231async fn drive(
3232    opts: &Opts,
3233    queue: &Queue,
3234    status_file: &Path,
3235    home: &Path,
3236    worktrees_root: &Path,
3237    stop: &Stop,
3238) -> Result<()> {
3239    // The status file is a *snapshot*, not a stream of events: a reader only
3240    // ever wants the latest values, and every tick rewrites the whole file
3241    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3242    // while an mpsc channel would force the loop to re-send unchanged fields on
3243    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3244    // for no gain. The lock is only ever held across a field assignment, never
3245    // across an await.
3246    let recovery_cfg = prepare(&opts.repo, opts).ok();
3247    let daemon_cfg = recovery_cfg
3248        .as_ref()
3249        .map(|c| c.daemon.clone())
3250        .unwrap_or_default();
3251    let reconciled = crate::driver::reconcile(home);
3252    if !reconciled.is_empty() {
3253        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3254    }
3255    let mut initial_status = Status::new();
3256    let owned = owned_task_jobs(home)?;
3257    initial_status.current = current_work(home, Timestamp::now())
3258        .into_iter()
3259        .filter(|current| {
3260            owned
3261                .iter()
3262                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3263        })
3264        .collect();
3265    initial_status.idle = initial_status.current.is_empty();
3266    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3267        recovery_cfg.as_ref(),
3268        daemon_cfg.max_deputies,
3269    ));
3270    let status = Arc::new(Mutex::new(initial_status));
3271    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3272    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3273
3274    // Read once at startup, not per task: how many runs this loop drives at
3275    // once is a property of the machine running it, not of whichever
3276    // repository a given task happens to name - see
3277    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3278    // fact in the same sense the agent roster is.
3279    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3280
3281    tracing::info!(
3282        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3283        queue.root().display(),
3284        opts.poll.as_secs(),
3285        opts.max_attempts,
3286        concurrency,
3287        if daemon_cfg.pause_for_interrupts {
3288            ", interrupts enabled"
3289        } else {
3290            ""
3291        }
3292    );
3293
3294    let outcome = tokio::select! {
3295        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3296            max_concurrent: concurrency,
3297            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3298            recovery_cfg,
3299        }) => outcome,
3300        () = async {
3301            while !stop.stopped() {
3302                tokio::time::sleep(Duration::from_millis(25)).await;
3303            }
3304        } => {
3305            if stop.parking() {
3306                request_control(home, crate::worker::Control::Park)?;
3307            }
3308            Ok(())
3309        }
3310    };
3311
3312    stop.busy.store(0, Ordering::SeqCst);
3313    beat.abort();
3314    clear_status_at(status_file);
3315    outcome
3316}
3317
3318/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3319/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3320pub(crate) fn release_watch_settings_from_config(
3321    home: &Path,
3322    repo: &Path,
3323    cfg: &Config,
3324) -> (Vec<PathBuf>, u64) {
3325    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3326        .into_iter()
3327        .map(|r| r.path)
3328        .collect();
3329    // Repositories the daemon has worked in, wherever they live: a task may
3330    // name one outside `[repos] roots`, and its release PR must be watched too.
3331    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3332        .list()
3333        .into_iter()
3334        .map(|t| t.repo)
3335        .collect();
3336    let runs = home.join("runs");
3337    for id in crate::run::list_ids_in(&runs) {
3338        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3339            .ok()
3340            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3341            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3342        known.extend(repo);
3343    }
3344    for k in known {
3345        let k = k.canonicalize().unwrap_or(k);
3346        if k.join(".git").exists() && !paths.contains(&k) {
3347            paths.push(k);
3348        }
3349    }
3350    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3351    if !paths.contains(&own) {
3352        paths.push(own);
3353    }
3354    (paths, cfg.daemon.release_stall_minutes)
3355}
3356
3357/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3358const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3359
3360/// Refresh the status file on a fixed tick.
3361///
3362/// Separate from the loop because a run takes tens of minutes: a status file
3363/// written only between tasks would look stale for the whole of every run, and
3364/// a reader would report the daemon dead exactly while it was busiest.
3365async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3366    loop {
3367        tokio::time::sleep(HEARTBEAT).await;
3368        let snapshot = {
3369            let mut guard = lock(&status);
3370            guard.updated_at = Timestamp::now();
3371            guard.clone()
3372        };
3373        if let Err(e) = write_status_to(&path, &snapshot) {
3374            // A failed heartbeat must not take the daemon down: the loop is the
3375            // product, the status file is only the window onto it.
3376            tracing::warn!("could not refresh the daemon status file: {e:#}");
3377        }
3378    }
3379}
3380
3381/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3382/// if so, whether that wait is over.
3383#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3384enum LandResume {
3385    /// The task's last run is not parked on a land approval; schedule it
3386    /// like any other candidate.
3387    NotLanding,
3388    /// Parked in `land`, waiting on a question nobody has answered yet.
3389    /// Left alone: attempting it now would only re-observe the same pull
3390    /// request and park again, spending a `gh` call on a decision that has
3391    /// not changed since the last time this was checked.
3392    StillWaiting,
3393    /// Parked in `land`, and the question is settled - answered or
3394    /// abandoned. Resuming this is the one kind of candidate that must not
3395    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3396    Ready,
3397}
3398
3399/// Classify a runnable candidate by whether it is parked on a land-merge
3400/// approval. Read-only - no claim taken, nothing written - so it is cheap
3401/// enough to call on every candidate, every poll.
3402fn land_resume_state(task: &Task) -> LandResume {
3403    if task.sync_only.is_some() {
3404        return LandResume::NotLanding;
3405    }
3406    let Some(run_id) = task.execution_runs().last() else {
3407        return LandResume::NotLanding;
3408    };
3409    let Ok(state) = RunState::load(run_id) else {
3410        return LandResume::NotLanding;
3411    };
3412    if !state.parked {
3413        return LandResume::NotLanding;
3414    }
3415    if state.status == RunStatus::Landing
3416        && state.land_approval.as_ref().is_some_and(|binding| {
3417            ask::Questions::open()
3418                .get_for_effects(&binding.question)
3419                .is_ok_and(|q| {
3420                    q.run == state.id
3421                        && q.resolution()
3422                            .as_deref()
3423                            .is_some_and(crate::merge_decision::stops)
3424                })
3425        })
3426    {
3427        return LandResume::Ready;
3428    }
3429    if !implementers_match(task, &state) {
3430        return LandResume::NotLanding;
3431    }
3432    // Parked in `land` on the merge approval, or at `merge` on the owner's
3433    // word about a title/body the posting gate withheld. Told apart by the
3434    // run's own record, not by a status both can share.
3435    let node = if state.status == RunStatus::Landing {
3436        land::APPROVAL_NODE
3437    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3438        crate::github_text::ASK_NODE
3439    } else {
3440        return LandResume::NotLanding;
3441    };
3442    let store = ask::Questions::open();
3443    let waiting = store
3444        .list_for_effects()
3445        .into_iter()
3446        .filter(|q| &q.run == run_id && q.node == node)
3447        .max_by(|a, b| a.id.cmp(&b.id));
3448    let Some(mut q) = waiting else {
3449        return LandResume::Ready;
3450    };
3451    if !q.status.open() {
3452        // Repair spends agent resources and must obey concurrency and quota
3453        // waits; only a merge/hold decision may use the decision-only lane.
3454        if q.resolution().as_deref() == Some(land::REPAIR) {
3455            return if state.liveness(false) == Liveness::Live {
3456                LandResume::StillWaiting
3457            } else {
3458                LandResume::NotLanding
3459            };
3460        }
3461        return LandResume::Ready;
3462    }
3463    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3464    // nobody ever answered; land's approval bypasses that wait entirely (see
3465    // `land::approval_gate`), so the same deadline has to be enforced here
3466    // instead, or `graph.answer_timeout` silently stops meaning anything for
3467    // a land approval and a run can sit `StillWaiting` forever with nobody
3468    // told to look at it.
3469    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3470    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3471    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3472        q.abandon(format!(
3473            "no answer within {}s of asking",
3474            timeout.as_secs().max(1)
3475        ));
3476        // If this can't be persisted, do not treat the wait as settled on a
3477        // guess: fall through and try again next poll.
3478        if store.put(&mut q).is_ok() {
3479            return LandResume::Ready;
3480        }
3481    }
3482    LandResume::StillWaiting
3483}
3484
3485/// How often the loop rechecks for new work while something it already
3486/// started is still running, rather than sleeping out the whole
3487/// [`Opts::poll`] interval.
3488///
3489/// Short on purpose: this is what lets a land-merge approval that comes back
3490/// while another task is mid-competition be noticed and resumed within a
3491/// fraction of a second, not within the next multi-second poll.
3492const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3493
3494/// How often [`poll`] rechecks the shared build cache against its cap at a
3495/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3496/// waiting for the queue to run dry.
3497///
3498/// A queue that never empties means the `janitor` call at the bottom of this
3499/// loop's fully-idle branch can go unreached for as long as the backlog
3500/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3501/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3502/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3503/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3504/// backlog of short tasks does not pay for that walk on every poll.
3505const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3506
3507/// State of [`poll`]'s own interrupt-scheduling sequence - see
3508/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3509/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3510/// both kept free of `Task`'s non-identity fields on purpose: every decision
3511/// here turns only on task ids and which ones are in flight, so the "never
3512/// more than one run at once" and "exactly one resume" invariants can be
3513/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3514/// queue - which is exactly the coverage this feature's first two attempts
3515/// were missing.
3516///
3517/// Persisted after every transition, so scheduler replacement preserves the
3518/// interrupt's exclusive turn and the interrupted task's priority resume.
3519#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3520enum Interrupt {
3521    /// No interrupt sequence in progress. Ordinary dispatch applies.
3522    Idle,
3523    /// `interrupt_task` is runnable and exactly one other run is in flight;
3524    /// `parked` names that one task's id. Dispatch is withheld from
3525    /// everyone, including `interrupt_task` itself, until it has left
3526    /// flight - only then is `interrupt_task` let through.
3527    ///
3528    /// `parked` is a `Vec` rather than a bare id for symmetry with
3529    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3530    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3531    /// when exactly one run is in flight, so it is guaranteed to hold
3532    /// exactly one entry in practice - see that branch's own doc for why
3533    /// more than one is deliberately never attempted.
3534    Parking {
3535        parked: Vec<String>,
3536        interrupt_task: String,
3537    },
3538    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3539    /// withheld from everyone until it leaves flight - merged, failed, held,
3540    /// it makes no difference - at which point the sequence moves to
3541    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3542    /// going straight to `Idle` would hand `parked` back to ordinary
3543    /// priority-order dispatch, where a higher-priority task filed in the
3544    /// meantime could start ahead of it.
3545    Running {
3546        parked: Vec<String>,
3547        interrupt_task: String,
3548    },
3549    /// `interrupt_task` left flight; `parked` still names the one run this
3550    /// sequence owes a resume. Dispatch is withheld from everyone except
3551    /// that task - see [`interrupt_gate`] - so the resume this feature
3552    /// promises is never raced by, or run alongside, an unrelated candidate.
3553    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3554    /// own doc on abandonment - the moment it is no longer runnable at all.
3555    Resuming { parked: Vec<String> },
3556}
3557
3558/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3559/// and `runnable` are read-only snapshots of this tick's reality, and the
3560/// only side effect the caller still owes the world is asking whichever
3561/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3562/// site.
3563///
3564/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3565/// accepted rather than a narrower type because that is what [`poll`] already
3566/// has on hand from [`runnable`], and building a second, smaller list on
3567/// every tick just to satisfy this signature would cost more than it proves.
3568///
3569/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3570/// back to a task they are waiting on no longer being [`runnable`] - held,
3571/// blocked, deleted, or finished by some other means entirely, all of which
3572/// an operator can do to a task sitting in the queue with no claim on it at
3573/// all, at any moment, interrupt sequence or not. Without this check the
3574/// sequence would wait forever for a dispatch that can never come, and
3575/// `interrupt_gate` would withhold every other task in the queue right along
3576/// with it - a single `magi task hold` on the wrong id turning into a
3577/// daemon that never dispatches anything again.
3578fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3579    match state {
3580        Interrupt::Idle => {
3581            // Not just "something to interrupt": exactly one thing. More
3582            // than one run in flight only happens above the default
3583            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3584            // one resume, never run alongside anything else" only because
3585            // it is only ever seeded with exactly one id - see
3586            // `Interrupt::Resuming`'s own doc on why releasing more than one
3587            // parked id back to ordinary dispatch cannot be made safe
3588            // against that same setting's own extra concurrency slots.
3589            // Waiting here for the herd to settle to one is the
3590            // simplification this feature's own constraints ask for rather
3591            // than a second concurrency model to reconcile with the first.
3592            if in_flight.len() != 1 {
3593                return Interrupt::Idle;
3594            }
3595            match runnable.iter().find(|t| t.interrupt) {
3596                Some(t) => Interrupt::Parking {
3597                    parked: in_flight.to_vec(),
3598                    interrupt_task: t.id.clone(),
3599                },
3600                None => Interrupt::Idle,
3601            }
3602        }
3603        Interrupt::Parking {
3604            parked,
3605            interrupt_task,
3606        } => {
3607            if in_flight.iter().any(|id| parked.contains(id)) {
3608                // Still waiting for what was in flight to actually stop.
3609                Interrupt::Parking {
3610                    parked,
3611                    interrupt_task,
3612                }
3613            } else if in_flight.contains(&interrupt_task) {
3614                Interrupt::Running {
3615                    parked,
3616                    interrupt_task,
3617                }
3618            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3619                // The parked run(s) are gone, but the interrupt task has not
3620                // been dispatched yet on this tick - `interrupt_gate` is
3621                // what lets it through next.
3622                Interrupt::Parking {
3623                    parked,
3624                    interrupt_task,
3625                }
3626            } else {
3627                // The interrupt task itself is no longer runnable - see this
3628                // function's own doc on abandonment. The parked run(s) still
3629                // get their guaranteed resume; there is simply no interrupt
3630                // to run ahead of them any longer.
3631                Interrupt::Resuming { parked }
3632            }
3633        }
3634        Interrupt::Running {
3635            parked,
3636            interrupt_task,
3637        } => {
3638            if in_flight.contains(&interrupt_task) {
3639                Interrupt::Running {
3640                    parked,
3641                    interrupt_task,
3642                }
3643            } else {
3644                // The interrupt task's own run reached a terminal status,
3645                // whichever one - this is the *only* trigger that moves the
3646                // sequence on, driven straight off the same in-flight
3647                // bookkeeping `poll` already reaps every tick, not a second,
3648                // independent poll of anything.
3649                Interrupt::Resuming { parked }
3650            }
3651        }
3652        Interrupt::Resuming { parked } => {
3653            if in_flight.iter().any(|id| parked.contains(id)) {
3654                // One of the parked runs has been dispatched - the resume
3655                // this sequence owed is fulfilled. Whatever else is left in
3656                // `parked` (ordinarily nothing, at the default concurrency
3657                // of one) rejoins ordinary priority-order dispatch, same as
3658                // any other runnable task.
3659                Interrupt::Idle
3660            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3661                Interrupt::Resuming { parked }
3662            } else {
3663                // Abandonment (see this function's own doc): nothing left in
3664                // `parked` is even runnable any longer.
3665                Interrupt::Idle
3666            }
3667        }
3668    }
3669}
3670
3671/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3672/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3673/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3674/// indistinguishable from any other runnable task - exactly the "off does
3675/// nothing" this feature promises.
3676fn advance_interrupt_tick(
3677    enabled: bool,
3678    state: Interrupt,
3679    in_flight: &[String],
3680    runnable: &[Task],
3681) -> Interrupt {
3682    if !enabled {
3683        return Interrupt::Idle;
3684    }
3685    advance_interrupt(state, in_flight, runnable)
3686}
3687
3688/// Which of this tick's runnable candidates the interrupt sequence actually
3689/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3690/// each half is assertable on its own: this is the half that keeps a
3691/// competition and an interrupt from ever running at the same moment.
3692fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3693    match state {
3694        Interrupt::Idle => candidates,
3695        Interrupt::Parking {
3696            parked,
3697            interrupt_task,
3698        } => {
3699            if in_flight.iter().any(|id| parked.contains(id)) {
3700                Vec::new()
3701            } else {
3702                candidates
3703                    .into_iter()
3704                    .filter(|t| &t.id == interrupt_task)
3705                    .collect()
3706            }
3707        }
3708        Interrupt::Running { .. } => Vec::new(),
3709        // At most one: even if `parked` names more than one id (more than
3710        // one run was in flight when the sequence began, only possible
3711        // above the default `max_concurrent_runs = 1`), only the first match
3712        // is offered. Capping this to a single candidate - not merely to
3713        // `parked`'s own ids - is what makes "exactly one resume, never two
3714        // dispatched together" true regardless of how many ordinary slots
3715        // happen to be free this tick.
3716        Interrupt::Resuming { parked } => candidates
3717            .into_iter()
3718            .find(|t| parked.contains(&t.id))
3719            .into_iter()
3720            .collect(),
3721    }
3722}
3723
3724/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3725/// bundled into one parameter so `poll`'s own signature stays readable -
3726/// see [`drive`]'s call site for where these are actually read.
3727struct DispatchLimits {
3728    /// How many *ordinary* candidates run at once. See
3729    /// [`crate::config::Daemon::max_concurrent_runs`].
3730    max_concurrent: usize,
3731    /// See [`crate::config::Daemon::pause_for_interrupts`].
3732    pause_for_interrupts: bool,
3733    recovery_cfg: Option<Config>,
3734}
3735
3736/// Which semaphore, if any, dispatching a candidate should draw its permit
3737/// from.
3738///
3739/// Pure and separate from [`poll`]'s loop body for the same reason
3740/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3741/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3742/// exactly the policy this feature adds, and a policy only exercisable by
3743/// running the whole loop is a policy nobody checks.
3744#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3745enum PermitKind {
3746    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3747    /// Checked first - a task can be both a land resume and marked
3748    /// [`Task::urgent`], and the resume's own "must not queue behind
3749    /// anything" guarantee takes precedence.
3750    None,
3751    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3752    /// (never in addition to trying) the ordinary pool. This is what lets
3753    /// an urgent task dispatch while every ordinary slot is already checked
3754    /// out, and what stops a second urgent task from opening a third run: it
3755    /// waits on this same one-slot semaphore rather than falling through to
3756    /// the ordinary one.
3757    Urgent,
3758    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3759    /// above.
3760    #[default]
3761    Ordinary,
3762}
3763
3764/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3765/// own boolean, already computed by the caller from [`land_resume_state`].
3766fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3767    if priority {
3768        PermitKind::None
3769    } else if urgent {
3770        PermitKind::Urgent
3771    } else {
3772        PermitKind::Ordinary
3773    }
3774}
3775
3776fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3777    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3778        (0usize, 0usize),
3779        |(ordinary, urgent), request| match request.lane {
3780            PermitKind::Ordinary => (ordinary + 1, urgent),
3781            PermitKind::Urgent => (ordinary, urgent + 1),
3782            PermitKind::None => (ordinary, urgent),
3783        },
3784    );
3785    (
3786        limit.saturating_sub(ordinary),
3787        1usize.saturating_sub(urgent),
3788    )
3789}
3790
3791/// Why a runnable candidate was not dispatched. This does not alter policy.
3792#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3793enum SkipReason {
3794    ClaimUnavailable,
3795    RereadFailed,
3796    NoLongerRunnable,
3797    WaitingOnLanding,
3798    CoolingDown,
3799    OrdinaryCapacity,
3800    UrgentCapacity,
3801    InterruptGate,
3802}
3803
3804impl SkipReason {
3805    fn key(self) -> &'static str {
3806        match self {
3807            Self::ClaimUnavailable => "claim_unavailable",
3808            Self::RereadFailed => "reread_failed",
3809            Self::NoLongerRunnable => "no_longer_runnable",
3810            Self::WaitingOnLanding => "waiting_on_landing",
3811            Self::CoolingDown => "cooling_down",
3812            Self::OrdinaryCapacity => "ordinary_capacity",
3813            Self::UrgentCapacity => "urgent_capacity",
3814            Self::InterruptGate => "interrupt_gate",
3815        }
3816    }
3817
3818    fn describe(self) -> &'static str {
3819        match self {
3820            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3821            Self::RereadFailed => "could not re-read it",
3822            Self::NoLongerRunnable => "no longer runnable",
3823            Self::WaitingOnLanding => "waiting on landing",
3824            Self::CoolingDown => "quota cooldown",
3825            Self::OrdinaryCapacity => "no free ordinary slot",
3826            Self::UrgentCapacity => "urgent slot busy",
3827            Self::InterruptGate => "withheld by the interrupt sequence",
3828        }
3829    }
3830}
3831
3832/// A reason count from a completed dispatch scan.
3833#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3834pub struct DispatchReasonCount {
3835    /// Stable string key, so readers can preserve future reasons.
3836    pub reason: String,
3837    /// Candidates skipped for this reason.
3838    pub count: usize,
3839}
3840
3841/// Observations from a completed scan, not a fresh queue estimate.
3842#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3843pub struct DispatchWait {
3844    /// Runnable candidates before the interrupt gate.
3845    pub runnable: usize,
3846    /// Counts in descending order, with stable reason order for ties.
3847    pub reasons: Vec<DispatchReasonCount>,
3848}
3849
3850type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3851
3852fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3853    if runnable == 0 {
3854        return None;
3855    }
3856    let mut counts = std::collections::BTreeMap::new();
3857    for (_, reason) in skips {
3858        *counts.entry(*reason).or_insert(0usize) += 1;
3859    }
3860    let mut counts: Vec<_> = counts.into_iter().collect();
3861    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3862    Some(DispatchWait {
3863        runnable,
3864        reasons: counts
3865            .into_iter()
3866            .map(|(reason, count)| DispatchReasonCount {
3867                reason: reason.key().to_owned(),
3868                count,
3869            })
3870            .collect(),
3871    })
3872}
3873
3874fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3875    before
3876        .iter()
3877        .filter(|id| !after.iter().any(|task| &task.id == *id))
3878        .map(|id| (id.clone(), SkipReason::InterruptGate))
3879        .collect()
3880}
3881
3882fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3883    if *previous == current {
3884        return false;
3885    }
3886    *previous = current;
3887    true
3888}
3889
3890struct DispatchClaim {
3891    task: Task,
3892    claim: crate::queue::Claim,
3893    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3894}
3895
3896/// Claim and re-read before choosing a lane: a queue listing may predate an
3897/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3898fn claim_dispatch(
3899    queue: &Queue,
3900    candidate: &Task,
3901    cooling_down: bool,
3902    ordinary: &Arc<tokio::sync::Semaphore>,
3903    urgent: &Arc<tokio::sync::Semaphore>,
3904) -> std::result::Result<DispatchClaim, SkipReason> {
3905    let claim = queue
3906        .claim(&candidate.id)
3907        .map_err(|_| SkipReason::ClaimUnavailable)?;
3908    let task = match queue.get(&candidate.id) {
3909        Ok(t) if t.status.runnable() => t,
3910        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3911        Err(e) => {
3912            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3913            return Err(SkipReason::RereadFailed);
3914        }
3915    };
3916    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
3917        let mut held = task;
3918        hold.apply(&mut held);
3919        record(queue, &mut held);
3920        return Err(SkipReason::NoLongerRunnable);
3921    }
3922    let resume = land_resume_state(&task);
3923    if resume == LandResume::StillWaiting {
3924        return Err(SkipReason::WaitingOnLanding);
3925    }
3926    let priority = resume == LandResume::Ready;
3927    if !priority && cooling_down {
3928        return Err(SkipReason::CoolingDown);
3929    }
3930    // Never borrow an ordinary slot when the single urgent slot is busy.
3931    // Keep scanning other candidates when either pool has no free slot.
3932    let permit = match permit_kind(priority, task.urgent) {
3933        PermitKind::None => None,
3934        PermitKind::Urgent => Some(
3935            Arc::clone(urgent)
3936                .try_acquire_owned()
3937                .map_err(|_| SkipReason::UrgentCapacity)?,
3938        ),
3939        PermitKind::Ordinary => Some(
3940            Arc::clone(ordinary)
3941                .try_acquire_owned()
3942                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3943        ),
3944    };
3945    // Persist the dispatch order under the claim, before config discovery or
3946    // coordination waits can reorder concurrent starts.
3947    let stamp = Timestamp::now();
3948    let mut task = task;
3949    task.dispatched_at = Some(stamp);
3950    if let Err(e) = queue.modify(&task.id, |t| {
3951        t.dispatched_at = Some(stamp);
3952        true
3953    }) {
3954        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3955    }
3956    Ok(DispatchClaim {
3957        task,
3958        claim,
3959        permit,
3960    })
3961}
3962
3963/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3964/// teardown and cannot skip the teardown on an early return.
3965///
3966/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3967/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3968/// land approval that has since been answered is dispatched outside that
3969/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3970/// the whole point of parking there is that it must not queue behind
3971/// whatever else the loop happens to be running, even at the default of one.
3972/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3973/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3974/// these exemptions is still subject to the interrupt gate below, urgent
3975/// included: a land-resume or urgent candidate is exactly as much "something
3976/// else running" as an ordinary one from the interrupt sequence's point of
3977/// view, and letting either slip through while a run is being parked, or
3978/// while the interrupt task itself has the floor, is precisely the second
3979/// run 75dd's own "at most one run, ever, at once" guarantee must never
3980/// allow - see [`Interrupt`]'s own doc.
3981#[derive(Serialize, Deserialize)]
3982struct ServiceWorker {
3983    opts: Opts,
3984    queue: PathBuf,
3985    worktrees_root: PathBuf,
3986    operation: String,
3987}
3988
3989fn load_conductor(home: &Path) -> Result<Conductor> {
3990    match std::fs::read(home.join("conductor-state.json")) {
3991        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3992        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3993        Err(error) => Err(error.into()),
3994    }
3995}
3996
3997fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
3998    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
3999        .into_iter()
4000        .map(|c| c.task)
4001        .collect();
4002    let stalled = stalled_tasks(queue, home, Timestamp::now());
4003    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4004    let finished = finished_tasks(queue)
4005        .into_iter()
4006        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4007        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4008        .collect();
4009    let queued = queued_tasks(queue)
4010        .into_iter()
4011        .filter(|t| !live.contains(&t.id))
4012        .collect();
4013    (queued, stalled, finished)
4014}
4015
4016// Separate latest dispatch and worker receipts expose version handoff and skips
4017// without erasing the last completed scan or treating observations as authority.
4018fn retention_service_receipt(
4019    home: &Path,
4020    operation: &str,
4021    phase: &str,
4022    outcome: &str,
4023    detail: &str,
4024    cfg: Option<&Config>,
4025) {
4026    if !matches!(operation, "housekeeping" | "disk-pressure") {
4027        return;
4028    }
4029    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
4030        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4031        "operation": operation, "outcome": outcome, "detail": detail,
4032        "auto_fold": cfg.map(|c| c.disk.auto_fold),
4033        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4034    if let Err(error) = crate::fold_evidence::atomic_write(
4035        &home.join(format!("source-eviction-{operation}-{phase}.json")),
4036        &serde_json::to_vec(&receipt).expect("service receipt"),
4037    ) {
4038        tracing::warn!("retention service receipt failed: {error:#}");
4039    }
4040}
4041
4042async fn start_service(
4043    home: &Path,
4044    opts: &Opts,
4045    queue: &Queue,
4046    worktrees_root: &Path,
4047    operation: &str,
4048    cfg: Option<&Config>,
4049    busy: bool,
4050) -> Result<()> {
4051    // Fetch policy is live configuration, unlike question recovery capacity.
4052    // Reload before both cadence and eligibility, including disabled -> enabled.
4053    let fetch_cfg = if operation == "fetch" {
4054        match prepare(&opts.repo, opts) {
4055            Ok(cfg) => Some(cfg),
4056            Err(error) => {
4057                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4058                return Ok(());
4059            }
4060        }
4061    } else {
4062        None
4063    };
4064    let cfg = fetch_cfg.as_ref().or(cfg);
4065    let ticks = home.join("service-ticks");
4066    std::fs::create_dir_all(&ticks)?;
4067    let receipt = ticks.join(format!("daemon-{operation}"));
4068    let last = std::fs::read(&receipt)
4069        .ok()
4070        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4071    let interval = match operation {
4072        "disk-pressure" => 30,
4073        "chat-goals" => 60,
4074        "cache" => CACHE_CHECK_INTERVAL_SECS,
4075        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4076        _ => opts.poll.as_secs().max(1),
4077    };
4078    let now = Timestamp::now();
4079    if !cache_check_due(last, now, interval) {
4080        retention_service_receipt(
4081            home,
4082            operation,
4083            "dispatch",
4084            "skipped",
4085            "cadence not due",
4086            cfg,
4087        );
4088        return Ok(());
4089    }
4090    let key = format!("service:daemon-{operation}");
4091    if crate::worker::active(home)?
4092        .iter()
4093        .any(|job| job.key == key)
4094    {
4095        retention_service_receipt(
4096            home,
4097            operation,
4098            "dispatch",
4099            "skipped",
4100            "service worker already active",
4101            cfg,
4102        );
4103        return Ok(());
4104    }
4105    let eligible = match operation {
4106        "conductor" => {
4107            let (queued, stalled, finished) = conductor_work(queue, home);
4108            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4109                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4110        }
4111        "maintenance" => {
4112            queue.list().iter().any(|task| {
4113                crate::triage::disk_wait_eligible(task)
4114                    && task
4115                        .disk_checked_at
4116                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4117            }) || Questions::at(home.join("questions"))
4118                .list_for_effects()
4119                .iter()
4120                .any(|q| {
4121                    q.chosen_action().is_some_and(|action| action.maintenance())
4122                        && !home
4123                            .join("choice-actions")
4124                            .join(format!("{}.json", q.id))
4125                            .exists()
4126                })
4127        }
4128        "housekeeping" => !busy && runnable(queue).is_empty(),
4129        "cache" => {
4130            !busy
4131                && !runnable(queue).is_empty()
4132                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4133        }
4134        "disk-pressure" => busy,
4135        "fetch" => {
4136            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4137        }
4138        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4139            .list()
4140            .iter()
4141            .any(|talk| {
4142                talk.status.open()
4143                    && talk.pending.is_empty()
4144                    && talk.pending_attachments.is_empty()
4145                    && talk.goals.iter().any(|goal| goal.active())
4146            }),
4147        _ => false,
4148    };
4149    if !eligible {
4150        retention_service_receipt(
4151            home,
4152            operation,
4153            "dispatch",
4154            "skipped",
4155            if operation == "housekeeping" {
4156                "active work or runnable task queue"
4157            } else {
4158                "no active work; idle housekeeping owns scan"
4159            },
4160            cfg,
4161        );
4162        return Ok(());
4163    }
4164    retention_service_receipt(
4165        home,
4166        operation,
4167        "dispatch",
4168        "launching",
4169        "eligible and cadence due",
4170        cfg,
4171    );
4172    let request = ServiceWorker {
4173        opts: opts.absolute()?,
4174        queue: std::path::absolute(queue.root())?,
4175        worktrees_root: std::path::absolute(worktrees_root)?,
4176        operation: operation.to_owned(),
4177    };
4178    if let Err(error) =
4179        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
4180    {
4181        retention_service_receipt(
4182            home,
4183            operation,
4184            "dispatch",
4185            "error",
4186            &format!("worker launch: {error:#}"),
4187            cfg,
4188        );
4189        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4190    }
4191    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4192    Ok(())
4193}
4194
4195/// Finite maintenance jobs survive scheduler replacement without duplicating
4196/// agent calls or cancelling an operation between its effect and receipt.
4197pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4198    let request: ServiceWorker = serde_json::from_value(payload)?;
4199    let opts = &request.opts;
4200    let queue = Queue::at(request.queue);
4201    let questions = Questions::at(home.join("questions"));
4202    match request.operation.as_str() {
4203        "chat-goals" => {
4204            let talks = crate::talk::Talks::at(home.join("talks"));
4205            crate::chat_goal_runtime::sweep(&talks, false).await;
4206        }
4207        "maintenance" => {
4208            apply_maintenance_choices(&queue, &questions, home).await;
4209            triage::monitor_disk_waits(
4210                &queue,
4211                &questions,
4212                opts.config.as_deref(),
4213                Timestamp::now(),
4214            );
4215        }
4216        "conductor" => {
4217            let path = home.join("conductor-state.json");
4218            let mut conductor = load_conductor(home)?;
4219            let (queued, stalled, finished) = conductor_work(&queue, home);
4220            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4221                && conductor.worth_a_look(&queue, &stalled, &finished)
4222            {
4223                let cfg = prepare(&opts.repo, opts)?;
4224                conductor
4225                    .maybe_run(
4226                        &cfg,
4227                        &opts.repo,
4228                        &queue,
4229                        &questions,
4230                        home,
4231                        &queued,
4232                        &stalled,
4233                        &finished,
4234                        opts.max_attempts,
4235                    )
4236                    .await;
4237                let temporary = path.with_extension("json.tmp");
4238                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4239                std::fs::rename(temporary, path)?;
4240            }
4241        }
4242        "fetch" => {
4243            let cfg = prepare(&opts.repo, opts)?;
4244            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4245                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4246                tracing::debug!("fetch origins: {outcome:?}");
4247            }
4248        }
4249        "cache" => {
4250            if task_jobs(home)?.is_empty() {
4251                let mut checked = None;
4252                maybe_prune_cache_between_runs(
4253                    &opts.repo,
4254                    opts,
4255                    home,
4256                    &Stop::new(),
4257                    &mut checked,
4258                    Timestamp::now(),
4259                )
4260                .await;
4261            }
4262        }
4263        "disk-pressure" => {
4264            if let Ok(cfg) = prepare(&opts.repo, opts) {
4265                retention_service_receipt(
4266                    home,
4267                    "disk-pressure",
4268                    "worker",
4269                    "running",
4270                    "retention sweep",
4271                    Some(&cfg),
4272                );
4273                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4274                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4275                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4276                }
4277                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4278                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4279                }
4280                for current in current_work(home, Timestamp::now()) {
4281                    if let Ok(state) = RunState::load_under(&current.run, home)
4282                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4283                    {
4284                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4285                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4286                        }) {
4287                            request_task_park(
4288                                home,
4289                                &job,
4290                                crate::run::ParkCause::Interrupt {
4291                                    reason: reason.clone(),
4292                                },
4293                            )?;
4294                        }
4295                        notices::raise_in(
4296                            home,
4297                            Notice::warn(
4298                                "disk:pressure",
4299                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4300                            ),
4301                        );
4302                    }
4303                }
4304            } else {
4305                retention_service_receipt(
4306                    home,
4307                    "disk-pressure",
4308                    "worker",
4309                    "error",
4310                    "configuration could not be loaded",
4311                    None,
4312                );
4313            }
4314        }
4315        "housekeeping" => {
4316            if task_jobs(home)?.is_empty() {
4317                match prepare(&opts.repo, opts) {
4318                    Ok(cfg) => {
4319                        retention_service_receipt(
4320                            home,
4321                            "housekeeping",
4322                            "worker",
4323                            "running",
4324                            "retention sweep",
4325                            Some(&cfg),
4326                        );
4327                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4328                    }
4329                    Err(error) => retention_service_receipt(
4330                        home,
4331                        "housekeeping",
4332                        "worker",
4333                        "error",
4334                        &format!("configuration: {error:#}"),
4335                        None,
4336                    ),
4337                }
4338                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4339                resweep_superseded_attempts(&queue, home);
4340                triage_held(&queue, home, opts).await;
4341            } else {
4342                retention_service_receipt(
4343                    home,
4344                    "housekeeping",
4345                    "worker",
4346                    "skipped",
4347                    "task worker became active",
4348                    None,
4349                );
4350            }
4351        }
4352        operation => bail!("unknown daemon service {operation}"),
4353    }
4354    Ok(())
4355}
4356
4357/// Only a different request under the same key is a dispatch handoff race.
4358/// Our own unacknowledged reservation is a startup failure, not competing work:
4359/// stop dispatch without fencing it, so an already detached child may still run.
4360fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4361    let key = format!("task:{}", request.task);
4362    let payload = serde_json::to_value(request)?;
4363    if crate::worker::active(home)?
4364        .iter()
4365        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4366    {
4367        tracing::warn!(
4368            "task {} acquired a competing worker reservation: {error:#}",
4369            crate::run::short_of(&request.task)
4370        );
4371        return Ok(());
4372    }
4373    tracing::error!("task worker startup stopped dispatch: {error:#}");
4374    notices::raise_in(
4375        home,
4376        Notice::error(
4377            "loop:worker-startup",
4378            // Startup diagnostics may contain private child-process details;
4379            // keep them in the local error/log rather than the chat or notifier.
4380            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),
4381        ).link(Link::Task { id: request.task.clone() }),
4382    );
4383    Err(error).with_context(|| {
4384        format!(
4385            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4386            crate::run::short_of(&request.task)
4387        )
4388    })
4389}
4390
4391async fn poll(
4392    opts: &Opts,
4393    queue: &Queue,
4394    status: &Arc<Mutex<Status>>,
4395    home: &Path,
4396    worktrees_root: &Path,
4397    stop: &Stop,
4398    limits: DispatchLimits,
4399) -> Result<()> {
4400    let mut attempted = Vec::new();
4401    let mut settling_once_services = false;
4402    let interrupt_path = home.join("scheduler-interrupt.json");
4403    let mut interrupt = match std::fs::read(&interrupt_path) {
4404        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4405        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4406        Err(error) => return Err(error.into()),
4407    };
4408    let mut previous = std::collections::BTreeSet::<String>::new();
4409    let mut previous_skips = DispatchSkips::new();
4410    while !stop.stopped() {
4411        let jobs: Vec<_> = crate::worker::active(home)?
4412            .into_iter()
4413            .filter(|job| job.kind == "task")
4414            .collect();
4415        let requests: Vec<_> = jobs
4416            .iter()
4417            .map(|job| {
4418                serde_json::from_value::<TaskWorker>(job.payload.clone())
4419                    .with_context(|| format!("read live task worker {}", job.id))
4420            })
4421            .collect::<Result<_>>()?;
4422        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4423        let owned: std::collections::BTreeSet<_> = requests
4424            .iter()
4425            .filter(|r| !r.standalone)
4426            .map(|r| r.task.clone())
4427            .collect();
4428        let current: Vec<_> = requests
4429            .iter()
4430            .zip(&jobs)
4431            .filter(|(request, _)| !request.standalone)
4432            .map(|(request, job)| Current {
4433                worker: Some(job.id.clone()),
4434                task: request.task.clone(),
4435                run: queue
4436                    .get(&request.task)
4437                    .ok()
4438                    .and_then(|task| task.execution_runs().last().cloned())
4439                    .unwrap_or_default(),
4440            })
4441            .collect();
4442        {
4443            let mut snapshot = lock(status);
4444            snapshot.polls += 1;
4445            snapshot.completed += previous.difference(&owned).count();
4446            snapshot.current = current;
4447            snapshot.idle = owned.is_empty();
4448            snapshot.dispatch_wait = None;
4449        }
4450        previous = owned.clone();
4451        stop.busy.store(owned.len(), Ordering::SeqCst);
4452
4453        // Slots are reconstructed from durable reservations and OS-held worker
4454        // leases, not this scheduler's lifetime or mutable task urgency.
4455        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4456        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4457        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4458        let mut permits = Vec::new();
4459        sweep_stale_claims(queue, STALE_CLAIM);
4460        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4461        reclaim_abandoned_runs(home, Timestamp::now());
4462        let questions = Questions::at(home.join("questions"));
4463
4464        // Deterministic: no model, run before the conductor sees anything so
4465        // its input reflects the queue's current, already-resolved state.
4466        crate::task_chat::sweep(
4467            queue,
4468            &crate::talk::Talks::at(home.join("talks")),
4469            &questions,
4470            home,
4471        );
4472        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4473            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4474        {
4475            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4476        }
4477        repair_choice_offers(&questions);
4478        resolve_blockers(queue, &questions);
4479        apply_task_choice_actions(queue, &questions, home);
4480        triage::apply_answers(queue, &questions);
4481        reconcile_task_questions(queue, &questions);
4482        let talks = crate::talk::Talks::at(home.join("talks"));
4483        crate::chat_notify::sweep(queue, &talks, home);
4484        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4485        crate::chat_watch::sweep(home, &talks);
4486        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4487            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4488        }
4489        let mut turns = tokio::task::JoinSet::new();
4490        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4491        // start_turns dispatches detached turns; no paid work lives in this set.
4492        while turns.join_next().await.is_some() {}
4493
4494        crate::consult::start_services(
4495            home,
4496            &opts.repo,
4497            limits.recovery_cfg.as_ref(),
4498            opts.config.as_deref(),
4499        )
4500        .await?;
4501        for operation in [
4502            "conductor",
4503            "maintenance",
4504            "housekeeping",
4505            "disk-pressure",
4506            "cache",
4507            "fetch",
4508            "chat-goals",
4509        ] {
4510            // Once an idle --once drain starts settling services, subsequent
4511            // scans only consume their effects. An expired cadence receipt
4512            // must not start another service and keep the drain alive.
4513            if settling_once_services {
4514                break;
4515            }
4516            if operation == "chat-goals" && stop.parking() {
4517                continue;
4518            }
4519            start_service(
4520                home,
4521                opts,
4522                queue,
4523                worktrees_root,
4524                operation,
4525                limits.recovery_cfg.as_ref(),
4526                !live.is_empty(),
4527            )
4528            .await?;
4529        }
4530        let latest = crate::worker::active(home)?;
4531        if latest.iter().any(|job| job.key == "service:daemon-cache")
4532            || latest
4533                .iter()
4534                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4535        {
4536            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4537            continue;
4538        }
4539        let candidates: Vec<Task> = runnable(queue)
4540            .into_iter()
4541            .filter(|task| !live.contains(&task.id))
4542            .filter(|task| !opts.once || !attempted.contains(&task.id))
4543            .collect();
4544        let in_flight: Vec<_> = owned.iter().cloned().collect();
4545        let prior_interrupt = std::mem::discriminant(&interrupt);
4546        interrupt = advance_interrupt_tick(
4547            limits.pause_for_interrupts,
4548            interrupt,
4549            &in_flight,
4550            &candidates,
4551        );
4552        // Same-variant transitions preserve their identities. Only an actual
4553        // transition needs a durable write, atomically before sending controls.
4554        if prior_interrupt != std::mem::discriminant(&interrupt) {
4555            let temporary = interrupt_path.with_extension("json.tmp");
4556            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4557            std::fs::rename(temporary, &interrupt_path)?;
4558        }
4559        if let Interrupt::Parking {
4560            parked,
4561            interrupt_task,
4562        } = &interrupt
4563        {
4564            for job in jobs.iter().filter(|job| {
4565                parked
4566                    .iter()
4567                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4568            }) {
4569                if crate::worker::control(home, &job.key)?.is_none() {
4570                    request_task_park(
4571                        home,
4572                        job,
4573                        crate::run::ParkCause::Interrupt {
4574                            reason: format!(
4575                                "task {} asked to run first",
4576                                crate::run::short_of(interrupt_task)
4577                            ),
4578                        },
4579                    )?;
4580                }
4581            }
4582        }
4583        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4584        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4585        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4586        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4587        let mut started = false;
4588        let mut resync = false;
4589        for candidate in candidates {
4590            if stop.stopped() {
4591                break;
4592            }
4593            let DispatchClaim {
4594                task,
4595                claim,
4596                permit,
4597            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4598                Ok(claim) => claim,
4599                Err(reason) => {
4600                    skips.insert((candidate.id, reason));
4601                    continue;
4602                }
4603            };
4604            if crate::worker::active(home)?
4605                .iter()
4606                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4607            {
4608                drop(claim);
4609                resync = true;
4610                break;
4611            }
4612            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4613            let request = TaskWorker {
4614                opts: opts.absolute()?,
4615                queue: std::path::absolute(queue.root())?,
4616                task: task.id.clone(),
4617                lane,
4618                standalone: false,
4619            };
4620            // Keep the claim until spawn acknowledges the worker's durable
4621            // reservation. The worker then claims and re-reads before attempt.
4622            if let Err(error) = crate::worker::spawn(
4623                home,
4624                "task",
4625                &format!("task:{}", task.id),
4626                serde_json::to_value(&request)?,
4627            )
4628            .await
4629            {
4630                task_worker_spawn_error(home, &request, error)?;
4631                drop(claim);
4632                resync = true;
4633                break;
4634            }
4635            drop(claim);
4636            permits.extend(permit);
4637            attempted.push(task.id);
4638            started = true;
4639        }
4640        if !resync && !stop.stopped() {
4641            if !started {
4642                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4643            }
4644            if changed_dispatch_skips(&mut previous_skips, skips) {
4645                if previous_skips.is_empty() {
4646                    tracing::info!("dispatch skips cleared");
4647                }
4648                for (task, reason) in &previous_skips {
4649                    tracing::info!(
4650                        task,
4651                        reason = reason.key(),
4652                        "task {} skipped: {}",
4653                        crate::run::short_of(task),
4654                        reason.describe()
4655                    );
4656                }
4657            }
4658        }
4659        if started || resync {
4660            continue;
4661        }
4662        if owned.is_empty() && opts.once {
4663            settling_once_services = true;
4664            // These finite services can own queue claims or publish answers.
4665            // A skipped claim is not an idle queue until they have finished;
4666            // scan again afterwards so their changes are actually scheduled.
4667            if crate::worker::active(home)?.iter().any(|job| {
4668                job.kind == "daemon-service"
4669                    && matches!(
4670                        job.key.as_str(),
4671                        "service:daemon-housekeeping"
4672                            | "service:daemon-conductor"
4673                            | "service:daemon-maintenance"
4674                    )
4675            }) {
4676                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4677                continue;
4678            }
4679            break;
4680        }
4681        stop.idle(if live.is_empty() {
4682            opts.poll
4683        } else {
4684            RECHECK_WHILE_BUSY.min(opts.poll)
4685        })
4686        .await;
4687    }
4688    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4689    // every queue claim and Runner driver lease through outcome settlement.
4690    stop.busy.store(0, Ordering::SeqCst);
4691    lock(status).dispatch_wait = None;
4692    Ok(())
4693}
4694
4695/// A maintenance pass may briefly own the same record while a worker starts.
4696/// Wait without blocking the executor or charging an agent attempt, then read
4697/// ownership again under the acquired lock. Other I/O failures still fail closed.
4698async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4699    let busy = |error: &anyhow::Error| {
4700        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4701            error.kind() == std::io::ErrorKind::WouldBlock
4702                || cfg!(windows) && error.raw_os_error() == Some(33)
4703        })
4704    };
4705    match crate::pr_head::owner_lock(home, id) {
4706        Ok(lock) => return Ok(lock),
4707        Err(error) if busy(&error) => {}
4708        Err(error) => return Err(error),
4709    }
4710    let wait = RunState::load_under(id, home)?
4711        .config
4712        .graph
4713        .timeout_resource_wait;
4714    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4715}
4716
4717/// Historical successors do not revoke a still-resumable public owner. Scan
4718/// under the same lock as publication/driver claims, and fail closed on unknown
4719/// history before spending another attempt.
4720async fn public_resume_owner(
4721    home: &Path,
4722    runs: &[String],
4723    repo: &Path,
4724) -> Result<Option<RunState>> {
4725    let mut owner = None;
4726    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4727        let _lock = resume_owner_lock(home, id).await?;
4728        let state = RunState::load_under(id, home)?;
4729        if state.released()
4730            || state.retired_to.is_some()
4731            || state.pr_taken_over_by.is_some()
4732            || !crate::handover::landing_checkpoint(&state)
4733        {
4734            continue;
4735        }
4736        anyhow::ensure!(
4737            crate::git::toplevel(&state.repo).await?.canonicalize()?
4738                == crate::git::toplevel(repo).await?.canonicalize()?,
4739            "public owner repository differs; inspect run lineage"
4740        );
4741        anyhow::ensure!(
4742            owner.is_none(),
4743            "multiple retained public owners; inspect run lineage"
4744        );
4745        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4746            anyhow::bail!(reason.diagnostic(&state));
4747        }
4748        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4749        anyhow::ensure!(
4750            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4751            "public owner's driver is live or unknown; wait before retrying"
4752        );
4753        owner = Some(state);
4754    }
4755    Ok(owner)
4756}
4757
4758/// Run one claimed task to a terminal status and record the outcome.
4759///
4760/// Every transition is flushed to the queue as it happens, so the state on disk
4761/// is what actually occurred rather than what this process still intends to
4762/// write.
4763async fn attempt(
4764    opts: &Opts,
4765    queue: &Queue,
4766    status: &Arc<Mutex<Status>>,
4767    stop: &Stop,
4768    interrupt_pause: crate::graph::Pause,
4769    task: &mut Task,
4770) -> Vec<QuotaLoss> {
4771    if let Some(request) = task.sync_only.clone() {
4772        Box::pin(attempt_sync_only(
4773            queue,
4774            status,
4775            stop,
4776            interrupt_pause,
4777            task,
4778            request,
4779        ))
4780        .await;
4781        return Vec::new();
4782    }
4783    let repo = repo_for(task, &opts.repo);
4784    tracing::info!(
4785        "task {} — {} (repo {})",
4786        task.short(),
4787        task.title,
4788        repo.display()
4789    );
4790
4791    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4792        Ok(owner) => owner,
4793        Err(e) => {
4794            task.hold_machine(Some(format!(
4795                "Cannot verify existing public owner: {e:#}; no attempt started."
4796            )));
4797            record(queue, task);
4798            return Vec::new();
4799        }
4800    };
4801    let resume_runs = public_owner
4802        .as_ref()
4803        .map(|s| vec![s.id.clone()])
4804        .unwrap_or_else(|| task.execution_runs().to_vec());
4805
4806    // A stop spends no agent resources and uses the saved landing owner.
4807    // Current roster edits, missing attachments or a failed config fetch must
4808    // never turn it into a new implementation, or prevent a PR from closing.
4809    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4810        && previous
4811            .merge_decision
4812            .as_ref()
4813            .is_some_and(|decision| !decision.closed)
4814        && previous.status != RunStatus::Landing
4815        && !crate::merge_decision::resumable_hold(&previous)
4816    {
4817        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)));
4818        record(queue, task);
4819        return Vec::new();
4820    }
4821    let stop_owner = resume_runs
4822        .last()
4823        .and_then(|id| RunState::load(id).ok())
4824        .filter(|state| {
4825            crate::merge_decision::resumable_hold(state)
4826                || state.status == RunStatus::Landing
4827                    && state.land_approval.as_ref().is_some_and(|binding| {
4828                        Questions::open()
4829                            .get_for_effects(&binding.question)
4830                            .is_ok_and(|q| {
4831                                q.run == state.id
4832                                    && q.resolution()
4833                                        .as_deref()
4834                                        .is_some_and(crate::merge_decision::stops)
4835                            })
4836                    })
4837        });
4838    if let Some(owner) = stop_owner {
4839        let mut runner = match Runner::resume(&owner.id) {
4840            Ok(runner) => runner,
4841            Err(e) => {
4842                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4843                record(queue, task);
4844                return Vec::new();
4845            }
4846        };
4847        runner.on_pause(stop.pause());
4848        runner.watch_interrupt(interrupt_pause);
4849        let quota_before = runner.state.quota.clone();
4850        let before_start = task.clone();
4851        task.start(owner.id.clone());
4852        if let Err(error) = queue.put(task) {
4853            *task = before_start;
4854            let error = runner.fail_startup("task-start", error);
4855            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4856                task.record_startup_failure(failure.clone());
4857            }
4858            task.hold_manual(Some(format!(
4859                "Could not persist task start; no agents dispatched: {error:#}"
4860            )));
4861            record(queue, task);
4862            return Vec::new();
4863        }
4864        lock(status).current.push(Current {
4865            worker: None,
4866            task: task.id.clone(),
4867            run: owner.id,
4868        });
4869        runner.state.carry_dispatched_resumes(task);
4870        runner.state.next_pass_task_entry = true;
4871        let result = runner.execute().await;
4872        return finish_attempt(
4873            opts.max_attempts,
4874            queue,
4875            task,
4876            &runner.state,
4877            &quota_before,
4878            result,
4879        );
4880    }
4881
4882    if let Some(owner) = &public_owner
4883        && (task.fresh_start || !may_resume_run(owner, task))
4884    {
4885        task.hold_machine(Some(format!("Existing PR belongs to run {}; resume its authorized instructions or explicitly resolve its owner decision before starting a successor. No attempt started.", owner.id)));
4886        record(queue, task);
4887        return Vec::new();
4888    }
4889
4890    if let Some(state) = task
4891        .execution_runs()
4892        .last()
4893        .and_then(|id| RunState::load(id).ok())
4894        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4895    {
4896        task.hold_machine(Some(reason));
4897        record(queue, task);
4898        return Vec::new();
4899    }
4900
4901    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4902        && !task.fresh_start
4903        && task.pr_recovery.is_none()
4904    {
4905        // A pinned infrastructure resume continues the saved reservation;
4906        // it does not authorize another base-sync interval.
4907        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
4908            && task.review_branch.is_none()
4909            && task.assignment_accepts(&held)
4910            && compatible_run_instruction(&held, task)
4911            && task
4912                .resume_override
4913                .as_ref()
4914                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
4915        // Exhaustion authorization still takes the owner lock and execution
4916        // lease and rechecks liveness, retained HEAD and ownership.
4917        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
4918        {
4919            true
4920        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4921            let home = queue.root().parent().expect("queue has a home");
4922            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4923                Ok(()) => true,
4924                Err(error) => {
4925                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4926                    false
4927                }
4928            }
4929        } else {
4930            false
4931        };
4932        if !authorized {
4933            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())));
4934            // Retain the existing stop identity when an old release reached the queue.
4935            task.base_sync_notice(&held);
4936            task.resume_override = None;
4937            record(queue, task);
4938            return Vec::new();
4939        }
4940    }
4941    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
4942        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
4943            hold.apply(task);
4944            record(queue, task);
4945            return Vec::new();
4946        }
4947        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
4948            run,
4949            stop_id,
4950            generation,
4951            approval_at,
4952        }) => Some((run, stop_id, generation, approval_at)),
4953        None => None,
4954    };
4955    let unfinished = (!task.fresh_start)
4956        .then(|| unfinished_run(&resume_runs, task.short()))
4957        .flatten()
4958        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4959    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4960    if task.repair_grants.last().is_some_and(|receipt| {
4961        task.execution_runs().last() == Some(&receipt.request.run)
4962            && task.operator_decided_at == receipt.decision
4963            && previous
4964                .as_ref()
4965                .is_none_or(|run| run.id != receipt.request.run)
4966    }) {
4967        task.hold_unrequested_retry(Some(
4968            "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(),
4969        ));
4970        record(queue, task);
4971        return Vec::new();
4972    }
4973    if let Some(id) = &task.disk_resume_run
4974        && unfinished.as_ref() != Some(id)
4975    {
4976        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()));
4977        record(queue, task);
4978        return Vec::new();
4979    }
4980
4981    if !task.fresh_start
4982        && task.pr_recovery.is_none()
4983        && task.review_branch.is_none()
4984        && task.resume_override.is_none()
4985        && previous
4986            .as_ref()
4987            .is_some_and(|run| run.retired_to.is_some())
4988        && unfinished.is_none()
4989    {
4990        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()));
4991        record(queue, task);
4992        return Vec::new();
4993    }
4994
4995    let saved_recovery = previous.as_ref().filter(|run| {
4996        task.replacement.is_none()
4997            && task.pr_recovery.as_ref().is_some_and(|selected| {
4998                selected
4999                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5000                    .is_ok()
5001                    && selected_starter(selected, Some(run), unfinished.as_deref())
5002                        == Starter::Resume(run.id.clone())
5003            })
5004    });
5005
5006    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
5007    // failure here is the network's or the operator's, not the task's: hold
5008    // without spending an attempt, never fall back to a possibly stale copy.
5009    let explicit = match &task.overrides {
5010        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5011        Some(_) => opts.config.as_deref(),
5012        None => opts.config.as_deref(),
5013    };
5014    let (mut config, layers) = if let Some(run) = saved_recovery {
5015        // A matching resume owns its resolved configuration and evidence;
5016        // current layers and inherited overrides only configure new work.
5017        let mut saved = run.clone();
5018        if let Err(e) = saved.configure_recovery_resume() {
5019            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
5020            record(queue, task);
5021            return Vec::new();
5022        }
5023        (saved.config, Vec::new())
5024    } else {
5025        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
5026            Ok(loaded) => loaded,
5027            Err(e) => {
5028                let reason = format!("[config] {e:#}");
5029                record_config_failure(task, &e);
5030                task.last_error = Some(reason.clone());
5031                task.hold_machine(Some(reason));
5032                record(queue, task);
5033                return Vec::new();
5034            }
5035        };
5036        if let Err(e) = apply_options(&mut config, opts, task) {
5037            task.hold_manual(Some(format!(
5038                "[config] {e:#}; correct the merge override before releasing the task"
5039            )));
5040            record(queue, task);
5041            return Vec::new();
5042        }
5043        if let Some(selected) = &task.pr_recovery
5044            && let Err(e) = selected.configure(&mut config)
5045        {
5046            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
5047            record(queue, task);
5048            return Vec::new();
5049        }
5050        (config, layers)
5051    };
5052    let config_evidence = crate::pr_recovery::ConfigEvidence {
5053        layers,
5054        overrides: task.overrides.clone(),
5055        daemon_merge: task
5056            .overrides
5057            .as_ref()
5058            .is_none_or(|o| o.inherit_daemon_options)
5059            .then(|| opts.merge.clone())
5060            .flatten(),
5061    };
5062    apply_task_implementers(&mut config, task);
5063    if let Some(replacement) = &task.replacement {
5064        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
5065            old.liveness(false) == Liveness::Dead
5066                && old.merge_decision.as_ref().is_some_and(|d| {
5067                    d.closed
5068                        && d.question == replacement.question
5069                        && d.replacement_run.as_ref().is_none_or(|run| {
5070                            task.execution_runs().last() == Some(run)
5071                                && RunState::load(run).is_ok_and(|current| {
5072                                    current.replaces.as_ref().is_some_and(|pin| {
5073                                        pin.question == replacement.question
5074                                            && pin.agent == replacement.agent
5075                                    })
5076                                })
5077                        })
5078                })
5079        });
5080        if !safe {
5081            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()));
5082            record(queue, task);
5083            return Vec::new();
5084        }
5085        match config.agent(&replacement.agent) {
5086            Ok(agent) if crate::agent::installed(agent) => {}
5087            _ => {
5088                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)));
5089                record(queue, task);
5090                return Vec::new();
5091            }
5092        }
5093        config.graph.implementers = 1;
5094        config.graph.land_approval = true;
5095        config.merge.mode = MergeMode::Pr;
5096        config.graph.selected_implementer = Some(replacement.agent.clone());
5097    }
5098    let p = phrases(&config.graph.language);
5099    let start_failed = p.could_not_start;
5100    // Resolve once for both admission and settlement. The inputs are the
5101    // task's explicit sources (never prose), plus an explicit review source's
5102    // current head; review-only runs may rebase later, and neither fact can
5103    // refund a failed automatic generation.
5104    if let Ok(base) =
5105        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
5106            .await
5107        && let Ok(head) =
5108            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
5109    {
5110        let mut inputs = crate::queue::recovery_inputs(&task.sources);
5111        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
5112            let source = crate::git::rev_parse(&repo, branch)
5113                .await
5114                .unwrap_or_default();
5115            inputs.push_str(&format!(";review:{branch}:{source}"));
5116        }
5117        if let Some(reason) = task
5118            .recovery_exhausted(
5119                &head,
5120                &inputs,
5121                task.attempt_limit
5122                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
5123            )
5124            .filter(|_| {
5125                !task.repair_grants.last().is_some_and(|receipt| {
5126                    RunState::load(&receipt.request.run)
5127                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
5128                })
5129            })
5130        {
5131            task.hold_recovery_budget(
5132                reason,
5133                crate::queue::RecoveryAdmission { base: head, inputs },
5134            );
5135            record(queue, task);
5136            return Vec::new();
5137        }
5138        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
5139    }
5140
5141    // A resumable run of this task is carried on, never re-competed. The
5142    // candidates are built and paid for, and a fresh competition races a
5143    // second implementation against them.
5144    //
5145    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
5146    // started 3cbf on the same task a moment later, duplicating two and a
5147    // half hours of agent work. Then b25f stalled on a judge that timed out
5148    // and one that answered with no JSON - `quota: 0`, so nothing the machine
5149    // was to blame for - and 4043 started **one second** later, buying three
5150    // fresh implementations to reach the same panel. `RunStatus::resumable`
5151    // rather than `!done()` is what catches the second case: a stall is
5152    // terminal, and its cheap recovery re-asks only the absent seats.
5153    //
5154    // A load failure is warned about rather than silently read as "not
5155    // resumable": the alternative is exactly what let a schema mismatch on
5156    // run `eba2` fall through to a full re-competition with nobody told why.
5157    // `crate::conduct` is what actually offers a better answer than
5158    // `Runner::start` here (see `Recovery::Review`), once this task's next
5159    // failure shows it up as `held`/`failed` with the run state unreadable.
5160    // Keep a retained review selection intact until disk admission succeeds.
5161    let consume_review = !previous
5162        .as_ref()
5163        .is_some_and(|state| crate::repair_budget::pending(task, state));
5164    let review_branch = consume_review
5165        .then(|| review_branch_for(task, previous.as_ref()))
5166        .flatten();
5167    let branch_exists = match review_branch {
5168        Some(branch) => crate::git::branch_exists(&repo, branch)
5169            .await
5170            .unwrap_or(false),
5171        None => false,
5172    };
5173    // An explicit `magi review <branch>` is reviewed whatever happens to the
5174    // branch unless an explicit implementer change requires fresh work. An
5175    // unfinished run of the same task still wins, so a retry resumes.
5176    let proposed = review_retry_starter(
5177        task,
5178        previous.as_ref(),
5179        review_branch,
5180        branch_exists,
5181        unfinished.as_deref(),
5182    );
5183    let retry_selected = task.replacement.is_some()
5184        && task.resumption.is_some()
5185        && !task.fresh_start
5186        && previous.as_ref().is_some_and(|run| {
5187            run.replaces.is_some()
5188                && ((run.status == RunStatus::Failed && run.viable().is_empty())
5189                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
5190        });
5191    let stop_pin = task
5192        .resume_override
5193        .as_ref()
5194        .filter(|pin| {
5195            Questions::open()
5196                .get_for_effects(&pin.question_id)
5197                .is_ok_and(|q| {
5198                    q.node == land::APPROVAL_NODE
5199                        && q.resolution()
5200                            .as_deref()
5201                            .is_some_and(crate::merge_decision::stops)
5202                })
5203        })
5204        .and_then(|pin| pin.pinned_run.clone());
5205    let granted_run = task.repair_grants.last().and_then(|receipt| {
5206        let state = RunState::load(&receipt.request.run).ok()?;
5207        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
5208    });
5209    let starter = if let Some(run) = granted_run {
5210        Starter::Resume(run)
5211    } else if let Some(owner) = &public_owner {
5212        Starter::Resume(owner.id.clone())
5213    } else if let Some(run) = stop_pin {
5214        // Stop actions resume their exact owner even after seat-count edits;
5215        // they must never fall through to implementation or a takeover.
5216        Starter::Resume(run)
5217    } else if retry_selected {
5218        Starter::Resume(previous.as_ref().unwrap().id.clone())
5219    } else if let Some(selected) = &task.pr_recovery {
5220        if selected
5221            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5222            .is_ok()
5223        {
5224            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5225        } else {
5226            Starter::Review(selected.branch.clone())
5227        }
5228    } else {
5229        starter_with_implementers(task, previous.as_ref(), proposed)
5230    };
5231    // A retained execution still writes to its saved output volume. A newer
5232    // repository policy only selects the volume for a fresh run.
5233    let disk_reason = match &starter {
5234        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5235            || {
5236                RunState::load(id)
5237                    .ok()
5238                    .and_then(|run| disk_gate(&run.repo, &run.config))
5239            },
5240            |run| disk_gate(&run.repo, &run.config),
5241        ),
5242        _ => disk_gate(&repo, &config),
5243    };
5244    if let Some(reason) = disk_reason {
5245        task.notice_cause("disk-space", None, None);
5246        task.last_error = Some(reason.clone());
5247        let disk_checked_at = task.disk_checked_at;
5248        task.hold_machine(Some(reason.clone()));
5249        if matches!(starter, Starter::Resume(_)) {
5250            task.mark_disk_capacity();
5251        } else {
5252            task.mark_startup_disk_capacity();
5253        }
5254        task.disk_checked_at = disk_checked_at;
5255        record(queue, task);
5256        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5257        notices::raise(
5258            Notice::warn(
5259                &format!("disk:{}", repo.display()),
5260                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5261            )
5262            .link(Link::Task {
5263                id: task.id.clone(),
5264            }),
5265        );
5266        return Vec::new();
5267    }
5268    let review_branch = if consume_review {
5269        let valid = review_branch.is_some();
5270        task.review_instruction = None;
5271        task.review_branch.take().filter(|_| valid)
5272    } else {
5273        None
5274    };
5275    // An explicit resume pin must never degrade into a new competition or
5276    // takeover, including when its run stops being eligible after the answer.
5277    if let Some(pin) = &task.resume_override
5278        && let Some(run) = &pin.pinned_run
5279        && starter != Starter::Resume(run.clone())
5280    {
5281        let run = run.clone();
5282        task.notice_cause("resume-owner", Some(&run), None);
5283        task.hold_machine(Some(format!(
5284            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5285            task.id
5286        )));
5287        record(queue, task);
5288        return Vec::new();
5289    }
5290    // Automatic disk recovery resumes its retained run or stops: a changed
5291    // seat count or review branch must not turn it into a new competition.
5292    // No attempt is spent here.
5293    if let Some(run) = &task.disk_resume_run
5294        && starter != Starter::Resume(run.clone())
5295    {
5296        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()));
5297        record(queue, task);
5298        return Vec::new();
5299    }
5300    if task.replacement.is_some()
5301        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5302        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5303    {
5304        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()));
5305        record(queue, task);
5306        return Vec::new();
5307    }
5308    if let Some((ref run, ..)) = head_e2e_approval
5309        && starter != Starter::Resume(run.clone())
5310    {
5311        task.hold_machine(Some(format!(
5312            "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."
5313        )));
5314        record(queue, task);
5315        return Vec::new();
5316    }
5317    if let Some(reason) = retained_attempt_hold(
5318        task,
5319        &starter,
5320        config.disk.retained_attempt_limit,
5321        RunState::load,
5322    ) {
5323        // The review choice was consumed above. Preserve it across this hold
5324        // so a later release cannot silently become a fresh implementation.
5325        if let Starter::Review(branch) = &starter {
5326            task.review_branch = Some(branch.clone());
5327        }
5328        task.hold_unrequested_retry(Some(reason));
5329        record(queue, task);
5330        return Vec::new();
5331    }
5332    // Absolute paths of the files the task was filed with, re-read from the
5333    // task now so a file attached while it was held reaches a resumed run
5334    // too. A stored name whose file has gone is an error before any agent is
5335    // paid for, never a silent omission the implementer cannot notice.
5336    let attachments = match task_attachments(queue, task) {
5337        Ok(a) => a,
5338        Err(e) => {
5339            task.attempts += 1;
5340            task.fail_startup_target(
5341                "startup-attachments",
5342                e.name.clone(),
5343                format!("{start_failed}{e:#}"),
5344                opts.max_attempts,
5345            );
5346            record(queue, task);
5347            return Vec::new();
5348        }
5349    };
5350    let startup_pause = stop.pause();
5351    let startup_interrupt = interrupt_pause.clone();
5352    let wait = crate::repo_lock::WaitPolicy::new(
5353        Duration::from_secs(config.graph.timeout_resource_wait),
5354        move || startup_pause.parked() || startup_interrupt.parked(),
5355    );
5356    // Startup includes review takeover and recovery. Do not embed its large
5357    // future in both the wait scope and the surrounding attempt stack frame.
5358    let started = wait.scope(Box::pin(async { match &starter {
5359        Starter::Review(_) if task.pr_recovery.is_some() => {
5360            let selected = task.pr_recovery.clone().expect("selected recovery");
5361            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5362                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5363                    .await
5364                    .map(|mut r| {
5365                        r.state.attachments = attachments.clone();
5366                        r
5367                    }),
5368                Err(e) => Err(e),
5369            }
5370        }
5371        Starter::Review(branch) => {
5372            tracing::info!(
5373                "task {} reopens `{branch}` as a review-only pass",
5374                task.short()
5375            );
5376            // Every earlier attempt is superseded by the one being minted
5377            // now, so a branch one of them still holds may be taken over.
5378            let takeover = crate::handover::Takeover {
5379                earlier: task.earlier_attempts().to_vec(),
5380                home: crate::run::home(),
5381                choice: take_divergence_answer(branch, &config.merge.remote, task),
5382                task_instruction: Some(instruction_for(task)),
5383            };
5384            Runner::review_taking_over(
5385                &repo,
5386                branch,
5387                config,
5388                Some(takeover),
5389                crate::run::Origin::queue(&task.id),
5390            )
5391            .await
5392        }
5393        Starter::Resume(id) => {
5394            tracing::info!("resuming run {id} rather than competing again");
5395            Runner::resume(id).and_then(|mut r| {
5396                if retry_selected {
5397                    // The explicit queue release retries this same pinned
5398                    // implementation, preserving the attempt and worktrees.
5399                    for candidate in &mut r.state.candidates {
5400                        candidate.failed = None;
5401                        candidate.empty = false;
5402                        candidate.commits = 0;
5403                    }
5404                    r.state.status = RunStatus::Implementing;
5405                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5406                }
5407                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5408                    r.state.sources = task.sources.clone();
5409                }
5410                if r.state.prep_failure.is_some() {
5411                    let approval = task
5412                        .resumption
5413                        .as_ref()
5414                        .context("preparation retry requires an explicit task release")?;
5415                    r.retry_preparation(approval.at)?;
5416                }
5417                if let Some(instruction) =
5418                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5419                {
5420                    r.state.instruction = instruction;
5421                }
5422                r.state.attachments = attachments.clone();
5423                if task.replacement.is_some() {
5424                    r.state.config.merge.mode = MergeMode::Pr;
5425                    r.state.config.graph.land_approval = true;
5426                }
5427                // Replacements publish a new PR and ask again. Selected PR
5428                // recoveries keep their saved disposition; ordinary runs can
5429                // retain the task's merge override.
5430                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5431                    .overrides
5432                    .as_ref()
5433                    .and_then(|o| o.merge.as_deref())
5434                    .and_then(|m| merge_mode(m).ok())
5435                {
5436                    r.state.config.merge.mode = mode;
5437                }
5438                Ok(r)
5439            })
5440        }
5441        Starter::Start => {
5442            if let Some(branch) = &review_branch {
5443                tracing::warn!(
5444                    "conductor chose review for task {} but branch `{branch}` no longer \
5445                     exists; requeuing as a fresh competition instead",
5446                    task.short()
5447                );
5448            }
5449            let instruction = prepare_instruction(&starter, None, task)
5450                .unwrap_or_else(|| task.instruction.clone());
5451            Runner::start_naming(
5452                &repo,
5453                instruction,
5454                &task.title,
5455                config,
5456                crate::run::Origin::queue(&task.id),
5457            )
5458            .await
5459            .map(|mut r| {
5460                r.state.attachments = attachments.clone();
5461                r.state.sources = task.sources.clone();
5462                r
5463            })
5464        }
5465    }})).await;
5466    if let Err(error) = &started
5467        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5468    {
5469        task.record_startup_failure(failure.clone());
5470    }
5471    let mut runner = match started {
5472        Ok(r) => r,
5473        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5474            let detail = format!("{e:#}");
5475            task.last_error = Some(detail.clone());
5476            if e.is::<crate::build_target::AdmissionDiskWait>()
5477                && let Starter::Review(branch) = &starter
5478                && review_branch.is_some()
5479            {
5480                task.review_branch = Some(branch.clone());
5481                task.review_instruction = Some(task.instruction.clone());
5482            }
5483            if stop.parking() || interrupt_pause.parked() {
5484                let attempts = task.attempts;
5485                task.park(e.to_string());
5486                // Startup has not spent an attempt to refund.
5487                task.attempts = attempts;
5488            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5489                let disk_checked_at = task.disk_checked_at;
5490                task.hold_machine(Some(detail));
5491                task.mark_startup_disk_capacity();
5492                task.disk_checked_at = disk_checked_at;
5493            } else {
5494                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5495            }
5496            record(queue, task);
5497            return Vec::new();
5498        }
5499        // A branch an earlier attempt still holds and magi will not release
5500        // by itself is the operator's call, not a failed attempt: hold the
5501        // task with the reason, spend nothing, and say so on the bell.
5502        Err(e) if task.pr_recovery.is_some() => {
5503            task.startup_notice_cause("startup-public-head");
5504            task.attempts += 1;
5505            task.last_error = Some(format!("{start_failed}{e:#}"));
5506            task.hold_unrequested_retry(Some(format!(
5507                "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."
5508            )));
5509            record(queue, task);
5510            return Vec::new();
5511        }
5512        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5513            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5514                Some(r) => (p.handover_refused)(r),
5515                None => format!("{e:#}"),
5516            };
5517            task.startup_notice_cause("startup-handover");
5518            let reason = format!("{start_failed}{detail}");
5519            task.last_error = Some(reason.clone());
5520            // Consumed above by `take`; keep it so the released task retries
5521            // as a review of this same branch.
5522            let branch = match &starter {
5523                Starter::Review(branch) => Some(branch.clone()),
5524                _ => None,
5525            };
5526            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5527            // one page; the guidance rides in the reason, fixed per state so a
5528            // re-put never changes the wording and relights it.
5529            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5530            record(queue, task);
5531            tracing::warn!(
5532                "holding {} for a branch it cannot take over: {e:#}",
5533                task.short()
5534            );
5535            return Vec::new();
5536        }
5537        // A branch that differs between here and the remote in ways magi
5538        // cannot prove are the same change is a decision for the owner, not a
5539        // failed attempt: ask with both sides laid out, spend no attempt, and
5540        // let the answer requeue the task.
5541        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5542            let d = e
5543                .downcast_ref::<crate::reconcile::Diverged>()
5544                .expect("checked by the guard");
5545            let mut q = ask::Question::new(
5546                task.id.clone(),
5547                crate::reconcile::NODE.to_owned(),
5548                crate::reconcile::SEAT.to_owned(),
5549                d.summary(),
5550                d.detail(),
5551                d.choices(),
5552            );
5553            match Questions::open().put(&mut q) {
5554                Ok(()) => {
5555                    task.last_error = Some(format!("{e:#}"));
5556                    // Consumed above by `take`; the answer has to reach a review
5557                    // of this same branch, so keep pointing the task at it.
5558                    task.review_branch = Some(d.branch.clone());
5559                    task.review_instruction = Some(task.instruction.clone());
5560                    task.block(vec![q.id.clone()], Some(d.summary()));
5561                }
5562                Err(put) => {
5563                    tracing::warn!("could not file the divergence question: {put:#}");
5564                    task.attempts += 1;
5565                    task.fail_startup(
5566                        "startup-question-store",
5567                        format!("{start_failed}{e:#}"),
5568                        opts.max_attempts,
5569                    );
5570                }
5571            }
5572            record(queue, task);
5573            return Vec::new();
5574        }
5575        Err(e) => {
5576            // The answer was stale and nothing was applied: keep pointing at
5577            // the branch so the next attempt asks again against its new tips.
5578            // Nothing went wrong with the task, so no attempt is spent: a
5579            // budget one short of its limit must not hold it instead of
5580            // letting the question be asked again.
5581            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5582                && let Starter::Review(branch) = &starter
5583            {
5584                task.review_branch = Some(branch.clone());
5585                task.review_instruction = Some(task.instruction.clone());
5586                task.last_error = Some(format!("{start_failed}{e:#}"));
5587                task.status = crate::queue::TaskStatus::Failed;
5588                record(queue, task);
5589                return Vec::new();
5590            }
5591            task.attempts += 1;
5592            task.last_error = Some(format!("{start_failed}{e:#}"));
5593            task.startup_notice_cause("startup-source");
5594            task.hold_unrequested_retry(Some(format!(
5595                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5596            )));
5597            record(queue, task);
5598            return Vec::new();
5599        }
5600    };
5601    if !matches!(starter, Starter::Resume(_))
5602        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5603    {
5604        runner
5605            .state
5606            .event("build-cache", format!("{mode} selected by {source}"));
5607    }
5608    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5609        runner.state.recovery_config = Some(config_evidence);
5610    }
5611    if let Some(replacement) = &task.replacement {
5612        if matches!(starter, Starter::Start) {
5613            runner.state.instruction.push_str(&format!(
5614                "\n\n# Replacement review context\n{}",
5615                replacement.context
5616            ));
5617        }
5618        runner.state.replaces = Some(replacement.clone());
5619        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5620        if let Ok(mut old) = RunState::load(&replacement.run)
5621            && let Some(d) = &mut old.merge_decision
5622        {
5623            d.replacement_run = Some(runner.state.id.clone());
5624            old.event(
5625                "replacement",
5626                format!(
5627                    "replacement run {} owns the next attempt; old PR remains closed",
5628                    runner.state.id
5629                ),
5630            );
5631            if let Err(e) = old.save() {
5632                let error = runner.fail_startup("replacement-history", e);
5633                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5634                    task.record_startup_failure(failure.clone());
5635                }
5636                task.hold_manual(Some(format!(
5637                    "Could not link replacement history: {error:#}; no agents dispatched"
5638                )));
5639                record(queue, task);
5640                return Vec::new();
5641            }
5642        }
5643    }
5644    runner.state.task_instruction = Some(task.instruction.clone());
5645    // The follow-up depth is fixed now, while the task certainly exists:
5646    // deleting it later must not reset the cap (`crate::followup`).
5647    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5648    if runner.state.origin_chat.is_none() {
5649        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5650    }
5651    // A stop that means "park" reaches the graph through this handle.
5652    runner.on_pause(stop.pause());
5653    // `poll`'s interrupt scheduler reaches this one run - and no other -
5654    // through this handle. See `Pause`'s own doc for why these are never
5655    // the same one.
5656    runner.watch_interrupt(interrupt_pause);
5657
5658    // `start` has minted the run, so the task can now point at it. Persisting
5659    // `Running` before `execute` is what makes a crash mid-run legible.
5660    let run = runner.state.id.clone();
5661    let before_start = task.clone();
5662    task.start(run.clone());
5663    if let Err(error) = queue.put(task) {
5664        *task = before_start;
5665        let error = runner.fail_startup("task-start", error);
5666        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5667            task.record_startup_failure(failure.clone());
5668        }
5669        task.hold_manual(Some(format!(
5670            "Could not persist task start; no agents dispatched: {error:#}"
5671        )));
5672        record(queue, task);
5673        return Vec::new();
5674    }
5675    if task.status != TaskStatus::Running {
5676        // Queue::put kept a newer hold or continuation instead of this start.
5677        return Vec::new();
5678    }
5679    lock(status).current.push(Current {
5680        worker: None,
5681        task: task.id.clone(),
5682        run,
5683    });
5684
5685    // `RunState::quota` is the run's whole history across every resume, so
5686    // only what this execution added may arm the cooldown or earn a refund.
5687    let quota_before = runner.state.quota.clone();
5688    runner.state.carry_dispatched_resumes(task);
5689    runner.state.entry_resumption_generation =
5690        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
5691    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
5692        && runner.state.id == run
5693    {
5694        crate::head_e2e_stop::record_consumed_approval(
5695            &mut runner.state,
5696            &task.id,
5697            &stop_id,
5698            generation,
5699            approval_at,
5700        );
5701    }
5702    runner.state.next_pass_task_entry = true;
5703    let result = runner.execute().await;
5704    finish_attempt(
5705        opts.max_attempts,
5706        queue,
5707        task,
5708        &runner.state,
5709        &quota_before,
5710        result,
5711    )
5712}
5713
5714async fn attempt_sync_only(
5715    queue: &Queue,
5716    status: &Arc<Mutex<Status>>,
5717    stop: &Stop,
5718    interrupt: crate::graph::Pause,
5719    task: &mut Task,
5720    request: crate::base_sync_only::Request,
5721) {
5722    let result = async {
5723        anyhow::ensure!(
5724            task.status == TaskStatus::Queued
5725                && task.execution_runs().last() == Some(&request.run)
5726                && task.resume_override.as_ref().is_some_and(
5727                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5728                ),
5729            "sync-base-only request no longer owns the exact queued run"
5730        );
5731        let mut runner = Runner::resume(&request.run)?;
5732        anyhow::ensure!(
5733            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5734                .await?
5735                .is_none(),
5736            "the task still has a public execution owner"
5737        );
5738        anyhow::ensure!(
5739            !stop.parking() && !interrupt.parked(),
5740            "paused before base synchronization"
5741        );
5742        let original = task.clone();
5743        task.start(request.run.clone());
5744        task.attempts = original.attempts;
5745        if let Err(error) = queue.put(task) {
5746            *task = original;
5747            return Err(error);
5748        }
5749        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5750            return Ok(());
5751        }
5752        lock(status).current.push(Current {
5753            worker: None,
5754            task: task.id.clone(),
5755            run: request.run.clone(),
5756        });
5757        runner.on_pause(stop.pause());
5758        runner.watch_interrupt(interrupt);
5759        runner.execute_sync_only(request.clone()).await
5760    }
5761    .await;
5762    if task.sync_only.as_ref() == Some(&request) {
5763        let saved = RunState::load(&request.run).ok();
5764        let detail = result.err().map(|error| {
5765            format!("Base synchronization only: {error:#}; verification was not allowed")
5766        });
5767        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5768        record(queue, task);
5769    }
5770}
5771
5772/// Settle `task` after its run executed: the verdict, the diagnosis, the
5773/// supersession of earlier attempts and the save. Shared by the loop and by
5774/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5775/// Returns the quota losses this execution added to the run.
5776pub fn finish_attempt(
5777    max_attempts: usize,
5778    queue: &Queue,
5779    task: &mut Task,
5780    state: &RunState,
5781    quota_before: &[QuotaLoss],
5782    result: Result<()>,
5783) -> Vec<QuotaLoss> {
5784    let detail = match result {
5785        Ok(()) => describe(state),
5786        Err(e) => format!("{e:#}"),
5787    };
5788    let fresh = losses_this_attempt(quota_before, &state.quota);
5789    let verdict = Verdict {
5790        status: state.status,
5791        // A run that opened a pull request handed its work over, whatever the
5792        // gate then decided about merging it.
5793        left_pr: state.pr.is_some(),
5794        // Only a rate limit earns the task its attempt back - and only one
5795        // suffered now: a refund justified by a previous session's loss is
5796        // the same mistake as re-arming the cooldown from it. A stalled run
5797        // resumed without hitting quota again therefore spends its attempt,
5798        // like any other failure of the task's own.
5799        quota_hit: !fresh.is_empty(),
5800        // A run that parked was asked to stop; that is not a failure and must
5801        // not spend an attempt, or replacing the binary a few times would
5802        // exhaust a task's budget without an agent ever misbehaving.
5803        parked: state.parked,
5804        // A quota loss that left nothing viable is the same machine fact as a
5805        // `Stalled` quota loss; see `settle`'s doc table.
5806        no_viable_candidates: state.viable().is_empty(),
5807    };
5808    if let Some(replacement) = &state.replaces
5809        && let Some(pr) = &state.pr
5810        && let Ok(mut old) = RunState::load(&replacement.run)
5811        && let Some(d) = &mut old.merge_decision
5812    {
5813        d.replacement_pr = Some(pr.url.clone());
5814        let _ = old.save();
5815    }
5816    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5817    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5818        task.hold_unrequested_retry(Some(format!(
5819            "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.",
5820            task.short()
5821        )));
5822    }
5823    if task.status == TaskStatus::Done {
5824        supersede_prior_runs(task, &crate::run::home());
5825    }
5826    record(queue, task);
5827    tracing::info!(
5828        "task {} is {} after run {} ({})",
5829        task.short(),
5830        task.status.as_str(),
5831        state.short(),
5832        label(state.status)
5833    );
5834    fresh
5835}
5836
5837/// A task a hand-started run leaves runnable (failed with attempts to spare,
5838/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5839/// later must not spend agent calls on it. `magi task release` retries.
5840pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5841    // Parked work (including legacy Failed records with a parked run) is a
5842    // checkpoint or owner handoff, not an unrequested retry.
5843    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5844        && !awaiting_resume_with(task, RunState::load)
5845        // A run parked on the owner's word about a withheld PR title/body
5846        // resumes via `land_resume_state`, including review-only tasks that
5847        // `awaiting_resume_with` does not consider.
5848        && withheld_text_wait(task).is_none()
5849        && !(task.fresh_start && task.replacement.is_some())
5850    {
5851        let why = task.last_error.clone().map_or_else(
5852            || "the run did not finish".to_owned(),
5853            |e| format!("the run did not finish: {e}"),
5854        );
5855        task.hold_unrequested_retry(Some(format!(
5856            "{why}. It was started by hand, so it is not retried \
5857             automatically; `magi task release` retries it."
5858        )));
5859        record(queue, task);
5860    }
5861}
5862
5863/// Whether an attempt at a task whose newest run is `run` would resume that
5864/// run rather than start a fresh competition. `magi run --resume` hands a run
5865/// to a live loop only when this holds.
5866#[must_use]
5867pub fn loop_would_resume(run: &str) -> bool {
5868    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5869}
5870
5871/// A loop in another process that is alive right now: a fresh heartbeat in
5872/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5873/// carries the pid it published (`None` inside when it published none - a
5874/// fresh heartbeat is still evidence of a live loop).
5875///
5876/// The one judgement of "is somebody else serving this queue", shared by the
5877/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5878/// deciding whether to hand a task to the loop. A claim file proves nothing
5879/// here: whether a claim succeeds says nothing about whether its owner lives.
5880#[must_use]
5881pub fn foreign_loop(
5882    reading: Option<&Reading>,
5883    now: Timestamp,
5884    own_pid: u32,
5885) -> Option<Option<u32>> {
5886    let reading = reading.filter(|r| r.running(now))?;
5887    match reading.pid {
5888        Some(pid) if pid == own_pid => None,
5889        pid => Some(pid),
5890    }
5891}
5892
5893fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5894    reading.worker_protocol != Some(1)
5895        && (foreign_loop(Some(reading), now, own_pid).is_some()
5896            || reading
5897                .pid
5898                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5899}
5900
5901/// Low-level claimed-task execution shared by the detached standalone worker
5902/// and focused lifecycle fixtures. The caller must retain the queue claim for
5903/// this entire call. CLI callers transfer ownership through
5904/// [`run_detached_claimed`] instead of executing inside their own runtime.
5905///
5906/// The one deliberate difference from the loop: a task the attempt leaves
5907/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5908/// Nobody asked for a retry, and a daemon starting later must not spend agent
5909/// calls re-running a hand-started task behind the operator's back;
5910/// `magi task release` is the explicit retry.
5911pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5912    run_claimed_until(opts, queue, task, &Stop::new()).await;
5913}
5914
5915async fn run_claimed_until(
5916    opts: &Opts,
5917    queue: &Queue,
5918    task: &mut Task,
5919    stop: &Stop,
5920) -> Vec<QuotaLoss> {
5921    let status = Arc::new(Mutex::new(Status::new()));
5922    // An attempt embeds startup and graph futures. Keep it off the standalone
5923    // caller's stack, on both the initial execution and withheld-text resume.
5924    let mut quota = Box::pin(attempt(
5925        opts,
5926        queue,
5927        &status,
5928        stop,
5929        crate::graph::Pause::new(),
5930        task,
5931    ))
5932    .await;
5933    // A run parked on the owner's word about a withheld PR title/body has no
5934    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5935    // here with the claim still held, and resume once the question is settled
5936    // (answered, or abandoned at its deadline -> the neutral text).
5937    // A rejected reply files one more question (the gate asks at most twice),
5938    // so after a resume the run may be waiting again: keep going, with a fresh
5939    // limit for the new question. `resumes` bounds it even if a resume parks
5940    // without asking anything new.
5941    let mut resumes = 0;
5942    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5943        let Some(timeout) = withheld_text_wait(task) else {
5944            break;
5945        };
5946        eprintln!(
5947            "waiting for the owner's answer on a withheld pull request text \
5948             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5949        );
5950        // The deadline abandons the question itself; the extra margin only
5951        // covers an abandon that could not be saved.
5952        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5953        let ready = loop {
5954            match land_resume_state(task) {
5955                LandResume::StillWaiting
5956                    if !stop.parking() && std::time::Instant::now() < limit =>
5957                {
5958                    tokio::time::sleep(WITHHELD_POLL).await;
5959                }
5960                LandResume::Ready => break true,
5961                _ => break false,
5962            }
5963        };
5964        if !ready || stop.parking() {
5965            break;
5966        }
5967        resumes += 1;
5968        quota.extend(
5969            Box::pin(attempt(
5970                opts,
5971                queue,
5972                &status,
5973                stop,
5974                crate::graph::Pause::new(),
5975                task,
5976            ))
5977            .await,
5978        );
5979    }
5980    hold_if_runnable(queue, task);
5981    quota
5982}
5983
5984/// Resumes an in-process run makes for withheld-text questions: the gate asks
5985/// at most twice, plus one for a resume that asks nothing new.
5986const MAX_WITHHELD_RESUMES: u32 = 3;
5987
5988/// How often an in-process run rechecks its withheld-text question.
5989const WITHHELD_POLL: Duration = Duration::from_secs(15);
5990
5991/// The `answer_timeout` (seconds) of the task's last run when that run is
5992/// parked on an unresolved withheld-text question; `None` otherwise.
5993fn withheld_text_wait(task: &Task) -> Option<u64> {
5994    let id = task.execution_runs().last()?;
5995    let s = RunState::load(id).ok()?;
5996    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
5997        .then_some(s.config.graph.answer_timeout)
5998}
5999
6000/// The quota losses `after` holds that `before` did not: what one execution
6001/// suffered, as opposed to the run's history.
6002///
6003/// Compared by value rather than by length or position because
6004/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
6005/// the vector can shrink and shift under a resume. A retried seat that hits
6006/// quota again is a `push` with a new `at`, so it shows up as new here.
6007/// Crash recovery uses the recorded pass start as its boundary when available;
6008/// legacy records without passes retain their original history-based policy.
6009fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
6010    after
6011        .iter()
6012        .filter(|q| !before.contains(q))
6013        .cloned()
6014        .collect()
6015}
6016
6017/// When the loop-wide quota cooldown should end, given this attempt's losses;
6018/// `None` when there were none. Reset-hint parsing and the cap live here.
6019fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
6020    let quota: Vec<_> = quota
6021        .iter()
6022        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
6023        .collect();
6024    if quota.is_empty() {
6025        return None;
6026    }
6027    let with_hint = quota.iter().find(|q| q.reset.is_some());
6028    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
6029    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
6030    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
6031    Some(
6032        now.checked_add(jiff::SignedDuration::from_secs(secs))
6033            .unwrap_or(Timestamp::MAX),
6034    )
6035}
6036
6037/// An explicit task count must agree with a run before any resume.
6038fn implementers_match(task: &Task, state: &RunState) -> bool {
6039    task.replacement.as_ref().map_or_else(
6040        || {
6041            task.implementers()
6042                .is_none_or(|n| n == state.config.graph.implementers)
6043        },
6044        |replacement| {
6045            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
6046                && state.config.graph.implementers == 1
6047        },
6048    )
6049}
6050
6051/// Never resume or take over candidate work built for a different seat count.
6052fn starter_with_implementers(
6053    task: &Task,
6054    previous: Option<&RunState>,
6055    proposed: Starter,
6056) -> Starter {
6057    if previous.is_some_and(|s| !implementers_match(task, s)) {
6058        task.review_of
6059            .as_ref()
6060            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
6061    } else {
6062        proposed
6063    }
6064}
6065
6066/// Apply this task's explicit count to the new attempt, without changing defaults.
6067fn apply_task_implementers(config: &mut Config, task: &Task) {
6068    if let Some(n) = task.implementers() {
6069        config.graph.implementers = n;
6070    }
6071}
6072
6073/// [`prepare`] for one task: its own `--config` and command-line overrides
6074/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
6075/// over the loop's, so handing a hand-started task to a daemon changes nothing
6076/// about what it does.
6077#[cfg(test)]
6078fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
6079    let explicit = match &task.overrides {
6080        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6081        _ => opts.config.as_deref(),
6082    };
6083    let (mut config, _) = Config::discover(repo, explicit)?;
6084    apply_options(&mut config, opts, task)?;
6085    Ok(config)
6086}
6087
6088fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
6089    if task
6090        .overrides
6091        .as_ref()
6092        .is_none_or(|o| o.inherit_daemon_options)
6093        && let Some(mode) = opts.merge.as_deref()
6094    {
6095        config.merge.mode = merge_mode(mode)?;
6096    }
6097    if let Some(o) = &task.overrides {
6098        o.apply(config);
6099    }
6100    if let Some((mode, _)) = task.build_cache_override(config) {
6101        config.verify.build_cache = mode;
6102    }
6103    Ok(())
6104}
6105
6106/// Load the config for a task's repository, with the merge override applied.
6107fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
6108    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
6109    if let Some(mode) = &opts.merge {
6110        config.merge.mode = merge_mode(mode)?;
6111    }
6112    Ok(config)
6113}
6114
6115/// Prune the shared build cache at a between-runs boundary. The detached cache
6116/// service checks authoritative task jobs first; dispatch waits for that finite
6117/// service, so scheduler replacement cannot turn a compile into idle cleanup.
6118/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
6119async fn maybe_prune_cache_between_runs(
6120    repo: &Path,
6121    opts: &Opts,
6122    home: &Path,
6123    stop: &Stop,
6124    last_checked: &mut Option<Timestamp>,
6125    now: Timestamp,
6126) {
6127    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
6128        return;
6129    }
6130    *last_checked = Some(now);
6131    let cfg = match prepare(repo, opts) {
6132        Ok(cfg) => cfg,
6133        Err(e) => {
6134            tracing::warn!("cache check: no config: {e:#}");
6135            return;
6136        }
6137    };
6138    match clean::prune_cache_if_over_limit(&cfg, home) {
6139        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
6140            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
6141            pruned.files,
6142            pruned.freed
6143        ),
6144        Ok(_) => {}
6145        Err(e) => {
6146            tracing::warn!("housekeep: prune cache: {e:#}");
6147            notices::raise_in(
6148                home,
6149                Notice::warn(
6150                    "housekeep:cache",
6151                    format!(
6152                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
6153                        e.to_string()
6154                            .lines()
6155                            .next()
6156                            .unwrap_or("unknown cleanup error")
6157                    ),
6158                ),
6159            );
6160        }
6161    }
6162}
6163
6164/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
6165/// now, given when it last did (if ever). Pure, so the cadence is asserted
6166/// directly rather than by waiting out real minutes in a test.
6167fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
6168    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
6169}
6170
6171/// The disk janitor, with its housekeeping logged rather than fatal.
6172///
6173/// Called only at the loop's idle points, for the reason the caller documents:
6174/// a prune racing a live compile would delete files mid-build. The config is
6175/// re-read on every call because the repository that just ran may not be the
6176/// daemon's own default, and the cache directory is a repository fact.
6177///
6178/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
6179/// and [`crate::run::default_worktree_root`] read here, for the same reason
6180/// [`drive`] takes its queue and status file rather than resolving them: a
6181/// test driving the loop must not reach through to the operator's real home
6182/// or worktree bay just because the janitor runs on every idle tick.
6183/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
6184/// to get wrong silently - a test's `home` was already isolated, but nothing
6185/// exercised the parameter next to it, so a real worktree bay stayed wired in
6186/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
6187/// it for real, every test in this file that drives the loop at all started
6188/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
6189async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
6190    let cfg = match prepare(repo, opts) {
6191        Ok(cfg) => cfg,
6192        Err(e) => {
6193            tracing::warn!("housekeep: no config: {e:#}");
6194            return;
6195        }
6196    };
6197    // A run's own worktree lives under `config.graph.worktree_root` when the
6198    // repository sets one - the same precedence `RunState::worktree_root`
6199    // uses - and `worktrees_root` only stands in for the *default* an
6200    // unconfigured repository resolves to (see this function's own
6201    // parameter, or the test fixture wiring one to a fake path). Housekeeping
6202    // that always swept the default regardless of this override would never
6203    // see, and so never reclaim, a single worktree for a repository that
6204    // relocated them elsewhere.
6205    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
6206    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
6207    // Reported whenever there is anything to say, not only when `folded > 0`:
6208    // the incident this exists to prevent was 90 of 93 runs skipped and 0
6209    // folded, on every single pass, for months - a report gated on `folded`
6210    // would have stayed silent through every one of them.
6211    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
6212        let mut extra = Vec::new();
6213        if out.unreadable > 0 {
6214            extra.push(format!("{} unreadable", out.unreadable));
6215        }
6216        if out.orphaned_worktrees > 0 {
6217            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
6218        }
6219        let detail = if extra.is_empty() {
6220            String::new()
6221        } else {
6222            format!(" ({})", extra.join(", "))
6223        };
6224        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
6225    }
6226    if out.external_merges_recorded > 0 {
6227        tracing::info!(
6228            "housekeep: recorded {} run(s) as merged externally",
6229            out.external_merges_recorded
6230        );
6231    }
6232    if out.stale_pr_states_repaired > 0 {
6233        tracing::info!(
6234            "housekeep: rewrote {} run record(s) whose pull request had already settled",
6235            out.stale_pr_states_repaired
6236        );
6237    }
6238    if out.cache_files > 0 {
6239        tracing::info!(
6240            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6241            out.cache_files,
6242            out.cache_freed
6243        );
6244    }
6245    if out.questions_abandoned > 0 {
6246        tracing::info!(
6247            "housekeep: abandoned {} question(s) left open by a finished run",
6248            out.questions_abandoned
6249        );
6250    }
6251}
6252
6253/// Run [`triage::run_once`] and log whatever it did, the same "only when
6254/// there is something to say" rule [`janitor`] follows for its own report.
6255///
6256/// Called at the same idle points as [`janitor`] - once per full poll
6257/// interval, never mid-attempt - for the same reason: it is not liveness
6258/// critical, and a task's own `hold_reason` string is the one thing this
6259/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
6260/// tick for no benefit.
6261async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6262    let questions = Questions::at(home.join("questions"));
6263    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6264    if report.is_empty() {
6265        return;
6266    }
6267    if !report.quarantined.is_empty() {
6268        tracing::info!(
6269            "triage: held {} blocked task(s) whose blocked-on task or \
6270             question no longer exists: {}",
6271            report.quarantined.len(),
6272            report.quarantined.join(", ")
6273        );
6274    }
6275    if !report.resumed.is_empty() {
6276        tracing::info!(
6277            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6278            report.resumed.len(),
6279            report.resumed.join(", ")
6280        );
6281    }
6282    if !report.asked.is_empty() {
6283        tracing::info!(
6284            "triage: asked about {} held task(s): {}",
6285            report.asked.len(),
6286            report.asked.join(", ")
6287        );
6288    }
6289    if !report.answered.is_empty() {
6290        tracing::info!(
6291            "triage: applied {} operator answer(s): {}",
6292            report.answered.len(),
6293            report.answered.join(", ")
6294        );
6295    }
6296}
6297
6298/// The free-space gate: what stands between this task and a new run, if
6299/// anything. `Some(reason)` holds the task; `None` lets it start.
6300///
6301/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
6302/// the operator opted out. A measurement failure is a gate, not a pass: both
6303/// sides of "cannot tell" are served by not starting.
6304pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6305    disk_gate_at(repo, config, crate::run::home)
6306}
6307
6308pub(crate) fn disk_gate_at(
6309    repo: &Path,
6310    config: &Config,
6311    home: impl FnOnce() -> PathBuf,
6312) -> Option<String> {
6313    let measure = if crate::build_target::isolated(config) {
6314        crate::disk::managed_free_bytes
6315    } else {
6316        crate::disk::free_bytes
6317    };
6318    disk_gate_with(repo, config, home, measure)
6319}
6320
6321/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
6322/// test can assert the exact wiring `attempt` runs - config's threshold in,
6323/// task-holding reason out - without asking the real machine's disk anything.
6324fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6325    repo: &Path,
6326    config: &Config,
6327    home: impl FnOnce() -> PathBuf,
6328    free_bytes: F,
6329) -> Option<String> {
6330    let min = config.disk.min_free_bytes;
6331    if min == 0 {
6332        return None;
6333    }
6334    let output = match config.verify.build_cache {
6335        BuildCache::Shared => config.cache_dir(),
6336        BuildCache::Isolated => Some(home()),
6337    };
6338    let default_worktree_root;
6339    let worktree_root = match config.graph.worktree_root.as_deref() {
6340        Some(root) => root,
6341        None => {
6342            default_worktree_root = crate::run::default_worktree_root();
6343            &default_worktree_root
6344        }
6345    };
6346    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6347        .into_iter()
6348        .flatten()
6349    {
6350        let probe = if path == repo {
6351            path
6352        } else {
6353            path.ancestors().find(|p| p.exists()).unwrap_or(path)
6354        };
6355        let reason = match free_bytes(probe) {
6356            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6357            Err(e) => Some(crate::disk::unmeasured_in(
6358                probe,
6359                &e,
6360                &config.graph.language,
6361            )),
6362        };
6363        if reason.is_some() {
6364            return reason;
6365        }
6366    }
6367    None
6368}
6369
6370/// How long to wait before offering another task when a run lost a seat to a
6371/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
6372/// could read, or carried nothing at all. Long enough that a quota outage
6373/// cannot burn through a whole backlog in the few seconds each doomed attempt
6374/// takes to fail; short enough that a quota which clears early is not left
6375/// idle for the fallback's sake.
6376const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6377
6378/// Longest a parsed reset hint may push the wait out to. The hint comes from
6379/// the CLI's own words, not a contract, so a parsing slip that lands a day
6380/// away must not leave the loop asleep for a day.
6381const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6382
6383/// How long [`poll`] should wait before offering the next task, after a run
6384/// lost at least one seat to a rate limit.
6385///
6386/// Pure and separate from the loop so the policy can be exercised without a
6387/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
6388/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
6389/// nothing to parse, or the parsed time has already passed; `cap` bounds how
6390/// far a parsed hint is trusted to push the wait out.
6391fn quota_wait(
6392    reset_at: Option<Timestamp>,
6393    now: Timestamp,
6394    fallback: Duration,
6395    cap: Duration,
6396) -> Duration {
6397    match reset_at {
6398        Some(at) if at > now => {
6399            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6400            Duration::from_secs(secs).min(cap)
6401        }
6402        _ => fallback,
6403    }
6404}
6405
6406/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6407///
6408/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6409/// explains why parsing it exactly "would be a bug factory" — so this only
6410/// recognises the shapes actually observed in the wild, and returns `None`
6411/// for anything else rather than guess at a format nobody has seen.
6412///
6413/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6414/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6415/// said it, not from whenever this loop happens to read it: anchoring on `now`
6416/// would push the reset later on every read and would read an already-elapsed
6417/// reset as still in the future. (A long hint is still clamped by
6418/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6419fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6420    parse_reset_hint_zoned(text, now)
6421        .or_else(|| parse_reset_hint_dated(text))
6422        .or_else(|| parse_reset_hint_relative(text, recorded))
6423}
6424
6425/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6426/// optional but at least one required, in that order. A bare number or any
6427/// unknown unit is refused.
6428fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6429    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6430    let mut rest = rest.trim();
6431    if rest.is_empty() {
6432        return None;
6433    }
6434    let mut total: i64 = 0;
6435    let mut matched = false;
6436    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6437        if let Some((digits, tail)) = rest.split_once(unit)
6438            && !digits.is_empty()
6439            && digits.bytes().all(|b| b.is_ascii_digit())
6440        {
6441            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6442            rest = tail;
6443            matched = true;
6444        }
6445    }
6446    if !rest.is_empty() || !matched {
6447        return None;
6448    }
6449    recorded
6450        .checked_add(jiff::SignedDuration::from_secs(total))
6451        .ok()
6452}
6453
6454/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6455/// case-insensitive) into a 24-hour hour and minute. Shared by every
6456/// reset-hint shape below.
6457fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6458    let clock = clock.trim().to_lowercase();
6459    let (digits, pm) = clock
6460        .strip_suffix("am")
6461        .map(|d| (d, false))
6462        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6463    let (h, m) = digits.trim().split_once(':')?;
6464    let mut hour: i8 = h.trim().parse().ok()?;
6465    let minute: i8 = m.trim().parse().ok()?;
6466    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6467        return None;
6468    }
6469    if pm && hour != 12 {
6470        hour += 12;
6471    } else if !pm && hour == 12 {
6472        hour = 0;
6473    }
6474    Some((hour, minute))
6475}
6476
6477/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6478/// and a zone, never a date. A clock reading already past today is read as
6479/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6480/// the window rolled over while nothing was watching.
6481fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6482    let open = text.find('(')?;
6483    let close = text.rfind(')')?;
6484    if close <= open {
6485        return None;
6486    }
6487    let zone = text[open + 1..close].trim();
6488    let (hour, minute) = parse_12h_clock(&text[..open])?;
6489    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6490    let candidate = now
6491        .to_zoned(tz)
6492        .with()
6493        .hour(hour)
6494        .minute(minute)
6495        .second(0)
6496        .millisecond(0)
6497        .microsecond(0)
6498        .nanosecond(0)
6499        .build()
6500        .ok()?;
6501    let mut at = candidate.timestamp();
6502    if at <= now {
6503        at += jiff::SignedDuration::from_hours(24);
6504    }
6505    Some(at)
6506}
6507
6508/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6509/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6510/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6511/// "already past today" correction to make: the year already disambiguates
6512/// it. Scanned as a five-word window so it can be pulled out of the middle
6513/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6514/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6515/// any other timestamp with no zone attached.
6516fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6517    let words: Vec<&str> = text.split_whitespace().collect();
6518    if words.len() < 5 {
6519        return None;
6520    }
6521    (0..=words.len() - 5)
6522        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6523}
6524
6525/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6526/// parenthesis right after the window is refused rather than ignored — it
6527/// reads as an explicit zone annotation on a shape that otherwise carries
6528/// none, and guessing UTC anyway would be exactly the silent misread this
6529/// module's parsing otherwise avoids.
6530fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6531    if trailing.is_some_and(|next| next.starts_with('(')) {
6532        return None;
6533    }
6534    let month = month_number(window[0])?;
6535    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6536    let day_digits = ["st", "nd", "rd", "th"]
6537        .iter()
6538        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6539    let day: i8 = day_digits.parse().ok()?;
6540    let year_token = window[2];
6541    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6542        return None;
6543    }
6544    let year: i16 = year_token.parse().ok()?;
6545    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6546    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6547    // reusing the same 12-hour clock reader the bracketed shape uses.
6548    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6549    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6550    let date = jiff::civil::Date::new(year, month, day).ok()?;
6551    let candidate = date
6552        .at(hour, minute, 0, 0)
6553        .to_zoned(jiff::tz::TimeZone::UTC)
6554        .ok()?;
6555    Some(candidate.timestamp())
6556}
6557
6558/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6559/// case-insensitively, into a 1-based month number.
6560fn month_number(name: &str) -> Option<i8> {
6561    const NAMES: [&str; 12] = [
6562        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6563    ];
6564    let lower = name.to_lowercase();
6565    NAMES
6566        .iter()
6567        .position(|n| *n == lower.as_str())
6568        .map(|i| i as i8 + 1)
6569}
6570
6571/// Test probe for the shared resume policy's review-budget exclusion.
6572#[cfg(test)]
6573fn exhausted_review_budget(state: &RunState) -> bool {
6574    // A run whose task-head publication failed has nothing left to review:
6575    // resuming it only retries the publication, so it is never "exhausted".
6576    !crate::handover::can_resume(state)
6577        && state.status == RunStatus::Blocked
6578        && !state.released()
6579        && state.retired_to.is_none()
6580}
6581
6582/// This task's *most recent* run, if resuming it would actually make
6583/// progress. `short` is only for the warning's own message.
6584///
6585/// Only ever `runs.last()` — never a search back through older history.
6586/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6587/// mint, oldest first, and every entry before the last one was already
6588/// superseded at the moment it was minted: the daemon only ever starts a new
6589/// run when the previous one was not worth resuming (unresumable, exhausted,
6590/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6591/// opens a fresh review-only run alongside an older, already-failed
6592/// competition. Searching further back would let an old run that merely
6593/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6594/// behind, say — get resumed instead of the fresh competition
6595/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6596/// nothing asked to revisit.
6597///
6598/// Two runs paid for the "prefer resuming over restarting" half of this
6599/// lesson, which is why this still checks `runs.last()` rather than always
6600/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6601/// task a moment later, duplicating two and a half hours of agent work. Then
6602/// b25f stalled on a judge that timed out and one that answered with no JSON
6603/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6604/// **one second** later, buying three fresh implementations to reach the
6605/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6606/// the second case: a stall is terminal, and its cheap recovery re-asks only
6607/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6608/// that is technically `resumable()` but provably cannot progress must not
6609/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6610/// no-op instead of the fresh competition it promises.
6611///
6612/// A load failure is warned about rather than silently read as "not
6613/// resumable": the alternative is exactly what let a schema mismatch on run
6614/// `eba2` fall through to a full re-competition with nobody told why.
6615/// `crate::conduct` is what actually offers a better answer than
6616/// `Runner::start` here (see `Recovery::Review`), once this task's next
6617/// failure shows it up as `held`/`failed` with the run state unreadable.
6618fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6619    unfinished_run_with(runs, short, RunState::load)
6620}
6621
6622/// [`unfinished_run`] with an injected state reader. Tests provide their
6623/// fixtures directly rather than touching the process-global run home.
6624pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6625where
6626    F: FnMut(&str) -> Result<RunState>,
6627{
6628    let mut id = runs.last()?.clone();
6629    let mut visited = std::collections::BTreeSet::new();
6630    let mut repo = None;
6631    loop {
6632        if !runs.contains(&id) || !visited.insert(id.clone()) {
6633            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6634            return None;
6635        }
6636        let state = match load(&id) {
6637            Ok(state) if state.id == id => state,
6638            Ok(_) => return None,
6639            Err(e) => {
6640                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6641                return None;
6642            }
6643        };
6644        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6645            return None;
6646        }
6647        repo = Some(state.repo.clone());
6648        if let Some(authority) = state.retired_to {
6649            id = authority;
6650            continue;
6651        }
6652        return (crate::handover::can_resume(&state)
6653            && state.liveness(false) != crate::run::Liveness::Live)
6654            .then_some(id);
6655    }
6656}
6657
6658/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6659/// that [`attempt`] will resume it on its own?
6660///
6661/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6662/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6663/// injected reader like its sibling. An unreadable run is not awaiting
6664/// anything: it keeps going to the conductor as before.
6665fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6666where
6667    F: FnOnce(&str) -> Result<RunState>,
6668{
6669    // `Failed` stays: a record an older build wrote for a parked run.
6670    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6671        || task.fresh_start
6672        || task.review_branch.is_some()
6673    {
6674        return false;
6675    }
6676    let Some(id) = task.execution_runs().last() else {
6677        return false;
6678    };
6679    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6680}
6681
6682/// Which of the three ways [`attempt`] can mint or continue a run this task
6683/// should use.
6684#[derive(Debug, Clone, PartialEq, Eq)]
6685enum Starter {
6686    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6687    /// and that still exists.
6688    Review(String),
6689    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6690    Resume(String),
6691    /// `crate::graph::Runner::start`: a fresh competition.
6692    Start,
6693}
6694
6695/// A second bound independent of inputs and the resettable failure counter.
6696/// Count execution and failed-startup recovery records once per run. Startup
6697/// failures can retain unrecorded preparation assets without an execution pass.
6698/// Unknown history is not evidence that a new set of worktrees is affordable.
6699fn retained_attempt_hold(
6700    task: &Task,
6701    starter: &Starter,
6702    limit: usize,
6703    mut load: impl FnMut(&str) -> Result<RunState>,
6704) -> Option<String> {
6705    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6706        return None;
6707    }
6708    let mut retained = 0;
6709    for id in task
6710        .runs
6711        .iter()
6712        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6713        .collect::<std::collections::BTreeSet<_>>()
6714    {
6715        let state = match load(id) {
6716            Ok(state) if state.id == *id => state,
6717            _ => {
6718                return Some(format!(
6719                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6720                ));
6721            }
6722        };
6723        if state.retired_to.is_some() || state.released() {
6724            continue;
6725        }
6726        // Neither a completed status nor an empty candidate array proves that
6727        // all recovery sources (including unrecorded preparation) were retired.
6728        retained += 1;
6729    }
6730    (retained >= limit).then(|| format!(
6731        "[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."
6732    ))
6733}
6734
6735/// A selected public implementation overrides every historical candidate and pin.
6736fn selected_starter(
6737    selected: &crate::pr_recovery::Selection,
6738    previous: Option<&RunState>,
6739    unfinished: Option<&str>,
6740) -> Starter {
6741    if let Some(id) = unfinished
6742        && previous.is_some_and(|r| {
6743            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6744        })
6745    {
6746        Starter::Resume(id.to_owned())
6747    } else {
6748        Starter::Review(selected.branch.clone())
6749    }
6750}
6751
6752/// The owner's answer to this branch's divergence question, consumed from the
6753/// task so a later, different divergence asks again. The runner applies it
6754/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6755fn take_divergence_answer(
6756    branch: &str,
6757    remote: &str,
6758    task: &mut Task,
6759) -> Option<crate::reconcile::Choice> {
6760    let summary = crate::reconcile::summary_for(branch, remote);
6761    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6762        (a.question == summary)
6763            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6764            .flatten()
6765            .map(|c| (i, c))
6766    })?;
6767    task.answers.remove(idx);
6768    Some(choice)
6769}
6770
6771/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6772/// this attempt should use. Pure, and separate from [`attempt`], so the
6773/// routing itself is assertable without spawning a real graph or a git
6774/// process: `attempt`'s own `crate::git::branch_exists` call has already
6775/// happened by the time this is called.
6776///
6777/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6778/// whose branch is gone falls all the way through to [`Starter::Start`], not
6779/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6780/// old (likely `Blocked`) run in the first place, and a branch that vanished
6781/// out from under that choice is not evidence resuming it would fare better.
6782fn choose_starter(
6783    review_branch: Option<&str>,
6784    branch_exists: bool,
6785    unfinished: Option<&str>,
6786) -> Starter {
6787    match review_branch {
6788        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6789        Some(_) => Starter::Start,
6790        None => match unfinished {
6791            Some(id) => Starter::Resume(id.to_owned()),
6792            None => Starter::Start,
6793        },
6794    }
6795}
6796
6797/// Reuse a compatible latest review owner instead of taking its checked-out
6798/// branch into a new run. Different branches and changed criteria still use
6799/// the ordinary review/takeover policy.
6800fn review_retry_starter(
6801    task: &Task,
6802    previous: Option<&RunState>,
6803    branch: Option<&str>,
6804    exists: bool,
6805    unfinished: Option<&str>,
6806) -> Starter {
6807    if let Some(run) = previous
6808        && unfinished == Some(run.id.as_str())
6809        && run.reviewed_commits.is_some()
6810        && branch.is_some_and(|branch| {
6811            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6812        })
6813        && may_resume_run(run, task)
6814    {
6815        return Starter::Resume(run.id.clone());
6816    }
6817    match (branch, unfinished, &task.review_of) {
6818        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6819        _ => choose_starter(branch, exists, unfinished),
6820    }
6821}
6822
6823/// A retained review is valid only while its authored criteria still match.
6824fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6825    task.review_branch
6826        .as_deref()
6827        .filter(|&branch| match &task.review_instruction {
6828            Some(authored) => *authored == task.instruction,
6829            // Legacy retained branches must agree with their prior run; only an
6830            // explicitly pinned review can proceed without recoverable provenance.
6831            None => previous.map_or_else(
6832                || task.review_of.as_deref() == Some(branch),
6833                |run| compatible_run_instruction(run, task),
6834            ),
6835        })
6836}
6837
6838/// A current explicit pin can select an otherwise incompatible run. Edits
6839/// and subsequent approvals invalidate pins selected for earlier criteria.
6840fn may_resume_run(run: &RunState, task: &Task) -> bool {
6841    if !task.assignment_accepts(run) {
6842        return false;
6843    }
6844    task.resume_override
6845        .as_ref()
6846        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6847        || compatible_run_instruction(run, task)
6848}
6849
6850/// Review scaffolding is execution context, not evidence of an operator edit.
6851pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6852    if let Some(authored) = &run.task_instruction {
6853        return compatible_instruction(authored, task);
6854    }
6855    if compatible_instruction(&run.instruction, task) {
6856        return true;
6857    }
6858    // Recognize only the existing generated review shapes on legacy runs.
6859    // Ordinary authored text with a similar heading is left intact.
6860    if run.reviewed_commits.is_some() {
6861        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6862            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6863        }
6864        if let Some(branch) = &task.review_of {
6865            let canonical = format!(
6866                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6867            );
6868            let generated = format!(
6869                "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"
6870            );
6871            return task.instruction == canonical && run.instruction.starts_with(&generated);
6872        }
6873    }
6874    false
6875}
6876
6877/// Compare authored instructions, excluding answer blocks appended by the daemon.
6878pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6879    strip_answers_block(old, task) == task.instruction
6880}
6881
6882/// Which repository a task runs in. A task that names none — the normal case
6883/// for one filed from a phone — runs in the daemon's own default.
6884fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6885    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6886        return fallback.to_path_buf();
6887    }
6888    task.repo.clone()
6889}
6890
6891/// The header [`append_answers`] appends operator answers under. Shared with
6892/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6893/// rather than grown a new block on every resume.
6894const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6895
6896/// Render the first `count` answers in the block appended to an instruction.
6897fn answers_block(task: &Task, count: usize) -> String {
6898    let mut s = ANSWERS_HEADER.to_owned();
6899    for a in &task.answers[..count] {
6900        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6901    }
6902    s
6903}
6904
6905/// Render the approval independently of transient task state, so historical
6906/// suffixes remain recognizable after another explicit release.
6907fn resumption_block(r: &crate::queue::Resumption) -> String {
6908    format!(
6909        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6910         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6911        r.generation, r.at, r.instruction, r.answers_through,
6912    )
6913}
6914
6915/// Append audit answers and the latest explicit approval to the instruction.
6916fn append_answers(base: &str, task: &Task) -> String {
6917    let mut s = base.to_owned();
6918    if !task.answers.is_empty() {
6919        s.push_str(&answers_block(task, task.answers.len()));
6920    }
6921    if let Some(r) = &task.resumption {
6922        s.push_str(&resumption_block(r));
6923    }
6924    s
6925}
6926
6927/// Drop the prior answer block only when it is exactly the suffix this task
6928/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6929/// the task author is ordinary instruction text, not a block to remove.
6930fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6931    let mut instruction = instruction;
6932    for approval in task
6933        .resumption
6934        .iter()
6935        .chain(task.resumption_history.iter().rev())
6936    {
6937        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6938            instruction = base;
6939            break;
6940        }
6941    }
6942    for count in (1..=task.answers.len()).rev() {
6943        let block = answers_block(task, count);
6944        if let Some(base) = instruction.strip_suffix(&block) {
6945            return base;
6946        }
6947    }
6948    instruction
6949}
6950
6951/// The instruction handed to `Runner::start`: the task's own text, plus any
6952/// operator answers `crate::conduct` collected for it (see
6953/// [`Task::answers`]), so a decision the operator actually made reaches the
6954/// implementers rather than only clearing the block that was waiting on it.
6955///
6956/// Appended rather than merged into [`Task::instruction`] itself, so the
6957/// task's own record stays exactly what its author wrote.
6958fn instruction_for(task: &Task) -> String {
6959    append_answers(&task.instruction, task)
6960}
6961
6962/// The instruction a resumed run should carry on with: whatever it already
6963/// had, refreshed with the task's *current* operator answers.
6964///
6965/// A resumable run's own `RunState::instruction` predates any answer
6966/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6967/// the behaviour before this function existed — silently drops the very
6968/// decision the operator made to unblock it. Re-stripping any block this
6969/// function appended on an earlier resume before re-appending the current
6970/// list (rather than blindly appending again) is what keeps a task resumed
6971/// three times over three answered questions from carrying the same answer
6972/// three times.
6973fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6974    append_answers(strip_answers_block(old_instruction, task), task)
6975}
6976
6977/// Preserve the producer's verified boundary and target, independent of prose.
6978fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6979    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6980    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6981    if let Some(cause) = task.hold_notice_cause.as_mut() {
6982        cause.target = failure.map(|f| f.target.clone());
6983    }
6984}
6985
6986#[derive(Debug, thiserror::Error)]
6987#[error("attachment `{name}` is recorded on the task but {path} is missing")]
6988struct MissingAttachment {
6989    name: String,
6990    path: PathBuf,
6991}
6992
6993/// The task's attachments as absolute paths, each checked to still exist.
6994fn task_attachments(
6995    queue: &Queue,
6996    task: &Task,
6997) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
6998    let paths = queue.attachment_paths(task);
6999    for (name, path) in task.attachments.iter().zip(&paths) {
7000        if !path.is_file() {
7001            return Err(MissingAttachment {
7002                name: name.clone(),
7003                path: path.clone(),
7004            });
7005        }
7006    }
7007    Ok(paths)
7008}
7009
7010/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
7011/// answers before handing it to `Runner` — the actual boundary between
7012/// [`choose_starter`]'s routing and the graph, factored out so it is
7013/// assertable without a real repository, git branch, or agent CLI.
7014///
7015/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
7016/// instruction from the reviewed branch's own commit log because there is no
7017/// task statement to speak of for hand-written work, and splicing operator
7018/// answers into that text would contradict the very message it sends
7019/// reviewers ("there is no task statement").
7020fn prepare_instruction(
7021    starter: &Starter,
7022    old_instruction: Option<&str>,
7023    task: &Task,
7024) -> Option<String> {
7025    match starter {
7026        Starter::Start => Some(instruction_for(task)),
7027        Starter::Resume(_) => Some(resumed_instruction(
7028            old_instruction.expect("a resumed run always has a prior instruction"),
7029            task,
7030        )),
7031        Starter::Review(_) => None,
7032    }
7033}
7034
7035/// Persist a transition. A queue write failure is logged rather than fatal: the
7036/// run already happened, and taking the daemon down would only add a lost
7037/// backlog to a full disk.
7038fn record(queue: &Queue, task: &mut Task) {
7039    if let Err(e) = queue.put(task) {
7040        tracing::error!("could not record task {}: {e:#}", task.short());
7041        let notice = Notice::error(
7042            "loop:record",
7043            format!(
7044                "Task {} state could not be saved: {}. Check the disk.",
7045                task.id,
7046                e.to_string().lines().next().unwrap_or("unknown save error")
7047            ),
7048        )
7049        .link(Link::Task {
7050            id: task.id.clone(),
7051        });
7052        // The queue lives at `<home>/queue`, so its parent is the home.
7053        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
7054            Some(home) => notices::raise_in(home, notice),
7055            None => notices::raise(notice),
7056        }
7057    }
7058}
7059
7060/// Every runnable task, in the order the loop should try them.
7061///
7062/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
7063/// tail exists so that a claim somebody else holds costs the loop the next
7064/// candidate rather than a whole poll interval of idleness.
7065fn runnable(queue: &Queue) -> Vec<Task> {
7066    let mut tasks: Vec<Task> = queue
7067        .list()
7068        .into_iter()
7069        .filter(|t| t.status.runnable())
7070        .collect();
7071    tasks.sort_unstable_by(crate::queue::dispatch_order);
7072    tasks
7073}
7074
7075/// Why a run ended where it did, in one line, for [`Task::last_error`].
7076///
7077/// A stalled run names the seats the quota took out: "out of quota" is not
7078/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
7079/// agent to replace or which plan to top up.
7080///
7081/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
7082/// purpose: unlike `label`'s other callers (an internal log line, an
7083/// already-a-bug fallback message), this string becomes `Task::last_error`
7084/// verbatim, which the phone renders in the same alarm-styled box an
7085/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
7086/// `.err` styling. A bare `verified_noop` there would read exactly like the
7087/// failure this whole feature exists to tell apart from one.
7088fn describe(state: &RunState) -> String {
7089    let p = phrases(&state.config.graph.language);
7090    let mut detail = if state.status == RunStatus::Stalled {
7091        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
7092        seats.sort_unstable();
7093        seats.dedup();
7094        if seats.is_empty() {
7095            p.quorum_lost.to_owned()
7096        } else {
7097            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
7098        }
7099    } else {
7100        format!("{}{}", p.run_ended, state.status.display_label())
7101    };
7102    if let Some(cause) = state.verification_blocking_cause() {
7103        detail.push_str(&format!(" ({cause})"));
7104    } else if let Some(last) = state.events.last() {
7105        // The review loop's "never answered" stop is the one event worth
7106        // translating; it is recognised from structured state, not by
7107        // matching the English event text (which stays as recorded).
7108        let unanswered = state
7109            .reviews
7110            .last()
7111            .filter(|r| {
7112                state.status == RunStatus::Blocked
7113                    && last.node == "review"
7114                    && r.incomplete()
7115                    && r.blocking == 0
7116                    && r.round == state.config.graph.review_rounds
7117                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
7118            })
7119            .map(|r| (r.expected - r.answered, r.round));
7120        match unanswered {
7121            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
7122                detail.push_str(&format!(
7123                    " ({}: {})",
7124                    last.node,
7125                    (p.reviewers_never_answered)(missing, rounds)
7126                ));
7127            }
7128            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
7129        }
7130    }
7131    detail.push_str(&format!(" [run {}]", state.id));
7132    detail
7133}
7134
7135/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
7136///
7137/// The task file lives in the backlog indefinitely; a diagnostic is an
7138/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
7139/// stay small regardless of how much a gate command or a candidate printed.
7140const DIAGNOSTIC_MAX: usize = 4_000;
7141
7142/// Tail kept from a single failing command's output inside a diagnostic.
7143/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
7144/// pointer for a human deciding whether to go read the full artifact by hand,
7145/// not a replacement for reading it.
7146const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
7147
7148/// Assemble a bounded diagnostic excerpt from a held task's own run, so
7149/// `magi task show` says more than the one-line reason in [`describe`].
7150///
7151/// The one-liner answers "where did the run stop"; this answers "what would a
7152/// human have found opening `artifacts/` by hand" — the point of the whole
7153/// feature is the case that one-liner actively misleads on: a run held as "no
7154/// candidate produced a change" can mean the implementer actually finished
7155/// the task (opened a PR, merged it, tagged a release) and only left a clean
7156/// local worktree behind, which reads as "nothing happened" unless someone
7157/// goes and reads what the agent actually said. `None` when the run carries
7158/// none of the three shapes this recognises — an ordinary run held for
7159/// something not diagnosable from `RunState` alone still explains itself
7160/// through `Task::last_error`.
7161pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
7162    diagnostic(state)
7163}
7164
7165fn diagnostic(state: &RunState) -> Option<String> {
7166    let mut parts: Vec<String> = Vec::new();
7167
7168    if let Some(e2e) = &state.head_e2e
7169        && !e2e.passed
7170    {
7171        for o in e2e
7172            .outcomes
7173            .iter()
7174            .filter(|o| !o.ok() && !o.resource_blocked)
7175        {
7176            parts.push(format!(
7177                "head_e2e `{}` failed on {} ({}):\n{}",
7178                o.command,
7179                e2e.head.chars().take(7).collect::<String>(),
7180                notices::exit_status(o.code),
7181                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7182            ));
7183        }
7184    }
7185
7186    // Gate failure: which check(s), and the tail of what each printed.
7187    for o in state.gate.iter().filter(|o| !o.ok()) {
7188        parts.push(format!(
7189            "gate `{}` failed ({}):\n{}",
7190            o.command,
7191            notices::exit_status(o.code),
7192            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7193        ));
7194    }
7195
7196    // The land loop gave up because the fixer declined while checks were
7197    // still red: the message already names them (see `land::run`).
7198    if let Some(last) = state
7199        .events
7200        .iter()
7201        .rev()
7202        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
7203    {
7204        parts.push(last.message.clone());
7205    }
7206
7207    // No viable candidate: every implementer's own final word, sanitized the
7208    // same way a judge would have read it, so a run that actually finished
7209    // the job does not read as an unexplained failure. A verified no-op is
7210    // called out ahead of its own summary and apart from an ordinary
7211    // failure's `why` — this is the one candidate shape whose diagnostic a
7212    // human is expected to actually judge, not just skim.
7213    if state.viable().is_empty() {
7214        for c in &state.candidates {
7215            if c.has_valid_verified_noop()
7216                && let Some(evidence) = c.verified_noop_display()
7217            {
7218                parts.push(format!(
7219                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
7220                    c.label
7221                ));
7222            } else if !c.summary.trim().is_empty() {
7223                if let Some(why) = &c.failed {
7224                    parts.push(format!(
7225                        "candidate {} ({why}): {}",
7226                        c.label,
7227                        c.summary.trim()
7228                    ));
7229                } else {
7230                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
7231                }
7232            } else if let Some(why) = &c.failed {
7233                parts.push(format!("candidate {}: {why}", c.label));
7234            }
7235        }
7236    }
7237
7238    if parts.is_empty() {
7239        return None;
7240    }
7241    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
7242    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
7243    // back slightly over. Leave it enough room to always land under the
7244    // limit.
7245    Some(crate::run::tail(
7246        &parts.join("\n\n"),
7247        DIAGNOSTIC_MAX.saturating_sub(100),
7248    ))
7249}
7250
7251/// Stable lower-case name for a run status, for an internal log line and the
7252/// "graph stopped without reaching a terminal status" bug message in
7253/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
7254/// doc for why that one reads [`RunStatus::display_label`] instead. One
7255/// definition of a status's name, on the type that owns it: this table used
7256/// to live here as a second copy, and a status renamed in one place would
7257/// have gone on reading correctly in the other.
7258fn label(status: RunStatus) -> &'static str {
7259    status.as_str()
7260}
7261
7262/// Parse a merge mode override.
7263pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
7264    match mode {
7265        "none" => Ok(MergeMode::None),
7266        "local" => Ok(MergeMode::Local),
7267        "pr" => Ok(MergeMode::Pr),
7268        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
7269    }
7270}
7271
7272/// Take the status lock, recovering from a poisoned one.
7273///
7274/// A panic elsewhere must not silently stop the heartbeat: the status is plain
7275/// data, and the worst a poisoned lock can hold is a stale timestamp.
7276fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7277    mutex
7278        .lock()
7279        .unwrap_or_else(std::sync::PoisonError::into_inner)
7280}
7281
7282#[cfg(test)]
7283mod tests {
7284    use super::*;
7285    use crate::queue::{Source, TaskStatus};
7286    use crate::run::{Candidate, CommandOutcome};
7287    use pretty_assertions::assert_eq;
7288
7289    fn task() -> Task {
7290        Task::new(
7291            "add retries".to_owned(),
7292            "add retries".to_owned(),
7293            PathBuf::from("/repo"),
7294            Source::Human,
7295        )
7296    }
7297
7298    #[test]
7299    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7300        let skips = DispatchSkips::from([
7301            ("a".into(), SkipReason::CoolingDown),
7302            ("b".into(), SkipReason::WaitingOnLanding),
7303            ("c".into(), SkipReason::WaitingOnLanding),
7304            ("d".into(), SkipReason::OrdinaryCapacity),
7305        ]);
7306        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7307        assert_eq!(wait.runnable, 4);
7308        assert_eq!(
7309            wait.reasons
7310                .iter()
7311                .map(|r| (r.reason.as_str(), r.count))
7312                .collect::<Vec<_>>(),
7313            [
7314                ("waiting_on_landing", 2),
7315                ("cooling_down", 1),
7316                ("ordinary_capacity", 1)
7317            ]
7318        );
7319        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7320        assert!(
7321            aggregate_dispatch_wait(2, &DispatchSkips::new())
7322                .unwrap()
7323                .reasons
7324                .is_empty()
7325        );
7326    }
7327
7328    #[test]
7329    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7330        let before = vec!["a".into(), "b".into(), "c".into()];
7331        let allowed = vec![task_with_id("b")];
7332        let skips = interrupt_skips(&before, &allowed);
7333        assert_eq!(
7334            skips,
7335            DispatchSkips::from([
7336                ("a".into(), SkipReason::InterruptGate),
7337                ("c".into(), SkipReason::InterruptGate),
7338            ])
7339        );
7340        let mut previous = DispatchSkips::new();
7341        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7342        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7343        assert!(!changed_dispatch_skips(&mut previous, skips));
7344        assert!(changed_dispatch_skips(
7345            &mut previous,
7346            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7347        ));
7348        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7349    }
7350
7351    #[test]
7352    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7353        let mut value = serde_json::to_value(Status::new()).unwrap();
7354        value.as_object_mut().unwrap().remove("dispatch_wait");
7355        assert!(
7356            serde_json::from_value::<Status>(value.clone())
7357                .unwrap()
7358                .dispatch_wait
7359                .is_none()
7360        );
7361        assert!(
7362            serde_json::from_value::<Reading>(value.clone())
7363                .unwrap()
7364                .dispatch_wait
7365                .is_none()
7366        );
7367        value["dispatch_wait"] = serde_json::json!({
7368            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7369        });
7370        let reading = serde_json::from_value::<Reading>(value).unwrap();
7371        assert_eq!(
7372            reading.dispatch_wait.unwrap().reasons[0].reason,
7373            "future_reason"
7374        );
7375    }
7376
7377    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7378        let job = crate::worker::Job {
7379            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7380            sequence: 1,
7381            kind: "task".into(),
7382            key: format!("task:{}", request.task),
7383            payload: serde_json::to_value(request).unwrap(),
7384            generation: "a".repeat(64),
7385            version: None,
7386            status: crate::worker::Status::Starting,
7387            result: None,
7388            pid: None,
7389            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7390            finished_at: None,
7391        };
7392        let dir = home.join("workers/jobs").join(&job.id);
7393        std::fs::create_dir_all(&dir).unwrap();
7394        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7395        job
7396    }
7397
7398    #[test]
7399    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7400        let home = tempfile::tempdir().unwrap();
7401        let request = TaskWorker {
7402            opts: Opts::default(),
7403            queue: home.path().join("queue"),
7404            task: "startup".into(),
7405            lane: PermitKind::Ordinary,
7406            standalone: false,
7407        };
7408        let job = starting_task_reservation(home.path(), &request);
7409        let error = task_worker_spawn_error(
7410            home.path(),
7411            &request,
7412            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7413        )
7414        .expect_err("our own reservation must not turn a failed spawn into a resync");
7415        let active = crate::worker::active(home.path()).unwrap();
7416        assert_eq!(active.len(), 1);
7417        assert_eq!(active[0].id, job.id);
7418        assert_eq!(active[0].status, crate::worker::Status::Starting);
7419        assert!(
7420            crate::worker::control(home.path(), &job.key)
7421                .unwrap()
7422                .is_none()
7423        );
7424        let notices = notices::Notices::at(home.path().join("notifications")).list();
7425        assert_eq!(notices.len(), 1);
7426        assert_eq!(notices[0].key, "loop:worker-startup");
7427        assert!(!notices[0].message.contains("private-error-detail"));
7428        assert!(notices[0].message.contains(&request.task));
7429        assert!(
7430            notices[0]
7431                .message
7432                .contains("could not be started or acknowledged")
7433        );
7434        assert!(notices[0].message.contains("worker.log"));
7435        assert_eq!(
7436            notices[0].link,
7437            Some(Link::Task {
7438                id: request.task.clone()
7439            })
7440        );
7441        assert!(format!("{error:#}").contains("private-error-detail"));
7442    }
7443
7444    #[test]
7445    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7446        let home = tempfile::tempdir().unwrap();
7447        let mut request = TaskWorker {
7448            opts: Opts::default(),
7449            queue: home.path().join("queue"),
7450            task: "handoff".into(),
7451            lane: PermitKind::Ordinary,
7452            standalone: true,
7453        };
7454        let job = starting_task_reservation(home.path(), &request);
7455        request.standalone = false;
7456        task_worker_spawn_error(
7457            home.path(),
7458            &request,
7459            anyhow::anyhow!("operation key is already reserved for a different request"),
7460        )
7461        .expect("a different standalone request is the handoff race, not our startup failure");
7462        let active = crate::worker::active(home.path()).unwrap();
7463        assert_eq!(active.len(), 1);
7464        assert_eq!(active[0].id, job.id);
7465        assert_eq!(active[0].payload, job.payload);
7466        assert!(
7467            notices::Notices::at(home.path().join("notifications"))
7468                .list()
7469                .is_empty()
7470        );
7471    }
7472
7473    #[test]
7474    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7475        let home = tempfile::tempdir().unwrap();
7476        let queue = Queue::at(home.path().join("queue"));
7477        let mut task = task();
7478        task.runs = vec!["previous".into()];
7479        queue.put(&mut task).unwrap();
7480        let request = TaskWorker {
7481            opts: Opts::default(),
7482            queue: home.path().join("queue"),
7483            task: task.id.clone(),
7484            lane: PermitKind::Ordinary,
7485            standalone: false,
7486        };
7487        let job = starting_task_reservation(home.path(), &request);
7488        let claims = current_work(home.path(), Timestamp::now());
7489        assert_eq!(claims.len(), 1);
7490        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7491        assert_eq!(claims[0].run, "previous");
7492        assert!(other_claims_run(&claims, "previous", None));
7493        // Only after confirming the executing caller may admission ignore
7494        // this exact projection. Cleanup continues to observe it as live.
7495        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7496        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7497    }
7498
7499    #[test]
7500    fn admission_excludes_only_the_callers_exact_reservation() {
7501        let own = Current {
7502            worker: Some("own".into()),
7503            task: "same-task".into(),
7504            run: "previous".into(),
7505        };
7506        assert!(!other_claims_run(
7507            std::slice::from_ref(&own),
7508            "previous",
7509            Some("own")
7510        ));
7511        assert!(other_claims_run(
7512            std::slice::from_ref(&own),
7513            "previous",
7514            None
7515        ));
7516        for worker in [None, Some("other".into())] {
7517            let other = Current {
7518                worker,
7519                ..own.clone()
7520            };
7521            assert!(other_claims_run(
7522                &[own.clone(), other],
7523                "previous",
7524                Some("own")
7525            ));
7526        }
7527        let legacy: Current =
7528            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7529        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7530    }
7531
7532    #[test]
7533    fn os_leased_task_worker_survives_wall_clock_advance() {
7534        let home = tempfile::tempdir().unwrap();
7535        let queue = Queue::at(home.path().join("queue"));
7536        let mut task = task();
7537        let run = "20260903-100000-abcd";
7538        task.start(run.into());
7539        queue.put(&mut task).unwrap();
7540        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
7541        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
7542        assert!(
7543            current_work(home.path(), future)
7544                .iter()
7545                .any(
7546                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
7547                        && claim.run == run
7548                )
7549        );
7550        worker.release_lease();
7551        assert!(worker.dir.join("job.json").is_file());
7552        assert!(!is_working_on(home.path(), run, future));
7553        let dir = worker.dir.clone();
7554        drop(worker);
7555        assert!(!dir.exists());
7556    }
7557
7558    #[test]
7559    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7560        let mut task = task();
7561        let mut run = run_state(RunStatus::Reviewing);
7562        run.task_instruction = Some(task.instruction.clone());
7563        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7564        let branch = "magi/test/B";
7565        run.candidates.push(crate::run::Candidate {
7566            branch: branch.into(),
7567            ..candidate('B', "preserved work", false, None)
7568        });
7569        task.runs = vec![run.id.clone()];
7570        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7571        assert_eq!(
7572            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7573            Starter::Resume(run.id.clone())
7574        );
7575        assert!(matches!(
7576            review_retry_starter(
7577                &task,
7578                Some(&run),
7579                Some("different"),
7580                true,
7581                unfinished.as_deref()
7582            ),
7583            Starter::Review(_)
7584        ));
7585        assert_eq!(
7586            review_retry_starter(
7587                &task,
7588                Some(&run),
7589                Some(branch),
7590                false,
7591                unfinished.as_deref()
7592            ),
7593            Starter::Start
7594        );
7595        task.instruction.push_str(" changed criteria");
7596        assert!(matches!(
7597            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7598            Starter::Review(_)
7599        ));
7600        assert!(matches!(
7601            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7602            Starter::Review(_)
7603        ));
7604    }
7605
7606    #[test]
7607    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7608        let dir = tempfile::tempdir().unwrap();
7609        let queue = Queue::at(dir.path().join("queue"));
7610        let mut task = task();
7611        task.status = TaskStatus::Running;
7612        task.attempts = 1;
7613        queue.put(&mut task).unwrap();
7614        let live = std::collections::BTreeSet::from([task.id.clone()]);
7615        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7616        drop(queue.claim(&task.id).unwrap());
7617        let saved = queue.get(&task.id).unwrap();
7618        assert_eq!(saved.status, TaskStatus::Running);
7619        assert_eq!(saved.attempts, 1);
7620        assert!(saved.last_error.is_none());
7621    }
7622
7623    #[test]
7624    fn standalone_workers_do_not_consume_scheduler_lanes() {
7625        let request = |task: &str, lane, standalone| TaskWorker {
7626            opts: Opts::default(),
7627            queue: PathBuf::from("/queue"),
7628            task: task.to_owned(),
7629            lane,
7630            standalone,
7631        };
7632        let mut jobs = vec![
7633            request("ordinary", PermitKind::Ordinary, false),
7634            request("standalone-urgent", PermitKind::Urgent, true),
7635            request("standalone-ordinary", PermitKind::Ordinary, true),
7636            request("decision", PermitKind::None, false),
7637        ];
7638        assert_eq!(available_slots(&jobs, 2), (1, 1));
7639        jobs.push(request("urgent", PermitKind::Urgent, false));
7640        assert_eq!(available_slots(&jobs, 2), (1, 0));
7641        assert_eq!(available_slots(&jobs, 0), (0, 0));
7642    }
7643
7644    #[test]
7645    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7646        let now = Timestamp::now();
7647        let mut reading = Reading {
7648            pid: Some(std::process::id()),
7649            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7650            ..Reading::default()
7651        };
7652        assert!(!reading.running(now));
7653        assert!(legacy_scheduler_running(&reading, now, 0));
7654        reading.worker_protocol = Some(1);
7655        assert!(!legacy_scheduler_running(&reading, now, 0));
7656    }
7657
7658    #[test]
7659    fn selected_public_head_overrides_historical_resume_and_pin() {
7660        let mut t = task();
7661        let mut old = run_state(RunStatus::Blocked);
7662        let selection = crate::pr_recovery::Selection {
7663            url: "url".into(),
7664            branch: format!("magi/task-{}", t.id),
7665            head: "a".repeat(40),
7666            source_head: None,
7667            source_run: None,
7668            source_proof: None,
7669            disposition: Some(crate::pr_recovery::Disposition::Review),
7670            instruction: t.instruction.clone(),
7671            approved_at: Timestamp::now(),
7672        };
7673        t.resume_override = Some(crate::queue::OperatorResume {
7674            pinned_run: Some(old.id.clone()),
7675            question_id: "choice".into(),
7676            at: Timestamp::now(),
7677            conductor_rehold: None,
7678            forced: false,
7679        });
7680        assert_eq!(
7681            selected_starter(&selection, Some(&old), Some(&old.id)),
7682            Starter::Review(selection.branch.clone())
7683        );
7684        old.pr_recovery = Some(selection.clone());
7685        assert_eq!(
7686            selected_starter(&selection, Some(&old), Some(&old.id)),
7687            Starter::Review(selection.branch.clone())
7688        );
7689        old.reviewed_commits = Some(vec!["implementation".into()]);
7690        assert_eq!(
7691            selected_starter(&selection, Some(&old), Some(&old.id)),
7692            Starter::Resume(old.id.clone())
7693        );
7694        let mut changed = selection.clone();
7695        changed.head = "b".repeat(40);
7696        assert_eq!(
7697            selected_starter(&changed, Some(&old), Some(&old.id)),
7698            Starter::Review(changed.branch)
7699        );
7700    }
7701
7702    #[test]
7703    fn candidate_transplant_failure_is_one_actionable_hold() {
7704        let dir = tempfile::tempdir().unwrap();
7705        let q = Queue::at(dir.path().join("queue"));
7706        let mut t = task();
7707        let mut state = run_state(RunStatus::Blocked);
7708        state.event("prep", "cannot apply referenced commit: conflict");
7709        state.prep_failure = Some("conflict".into());
7710        t.start(state.id.clone());
7711        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7712        assert_eq!(t.attempts, 1);
7713        assert_eq!(t.status, TaskStatus::Held);
7714        assert!(t.operator_held());
7715        assert!(!t.status.runnable());
7716        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7717        let first = t.chat_notice_key().unwrap();
7718        t.chat_notices.push(first.clone());
7719        t.release_operator("test", None);
7720        state.id = "another-unprepared-run".into();
7721        t.start(state.id.clone());
7722        finish_attempt(
7723            3,
7724            &q,
7725            &mut t,
7726            &state,
7727            &[],
7728            Err(anyhow::anyhow!("still conflicts")),
7729        );
7730        assert_eq!(
7731            t.chat_notice_key().as_ref(),
7732            Some(&first),
7733            "no work happened"
7734        );
7735        t.release_operator("test", None);
7736        state.prep_failure = None;
7737        state.status = RunStatus::Failed;
7738        state.begin_pass();
7739        t.start(state.id.clone());
7740        finish_attempt(
7741            1,
7742            &q,
7743            &mut t,
7744            &state,
7745            &[],
7746            Err(anyhow::anyhow!("new gate failure")),
7747        );
7748        let failure = t.chat_notice_key().unwrap();
7749        assert_ne!(failure, first, "approved recovery reached a real failure");
7750        t.release_operator("test", None);
7751        state.begin_pass();
7752        t.start(state.id.clone());
7753        finish_attempt(
7754            1,
7755            &q,
7756            &mut t,
7757            &state,
7758            &[],
7759            Err(anyhow::anyhow!("new failure on resume")),
7760        );
7761        assert_ne!(
7762            t.chat_notice_key().as_ref(),
7763            Some(&failure),
7764            "a new settled pass"
7765        );
7766    }
7767
7768    #[test]
7769    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7770        for source in ["cli", "web"] {
7771            let mut t = task();
7772            let mut run = run_state(RunStatus::Blocked);
7773            run.instruction = "Run A original criteria".into();
7774            run.task_instruction = Some(run.instruction.clone());
7775            t.start(run.id.clone());
7776            t.release_operator("choice", Some("resume-question"));
7777            t.resume_override = Some(crate::queue::OperatorResume {
7778                question_id: "resume-question".into(),
7779                at: Timestamp::now(),
7780                conductor_rehold: None,
7781                forced: true,
7782                pinned_run: Some(run.id.clone()),
7783            });
7784            t.hold_machine(Some("not enough free space to start a run".into()));
7785            let mut unchanged = t.clone();
7786            unchanged
7787                .edit("title changed".into(), unchanged.instruction.clone())
7788                .unwrap();
7789            unchanged.release_operator(source, None);
7790            assert_eq!(
7791                unchanged
7792                    .resume_override
7793                    .as_ref()
7794                    .unwrap()
7795                    .pinned_run
7796                    .as_deref(),
7797                Some(run.id.as_str())
7798            );
7799            assert!(!compatible_run_instruction(&run, &unchanged));
7800            assert!(may_resume_run(&run, &unchanged));
7801
7802            t.edit(
7803                "approved recovery".into(),
7804                "Reuse measured PR head B; fix Clippy; review".into(),
7805            )
7806            .unwrap();
7807            assert!(t.resume_override.is_none());
7808            t.release_operator(source, None);
7809            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7810            assert!(reloaded.resume_override.is_none());
7811            assert!(!may_resume_run(&run, &reloaded));
7812            let unfinished =
7813                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7814                    .filter(|_| may_resume_run(&run, &reloaded));
7815            assert_eq!(
7816                choose_starter(None, false, unfinished.as_deref()),
7817                Starter::Start
7818            );
7819            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7820            assert_eq!(
7821                reloaded.resumption_history[0].question_id.as_deref(),
7822                Some("resume-question")
7823            );
7824
7825            // A revision already persisted with the old approval/pin is also
7826            // invalidated when the new operator release is recorded.
7827            unchanged.instruction = "Reuse measured PR head B".into();
7828            unchanged.hold_machine(Some("disk hold".into()));
7829            unchanged.release_operator(source, None);
7830            assert!(unchanged.resume_override.is_none());
7831            assert!(!may_resume_run(&run, &unchanged));
7832        }
7833    }
7834
7835    #[test]
7836    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7837        let mut t = task();
7838        let mut run = run_state(RunStatus::Blocked);
7839        t.review_of = Some("approved-head".into());
7840        t.instruction =
7841            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7842                .into();
7843        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();
7844        run.reviewed_commits = Some(vec!["Commit log".into()]);
7845        t.start(run.id.clone());
7846        t.hold_machine(Some("interrupted review".into()));
7847        t.release_operator("cli", None);
7848        assert!(
7849            compatible_run_instruction(&run, &t),
7850            "legacy explicit review remains resumable"
7851        );
7852        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7853            .filter(|_| compatible_run_instruction(&run, &t));
7854        assert_eq!(
7855            choose_starter(None, false, unfinished.as_deref()),
7856            Starter::Resume(run.id.clone())
7857        );
7858        run.task_instruction = Some(t.instruction.clone());
7859        assert!(compatible_run_instruction(&run, &t));
7860        let reloaded: RunState =
7861            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7862        assert!(compatible_run_instruction(&reloaded, &t));
7863        t.edit(
7864            "new approved head".into(),
7865            "Reuse measured PR head B".into(),
7866        )
7867        .unwrap();
7868        assert!(!compatible_run_instruction(&run, &t));
7869
7870        // Legacy recovery reviews retain the task criteria ahead of the log.
7871        t.review_of = None;
7872        t.instruction = "Fix Clippy on approved head".into();
7873        run.task_instruction = None;
7874        run.instruction = format!(
7875            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7876            t.instruction
7877        );
7878        assert!(compatible_run_instruction(&run, &t));
7879        t.instruction.push('\n');
7880        assert!(
7881            compatible_run_instruction(&run, &t),
7882            "legacy generated review trimmed the original criteria"
7883        );
7884        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7885        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7886        t.edit("new plan".into(), "Reuse measured PR head B".into())
7887            .unwrap();
7888        assert!(review_branch_for(&t, Some(&run)).is_none());
7889        assert!(!compatible_run_instruction(&run, &t));
7890        t.review_branch = Some("approved-head".into());
7891        t.review_instruction = None;
7892        assert!(
7893            review_branch_for(&t, Some(&run)).is_none(),
7894            "legacy retained candidate cannot replace a revised approved head"
7895        );
7896    }
7897
7898    #[test]
7899    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7900        let home = crate::run::test_home();
7901        crate::run::pin_test_home();
7902        let dir = tempfile::tempdir().unwrap();
7903        let queue = Queue::at(dir.path().join("queue"));
7904        for resume in [true, false] {
7905            let state = run_state(RunStatus::Blocked);
7906            let mut t = task();
7907            t.start(state.id.clone());
7908            let action = if resume {
7909                ask::ChoiceAction::Resume {
7910                    run: state.id.clone(),
7911                }
7912            } else {
7913                ask::ChoiceAction::Requeue
7914            };
7915            let mut q = action_question(&state.id, action);
7916            q.status = ask::QuestionStatus::Open;
7917            q.answer = None;
7918            q.answered_at = None;
7919            t.fail("run stopped with a question", 3);
7920            hold_if_runnable(&queue, &mut t);
7921            assert!(t.operator_decided_at.is_none());
7922            assert!(t.operator_held());
7923            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7924            let expected = if resume {
7925                ActionDecision::Resume(state.id.clone())
7926            } else {
7927                ActionDecision::Requeue
7928            };
7929            assert_eq!(
7930                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7931                expected
7932            );
7933            t.hold_manual(Some("later explicit hold".into()));
7934            assert_eq!(
7935                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7936                ActionDecision::Stale
7937            );
7938        }
7939    }
7940
7941    #[test]
7942    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7943        let mut t = task();
7944        t.answers.push(crate::queue::AnsweredQuestion {
7945            question: "Inspect the remote?".into(),
7946            answer: "Inspect then wait".into(),
7947        });
7948        let old = instruction_for(&t);
7949        assert!(compatible_instruction(&old, &t));
7950        t.instruction = "Reuse approved PR head and review".into();
7951        t.release_operator("cli", None);
7952        assert!(!compatible_instruction(&old, &t));
7953        let approved = instruction_for(&t);
7954        assert!(approved.contains("waiting premises are superseded"));
7955        assert!(compatible_instruction(&approved, &t));
7956        assert_eq!(resumed_instruction(&approved, &t), approved);
7957        t.release_operator("web", None);
7958        assert!(compatible_instruction(&approved, &t));
7959        assert_eq!(t.resumption_history.len(), 1);
7960        t.start("run".into());
7961        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7962    }
7963
7964    /// A run that stopped on an infrastructure wait asked no agent anything:
7965    /// the task is held by the machine under a `[resource]` reason (resumable,
7966    /// re-checked by triage), and the attempt it started is given back.
7967    #[test]
7968    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7969        let mut state = RunState::new(
7970            PathBuf::from("/repo"),
7971            "main".into(),
7972            "base".into(),
7973            "task".into(),
7974            Config::default(),
7975        );
7976        state.status = RunStatus::Landing;
7977        state.parked = true;
7978        state.pr_pushed_head = Some("head".into());
7979        state.land_unrelated = Some(
7980            serde_json::from_value(serde_json::json!({
7981                "head": "head", "question": "ci-question",
7982                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
7983            }))
7984            .unwrap(),
7985        );
7986        let mut t = task();
7987        t.start(state.id.clone());
7988        let verdict = Verdict {
7989            status: RunStatus::Landing,
7990            left_pr: true,
7991            quota_hit: false,
7992            parked: true,
7993            no_viable_candidates: false,
7994        };
7995        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
7996        assert_eq!(t.attempts, 0);
7997        assert_eq!(t.status, TaskStatus::Held);
7998        assert!(!t.operator_held());
7999        assert!(
8000            t.hold_reason
8001                .as_deref()
8002                .unwrap()
8003                .starts_with("[ci-unrelated]")
8004        );
8005        // A second settlement must not refund an earlier task attempt.
8006        t.attempts = 1;
8007        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8008        assert_eq!(t.attempts, 1);
8009        assert_eq!(t.passes.len(), 1);
8010        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8011        state.pr_pushed_head = Some("new-head".into());
8012        state.parked = false;
8013        state.status = RunStatus::Blocked;
8014        let stale = Verdict {
8015            status: RunStatus::Blocked,
8016            parked: false,
8017            ..verdict
8018        };
8019        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
8020        assert_eq!(t.attempts, 1);
8021        // A new execution pass can refund its own newly charged attempt.
8022        state.begin_pass();
8023        state.begin_pass();
8024        state.status = RunStatus::Landing;
8025        state.parked = true;
8026        state.pr_pushed_head = Some("head".into());
8027        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
8028        assert_eq!(t.attempts, 0);
8029        assert_eq!(t.passes.len(), 2);
8030    }
8031
8032    #[test]
8033    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
8034        let mut state = run_state(RunStatus::Failed);
8035        state
8036            .quota
8037            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
8038        state.begin_pass();
8039        let mut t = task();
8040        t.start(state.id.clone());
8041        reclaim(&mut t, Some(state), 2, "en");
8042        assert_eq!(t.attempts, 1);
8043    }
8044
8045    #[test]
8046    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
8047        let mut state = run_state(RunStatus::Blocked);
8048        let losses: Vec<_> = ["alpha", "beta"]
8049            .into_iter()
8050            .enumerate()
8051            .map(|(i, agent)| {
8052                QuotaLoss::from_report(
8053                    format!("advisor-{i}"),
8054                    "advise",
8055                    Some(&crate::agent::Quota {
8056                        cause: crate::agent::QuotaCause::Authentication,
8057                        agent: agent.to_owned(),
8058                        reset: None,
8059                    }),
8060                )
8061            })
8062            .collect();
8063        crate::graph::block_machine_outage(&mut state, "advise", &losses);
8064        state.quota = losses;
8065        let mut t = task();
8066        t.start(state.id.clone());
8067        let verdict = Verdict {
8068            status: state.status,
8069            left_pr: false,
8070            quota_hit: true,
8071            parked: false,
8072            no_viable_candidates: true,
8073        };
8074        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
8075        assert_eq!(t.attempts, 0);
8076        assert_eq!(t.status, TaskStatus::Held);
8077        assert!(!t.operator_held());
8078        let reason = t.hold_reason.as_deref().unwrap();
8079        assert!(reason.starts_with("[authentication]"));
8080        assert!(
8081            reason.contains("alpha")
8082                && reason.contains("beta")
8083                && reason.contains("re-authenticate")
8084        );
8085        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
8086        // Orphan recovery uses the same settlement and cannot spend an attempt.
8087        let mut orphan = task();
8088        orphan.start(state.id.clone());
8089        reclaim(&mut orphan, Some(state), 2, "en");
8090        assert_eq!(orphan.attempts, 0);
8091        assert_eq!(orphan.status, TaskStatus::Held);
8092    }
8093
8094    #[test]
8095    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
8096        let mut state = RunState::new(
8097            PathBuf::from("/repo"),
8098            "main".to_owned(),
8099            "abc1234".to_owned(),
8100            "task".to_owned(),
8101            Config::default(),
8102        );
8103        state.status = RunStatus::Blocked;
8104        state.resource_block = Some(crate::run::ResourceBlock {
8105            cause: crate::run::ResourceBlockCause::Other,
8106            node: "graft".to_owned(),
8107            kind: "shared build cache".to_owned(),
8108            detail: "timed out".to_owned(),
8109            at: jiff::Timestamp::now(),
8110        });
8111        let mut t = task();
8112        t.start("20260902-000000-aaaa".to_owned());
8113        assert_eq!(t.attempts, 1);
8114        let verdict = Verdict {
8115            status: RunStatus::Blocked,
8116            left_pr: false,
8117            quota_hit: false,
8118            parked: false,
8119            no_viable_candidates: false,
8120        };
8121        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
8122        assert_eq!(t.status, TaskStatus::Held);
8123        assert_eq!(t.attempts, 0, "the attempt is refunded");
8124        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
8125        assert!(
8126            !t.operator_held(),
8127            "a machine hold, released without a human"
8128        );
8129
8130        let mut selected = task();
8131        selected.start("20260902-000000-cccc".into());
8132        selected.replacement = Some(crate::merge_decision::Replacement {
8133            question: "fixture".into(),
8134            run: "earlier".into(),
8135            pr: "https://example.invalid/pr/1".into(),
8136            agent: "selected".into(),
8137            context: "fixture".into(),
8138        });
8139        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
8140        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
8141        assert_eq!(selected.attempts, 0);
8142        assert!(
8143            !selected.operator_held(),
8144            "a selected agent also retains a machine resource hold"
8145        );
8146        assert!(
8147            selected
8148                .hold_reason
8149                .as_deref()
8150                .unwrap()
8151                .starts_with("[resource] ")
8152        );
8153
8154        // A park request outranks it: still the operator's doing.
8155        let mut p = task();
8156        p.start("20260902-000000-bbbb".to_owned());
8157        settle_and_diagnose(
8158            &mut p,
8159            Verdict {
8160                parked: true,
8161                ..verdict
8162            },
8163            "parked",
8164            2,
8165            &state,
8166        );
8167        assert_eq!(p.status, TaskStatus::Parked);
8168        assert_eq!(
8169            p.attempts, 0,
8170            "parking refunds once rather than also settling the resource hold"
8171        );
8172    }
8173
8174    #[test]
8175    fn record_failure_notice_links_the_task() {
8176        let dir = tempfile::tempdir().unwrap();
8177        // A regular file where the queue directory should be makes every
8178        // `put` fail, on every platform and whoever runs the test.
8179        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
8180        let queue = Queue::at(dir.path().join("queue"));
8181        let mut t = interrupt_task("rec-fail-1");
8182        record(&queue, &mut t);
8183
8184        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
8185        assert_eq!(found.len(), 1);
8186        assert_eq!(found[0].key, "loop:record");
8187        assert_eq!(
8188            found[0].link,
8189            Some(Link::Task {
8190                id: "rec-fail-1".to_owned()
8191            })
8192        );
8193    }
8194
8195    /// A runnable task marked to interrupt, with an id fixed for assertions
8196    /// rather than the random one [`Task::new`] mints.
8197    fn interrupt_task(id: &str) -> Task {
8198        let mut t = task();
8199        t.id = id.to_owned();
8200        t.interrupt = true;
8201        t
8202    }
8203
8204    /// An ordinary runnable task with an id fixed for assertions.
8205    fn task_with_id(id: &str) -> Task {
8206        let mut t = task();
8207        t.id = id.to_owned();
8208        t
8209    }
8210
8211    /// A runnable task marked `--urgent`, with an id fixed for assertions.
8212    fn urgent_task(id: &str) -> Task {
8213        let mut t = task();
8214        t.id = id.to_owned();
8215        t.urgent = true;
8216        t
8217    }
8218
8219    #[test]
8220    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
8221        let dir = tempfile::tempdir().unwrap();
8222        let queue = Queue::at(dir.path().join("queue"));
8223        let mut parked = task_with_id("parked");
8224        parked.start("run".into());
8225        parked.park("upgrade");
8226        parked.record_pass_at(
8227            "run",
8228            0,
8229            Some(Timestamp::now()),
8230            1,
8231            Some(crate::run::ParkCause::Upgrade {
8232                from: "old".into(),
8233                to: None,
8234            }),
8235        );
8236        let mut fresh = task_with_id("fresh");
8237        fresh.priority = 100;
8238        let mut urgent_task = urgent_task("urgent");
8239        for t in [&mut parked, &mut fresh, &mut urgent_task] {
8240            queue.put(t).unwrap();
8241        }
8242        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8243        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8244        let candidates = runnable(&queue);
8245        assert_eq!(candidates[0].id, parked.id);
8246        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
8247        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
8248        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
8249        drop(first);
8250        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
8251        let next = runnable(&queue)
8252            .into_iter()
8253            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
8254            .unwrap();
8255        assert_eq!(next.task.id, fresh.id);
8256        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
8257        drop(claimed_elsewhere);
8258        drop(next);
8259        assert!(matches!(
8260            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
8261            Err(SkipReason::CoolingDown)
8262        ));
8263    }
8264
8265    #[test]
8266    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
8267        let dir = tempfile::tempdir().unwrap();
8268        let queue = Queue::at(dir.path().join("queue"));
8269        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8270        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8271        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
8272        let mut first = task();
8273        queue.put(&mut first).unwrap();
8274        let stale_plain = queue.get(&first.id).unwrap();
8275        first.set_urgent(true).unwrap();
8276        queue.put(&mut first).unwrap();
8277        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
8278        let mut second = urgent_task("second");
8279        queue.put(&mut second).unwrap();
8280        assert!(matches!(
8281            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
8282            Err(SkipReason::UrgentCapacity)
8283        ));
8284        drop(queue.claim(&second.id).unwrap());
8285        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
8286        drop(dispatched);
8287        let stale_urgent = queue.get(&first.id).unwrap();
8288        first.set_urgent(false).unwrap();
8289        queue.put(&mut first).unwrap();
8290        assert!(matches!(
8291            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
8292            Err(SkipReason::OrdinaryCapacity)
8293        ));
8294        assert_eq!(urgent.available_permits(), 1);
8295        drop(queue.claim(&first.id).unwrap());
8296        drop(occupied);
8297    }
8298
8299    #[test]
8300    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8301        let dir = tempfile::tempdir().unwrap();
8302        let queue = Queue::at(dir.path().join("queue"));
8303        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8304        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8305        let mut t = task();
8306        queue.put(&mut t).unwrap();
8307        for enabled in [true, false] {
8308            let stale = queue.get(&t.id).unwrap();
8309            t.set_urgent(enabled).unwrap();
8310            queue.put(&mut t).unwrap();
8311            assert_ne!(stale.urgent, enabled);
8312            let DispatchClaim {
8313                task: fresh,
8314                claim,
8315                permit,
8316            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8317            assert_eq!(fresh.urgent, enabled);
8318            assert_eq!(ordinary.available_permits(), usize::from(enabled));
8319            assert_eq!(urgent.available_permits(), usize::from(!enabled));
8320            assert!(queue.claim(&t.id).is_err());
8321            assert_eq!(fresh.attempts, stale.attempts);
8322            drop((claim, permit));
8323            assert_eq!(ordinary.available_permits(), 1);
8324            assert_eq!(urgent.available_permits(), 1);
8325        }
8326        t.set_urgent(true).unwrap();
8327        queue.put(&mut t).unwrap();
8328        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8329        assert!(matches!(
8330            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8331            Err(SkipReason::UrgentCapacity)
8332        ));
8333        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8334        drop(queue.claim(&t.id).unwrap());
8335        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8336        drop(occupied);
8337        assert!(matches!(
8338            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8339            Err(SkipReason::CoolingDown)
8340        ));
8341        drop(queue.claim(&t.id).unwrap());
8342        let held = queue.claim(&t.id).unwrap();
8343        assert!(matches!(
8344            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8345            Err(SkipReason::ClaimUnavailable)
8346        ));
8347        drop(held);
8348        t.status = TaskStatus::Held;
8349        queue.put(&mut t).unwrap();
8350        assert!(matches!(
8351            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8352            Err(SkipReason::NoLongerRunnable)
8353        ));
8354        drop(queue.claim(&t.id).unwrap());
8355        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8356        assert!(matches!(
8357            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8358            Err(SkipReason::RereadFailed)
8359        ));
8360        drop(queue.claim(&t.id).unwrap());
8361        assert_eq!(urgent.available_permits(), 1);
8362    }
8363
8364    /// The land-resume exemption wins outright, whether or not the candidate
8365    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
8366    /// queue behind anything" guarantee cannot be weaker just because the
8367    /// same task was also filed with `--urgent`.
8368    #[test]
8369    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8370        assert_eq!(permit_kind(true, false), PermitKind::None);
8371        assert_eq!(permit_kind(true, true), PermitKind::None);
8372    }
8373
8374    /// The one property this whole feature exists for: `--urgent` draws from
8375    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
8376    /// ordinary candidate draws from the ordinary pool exactly as before,
8377    /// untouched by the urgent slot's existence.
8378    #[test]
8379    fn permit_kind_separates_urgent_from_ordinary() {
8380        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8381        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8382    }
8383
8384    /// The exact wiring `attempt` runs before minting anything: a config's
8385    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
8386    /// Free space is injected rather than asked of the real disk - the point
8387    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
8388    /// is deterministic on every machine this test runs on, never dependent
8389    /// on how full the CI runner's own disk happens to be.
8390    #[test]
8391    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8392        let cfg = Config::default();
8393        let repo = Path::new("/any/repo/path");
8394
8395        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8396            .expect("must hold below the threshold");
8397        assert!(reason.contains("1024"), "{reason}");
8398        assert!(
8399            reason.contains(&cfg.disk.min_free_bytes.to_string()),
8400            "{reason}"
8401        );
8402
8403        assert_eq!(
8404            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8405            None,
8406            "exactly at the floor is open"
8407        );
8408        assert_eq!(
8409            disk_gate_with(
8410                repo,
8411                &cfg,
8412                PathBuf::new,
8413                |_| Ok(cfg.disk.min_free_bytes + 1)
8414            ),
8415            None,
8416            "comfortably above the floor is open"
8417        );
8418    }
8419
8420    #[test]
8421    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8422        let dir = tempfile::tempdir().unwrap();
8423        let repo = dir.path().join("repo");
8424        let cache = dir.path().join("cache");
8425        let worktrees = dir.path().join("worktrees");
8426        for path in [&repo, &cache, &worktrees] {
8427            std::fs::create_dir(path).unwrap();
8428        }
8429        let mut cfg = Config::default();
8430        cfg.graph.worktree_root = Some(worktrees.clone());
8431        cfg.verify.gate = vec![format!(
8432            "CARGO_TARGET_DIR='{}' cargo build",
8433            cache.display()
8434        )];
8435        for blocked in [&cache, &worktrees] {
8436            for unmeasured in [false, true] {
8437                assert!(
8438                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8439                        if path == blocked {
8440                            if unmeasured {
8441                                Err(anyhow::anyhow!("measurement failed"))
8442                            } else {
8443                                Ok(0)
8444                            }
8445                        } else {
8446                            Ok(u64::MAX)
8447                        }
8448                    })
8449                    .is_some(),
8450                    "a blocked secondary output volume must close admission"
8451                );
8452            }
8453        }
8454        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8455    }
8456
8457    #[test]
8458    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8459        let dir = tempfile::tempdir().unwrap();
8460        let repo = dir.path().join("repo");
8461        let cache = dir.path().join("cache");
8462        let home_parent = dir.path().join("run-volume");
8463        let home = home_parent.join("new-home");
8464        for path in [&repo, &cache, &home_parent] {
8465            std::fs::create_dir(path).unwrap();
8466        }
8467        let mut cfg = Config::default();
8468        cfg.graph.worktree_root = Some(repo.clone());
8469        cfg.verify.gate = vec![format!(
8470            "CARGO_TARGET_DIR='{}' cargo build",
8471            cache.display()
8472        )];
8473        cfg.verify.build_cache = BuildCache::Isolated;
8474        let denied = |blocked: &Path| {
8475            disk_gate_with(
8476                &repo,
8477                &cfg,
8478                || home.clone(),
8479                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8480            )
8481            .is_some()
8482        };
8483        assert!(!denied(&cache));
8484        assert!(denied(&home_parent));
8485    }
8486
8487    #[test]
8488    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8489        let mut cfg = Config::default();
8490        cfg.disk.min_free_bytes = 0;
8491        let repo = Path::new("/any/repo/path");
8492        assert_eq!(
8493            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8494            None,
8495            "a zero floor never measures at all"
8496        );
8497    }
8498
8499    #[test]
8500    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8501        let cfg = Config::default();
8502        let repo = Path::new("/any/repo/path");
8503        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8504            Err(anyhow::anyhow!("no df on this box"))
8505        })
8506        .expect("a measurement failure must close the gate, not open it");
8507        assert!(reason.contains("could not measure"), "{reason}");
8508    }
8509
8510    #[test]
8511    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8512        let ordinary = task();
8513        let next = advance_interrupt(
8514            Interrupt::Idle,
8515            std::slice::from_ref(&ordinary.id),
8516            std::slice::from_ref(&ordinary),
8517        );
8518        assert_eq!(next, Interrupt::Idle);
8519    }
8520
8521    #[test]
8522    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8523        // Nothing to interrupt - this is just an ordinary candidate, and the
8524        // loop's normal dispatch will pick it up like any other.
8525        let marked = interrupt_task("marked");
8526        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8527        assert_eq!(next, Interrupt::Idle);
8528    }
8529
8530    #[test]
8531    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8532        let marked = interrupt_task("marked");
8533        let next = advance_interrupt(
8534            Interrupt::Idle,
8535            &["running".to_owned()],
8536            std::slice::from_ref(&marked),
8537        );
8538        assert_eq!(
8539            next,
8540            Interrupt::Parking {
8541                parked: vec!["running".to_owned()],
8542                interrupt_task: "marked".to_owned(),
8543            }
8544        );
8545    }
8546
8547    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8548    /// one run can be in flight when a task becomes runnable and marked.
8549    /// Parking all of them would mean `Resuming` later has more than one id
8550    /// to release back to ordinary dispatch, which cannot be made safe
8551    /// against that same setting's own extra concurrency slots letting two
8552    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8553    /// The simplification the task's own constraints ask for: do not begin
8554    /// a sequence at all until the herd settles back to exactly one.
8555    #[test]
8556    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8557        let marked = interrupt_task("marked");
8558
8559        let two = advance_interrupt(
8560            Interrupt::Idle,
8561            &["a".to_owned(), "b".to_owned()],
8562            std::slice::from_ref(&marked),
8563        );
8564        assert_eq!(two, Interrupt::Idle);
8565
8566        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8567        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8568    }
8569
8570    #[test]
8571    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8572        let state = Interrupt::Parking {
8573            parked: vec!["running".to_owned()],
8574            interrupt_task: "marked".to_owned(),
8575        };
8576        // Still in flight: no change.
8577        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8578        assert_eq!(still_going, state);
8579
8580        // Left flight, but the interrupt task has not been dispatched yet on
8581        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8582        // as long as it is still runnable.
8583        let stopped_but_not_yet_dispatched =
8584            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8585        assert_eq!(stopped_but_not_yet_dispatched, state);
8586
8587        // Left flight, and the interrupt task is now in flight itself.
8588        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8589        assert_eq!(
8590            dispatched,
8591            Interrupt::Running {
8592                parked: vec!["running".to_owned()],
8593                interrupt_task: "marked".to_owned(),
8594            }
8595        );
8596    }
8597
8598    #[test]
8599    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8600        let state = Interrupt::Running {
8601            parked: vec!["running".to_owned()],
8602            interrupt_task: "marked".to_owned(),
8603        };
8604        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8605        assert_eq!(still_running, state);
8606
8607        // Whatever it ended as - merged, failed, held - is not this
8608        // function's concern: leaving flight is the only trigger, driven
8609        // straight off the same in-flight list `poll` already reaps. It does
8610        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8611        // why that would let an unrelated task start ahead of, or alongside,
8612        // the guaranteed resume.
8613        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8614        assert_eq!(
8615            ended,
8616            Interrupt::Resuming {
8617                parked: vec!["running".to_owned()]
8618            }
8619        );
8620    }
8621
8622    #[test]
8623    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8624        let state = Interrupt::Resuming {
8625            parked: vec!["running".to_owned()],
8626        };
8627        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8628        assert_eq!(still_waiting, state);
8629
8630        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8631        assert_eq!(dispatched, Interrupt::Idle);
8632    }
8633
8634    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8635    /// or otherwise moved on by an operator with no claim standing in the
8636    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8637    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8638    /// come. The parked run still gets its resume.
8639    #[test]
8640    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8641    {
8642        let state = Interrupt::Parking {
8643            parked: vec!["running".to_owned()],
8644            interrupt_task: "marked".to_owned(),
8645        };
8646        // `marked` has been held/blocked/deleted since the sequence began:
8647        // it no longer appears in `runnable` at all.
8648        let next = advance_interrupt(state, &[], &[]);
8649        assert_eq!(
8650            next,
8651            Interrupt::Resuming {
8652                parked: vec!["running".to_owned()]
8653            },
8654            "abandoning the interrupt must not abandon the resume it owes"
8655        );
8656    }
8657
8658    /// The same abandonment, one step later: `Resuming` itself must not wait
8659    /// forever for a parked task that has since become unrunnable.
8660    #[test]
8661    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8662        let state = Interrupt::Resuming {
8663            parked: vec!["running".to_owned()],
8664        };
8665        let next = advance_interrupt(state, &[], &[]);
8666        assert_eq!(
8667            next,
8668            Interrupt::Idle,
8669            "nothing is left to wait for; the loop must not stay wedged"
8670        );
8671    }
8672
8673    #[test]
8674    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8675        let marked = interrupt_task("marked");
8676        let next = advance_interrupt_tick(
8677            false,
8678            Interrupt::Idle,
8679            &["running".to_owned()],
8680            std::slice::from_ref(&marked),
8681        );
8682        assert_eq!(
8683            next,
8684            Interrupt::Idle,
8685            "an unmarked, unconfigured daemon must behave exactly as before"
8686        );
8687    }
8688
8689    #[test]
8690    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8691        let state = Interrupt::Parking {
8692            parked: vec!["running".to_owned()],
8693            interrupt_task: "marked".to_owned(),
8694        };
8695        let candidates = vec![interrupt_task("marked"), task()];
8696        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8697        assert!(
8698            allowed.is_empty(),
8699            "nothing may dispatch - not even the interrupt task itself - \
8700             until the parked run has actually stopped"
8701        );
8702    }
8703
8704    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8705    /// grow a special case for it: an urgent candidate that is not the
8706    /// interrupt task withholds exactly like an ordinary one for as long as
8707    /// the parked run it is racing has not actually left flight. A version
8708    /// of this feature once bypassed the gate for urgent candidates, on the
8709    /// theory that a genuinely separate concurrency lane could not collide
8710    /// with 75dd's own; it could, and did - the bypassed task dispatched
8711    /// alongside a run 75dd's own state machine had only *asked* to park,
8712    /// not yet confirmed gone, which is exactly the second run
8713    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8714    /// tick during Parking/Running/Resuming where letting an extra
8715    /// candidate through is safe, urgent or not - the parked run may still
8716    /// be genuinely mid-call.
8717    #[test]
8718    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8719        for state in [
8720            Interrupt::Parking {
8721                parked: vec!["running".to_owned()],
8722                interrupt_task: "marked".to_owned(),
8723            },
8724            Interrupt::Running {
8725                parked: vec!["running".to_owned()],
8726                interrupt_task: "marked".to_owned(),
8727            },
8728            Interrupt::Resuming {
8729                parked: vec!["running".to_owned()],
8730            },
8731        ] {
8732            let candidates = vec![
8733                interrupt_task("marked"),
8734                urgent_task("hot"),
8735                task_with_id("ordinary"),
8736            ];
8737            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8738            assert!(
8739                !allowed.iter().any(|t| t.id == "hot"),
8740                "an urgent candidate must wait out the same gate as anything \
8741                 else while the run it would run alongside has not actually \
8742                 left flight, for state {state:?}: {allowed:?}"
8743            );
8744        }
8745    }
8746
8747    /// The one case where marking a task `--urgent` and `interrupt` at once
8748    /// is not redundant: once the interrupt sequence's own guaranteed
8749    /// resume/dispatch actually admits the task, it is unaffected by also
8750    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8751    /// never on the urgent flag.
8752    #[test]
8753    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8754        let state = Interrupt::Resuming {
8755            parked: vec!["hot".to_owned()],
8756        };
8757        let candidates = vec![urgent_task("hot"), task()];
8758        let allowed = interrupt_gate(&state, &[], candidates);
8759        assert_eq!(
8760            allowed.iter().filter(|t| t.id == "hot").count(),
8761            1,
8762            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8763        );
8764    }
8765
8766    #[test]
8767    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8768        let state = Interrupt::Parking {
8769            parked: vec!["running".to_owned()],
8770            interrupt_task: "marked".to_owned(),
8771        };
8772        let other = task();
8773        let candidates = vec![interrupt_task("marked"), other.clone()];
8774        let allowed = interrupt_gate(&state, &[], candidates);
8775        assert_eq!(allowed.len(), 1);
8776        assert_eq!(allowed[0].id, "marked");
8777    }
8778
8779    #[test]
8780    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8781        let state = Interrupt::Running {
8782            parked: vec!["running".to_owned()],
8783            interrupt_task: "marked".to_owned(),
8784        };
8785        let candidates = vec![task(), task()];
8786        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8787        assert!(allowed.is_empty());
8788    }
8789
8790    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8791    /// sequence began (only reachable above the default
8792    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8793    /// never both in the same tick, which is what "exactly one resume, no
8794    /// simultaneous run" actually requires structurally rather than by
8795    /// coincidence of how many ordinary slots happen to be free.
8796    #[test]
8797    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8798        let state = Interrupt::Resuming {
8799            parked: vec!["a".to_owned(), "c".to_owned()],
8800        };
8801        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8802        let allowed = interrupt_gate(&state, &[], candidates);
8803        assert_eq!(
8804            allowed.len(),
8805            1,
8806            "at most one candidate may be offered while resuming: {allowed:?}"
8807        );
8808        assert_eq!(allowed[0].id, "a");
8809    }
8810
8811    #[test]
8812    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8813        let state = Interrupt::Resuming {
8814            parked: vec!["a".to_owned()],
8815        };
8816        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8817        assert!(allowed.is_empty());
8818    }
8819
8820    /// The invariant the completion criteria ask for by name: across a whole
8821    /// simulated sequence, there is never a tick where the gate would let
8822    /// through both the parked run's resume and the interrupt task, and
8823    /// exactly one candidate resumes the instant the interrupt task's run
8824    /// ends - never zero, never more than one.
8825    #[test]
8826    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8827        let running = task(); // id: whatever `Task::new` minted
8828        let marked = interrupt_task("marked");
8829
8830        let mut state = Interrupt::Idle;
8831        // Tick 1: `running` is in flight, `marked` becomes runnable.
8832        let in_flight = vec![running.id.clone()];
8833        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8834        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8835        assert!(gated.is_empty(), "still waiting on `running` to park");
8836
8837        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8838        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8839        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8840        assert_eq!(
8841            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8842            vec!["marked"],
8843            "only the interrupt task may be offered to the dispatcher now"
8844        );
8845
8846        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8847        state = advance_interrupt_tick(
8848            true,
8849            state,
8850            &["marked".to_owned()],
8851            std::slice::from_ref(&running),
8852        );
8853        let gated = interrupt_gate(
8854            &state,
8855            &["marked".to_owned()],
8856            vec![marked.clone(), running.clone()],
8857        );
8858        assert!(
8859            gated.is_empty(),
8860            "the parked run must not be offered back while the interrupt \
8861             task is still running"
8862        );
8863
8864        // Tick 4: `marked`'s run reached a terminal status and left flight.
8865        // A higher-priority ordinary task `other` is also runnable now - it
8866        // must not be let through instead of, or alongside, `running`.
8867        let other = task_with_id("other");
8868        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8869        assert_eq!(
8870            state,
8871            Interrupt::Resuming {
8872                parked: vec![running.id.clone()]
8873            }
8874        );
8875        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8876        assert_eq!(
8877            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8878            vec![running.id.as_str()],
8879            "exactly the parked run resumes - not the unrelated task, even \
8880             though it was offered first"
8881        );
8882
8883        // Tick 5: `running` is now in flight (dispatched from tick 4's
8884        // gate). Only now does the sequence end and ordinary dispatch fully
8885        // resume.
8886        state = advance_interrupt_tick(
8887            true,
8888            state,
8889            std::slice::from_ref(&running.id),
8890            std::slice::from_ref(&other),
8891        );
8892        assert_eq!(state, Interrupt::Idle);
8893        let gated = interrupt_gate(
8894            &state,
8895            std::slice::from_ref(&running.id),
8896            vec![other.clone()],
8897        );
8898        assert_eq!(
8899            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8900            vec![other.id.as_str()],
8901            "ordinary dispatch is unrestricted again"
8902        );
8903    }
8904
8905    #[test]
8906    fn every_run_status_settles_the_task_it_came_from() {
8907        // run status, resulting task status, attempts still standing after one
8908        let table = [
8909            (RunStatus::Merged, TaskStatus::Done, 1),
8910            (RunStatus::Ready, TaskStatus::Done, 1),
8911            (RunStatus::Stalled, TaskStatus::Failed, 0),
8912            (RunStatus::Blocked, TaskStatus::Failed, 1),
8913            (RunStatus::Failed, TaskStatus::Failed, 1),
8914            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8915            (RunStatus::Prep, TaskStatus::Failed, 1),
8916            (RunStatus::Implementing, TaskStatus::Failed, 1),
8917            (RunStatus::Judging, TaskStatus::Failed, 1),
8918            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8919            (RunStatus::Voting, TaskStatus::Failed, 1),
8920            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8921            (RunStatus::Gating, TaskStatus::Failed, 1),
8922        ];
8923        for (run, want, attempts) in table {
8924            let mut t = task();
8925            t.start("20260902-000000-aaaa".to_owned());
8926            settle(
8927                &mut t,
8928                Verdict {
8929                    status: run,
8930                    left_pr: false,
8931                    parked: false,
8932                    quota_hit: matches!(run, RunStatus::Stalled),
8933                    no_viable_candidates: false,
8934                },
8935                "why",
8936                2,
8937            );
8938            assert_eq!(t.status, want, "task status after {}", label(run));
8939            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8940        }
8941    }
8942
8943    #[test]
8944    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8945        let mut stalled = task();
8946        stalled.start("20260902-000000-aaaa".to_owned());
8947        settle(
8948            &mut stalled,
8949            Verdict {
8950                status: RunStatus::Stalled,
8951                left_pr: false,
8952                parked: false,
8953                quota_hit: true,
8954                no_viable_candidates: false,
8955            },
8956            "quota",
8957            1,
8958        );
8959        assert_eq!(stalled.attempts, 0);
8960        assert!(
8961            stalled.status.runnable(),
8962            "a machine problem must leave the task in line"
8963        );
8964
8965        let mut blocked = task();
8966        blocked.start("20260902-000000-aaaa".to_owned());
8967        settle(
8968            &mut blocked,
8969            Verdict {
8970                status: RunStatus::Blocked,
8971                left_pr: false,
8972                parked: false,
8973                quota_hit: false,
8974                no_viable_candidates: false,
8975            },
8976            "findings open",
8977            1,
8978        );
8979        assert_eq!(blocked.attempts, 1);
8980        assert_eq!(
8981            blocked.status,
8982            TaskStatus::Held,
8983            "the last attempt hands the task to a human"
8984        );
8985    }
8986
8987    #[test]
8988    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
8989        // Attempts to spare: without the pull request this task would go
8990        // straight back in line and run the whole competition again.
8991        let mut delivered = task();
8992        delivered.start("20260903-080619-01c2".to_owned());
8993        settle(
8994            &mut delivered,
8995            Verdict {
8996                status: RunStatus::Blocked,
8997                left_pr: true,
8998                parked: false,
8999                quota_hit: false,
9000                no_viable_candidates: false,
9001            },
9002            "no check status",
9003            4,
9004        );
9005        assert_eq!(
9006            delivered.status,
9007            TaskStatus::Held,
9008            "a pull request waiting on CI or a person is not a retryable failure"
9009        );
9010        assert!(
9011            !delivered.status.runnable(),
9012            "the loop must not pick this task up again"
9013        );
9014        assert_eq!(
9015            delivered.last_error.as_deref(),
9016            Some("no check status"),
9017            "the operator needs to be told what the gate was waiting for"
9018        );
9019
9020        // The same status without a pull request is a plain failure, and with
9021        // attempts left it is retried.
9022        let mut empty_handed = task();
9023        empty_handed.start("20260903-080619-01c2".to_owned());
9024        settle(
9025            &mut empty_handed,
9026            Verdict {
9027                status: RunStatus::Blocked,
9028                left_pr: false,
9029                parked: false,
9030                quota_hit: false,
9031                no_viable_candidates: false,
9032            },
9033            "findings open",
9034            4,
9035        );
9036        assert_eq!(empty_handed.status, TaskStatus::Failed);
9037        assert!(empty_handed.status.runnable());
9038    }
9039
9040    #[test]
9041    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
9042        // Every candidate agreed, with evidence, that nothing belonged in the
9043        // worktree. That is not a confirmed success to close automatically -
9044        // a human still has to check the claim - and it is not an ordinary
9045        // failure either, so this settles exactly like a pull request nobody
9046        // merged yet: `Held`, same as `Blocked` with a PR.
9047        let mut noop = task();
9048        noop.start("20260912-131304-391f".to_owned());
9049        settle(
9050            &mut noop,
9051            Verdict {
9052                status: RunStatus::VerifiedNoop,
9053                left_pr: false,
9054                parked: false,
9055                quota_hit: false,
9056                no_viable_candidates: true,
9057            },
9058            "candidate A: already fixed by b32cfc4, on main",
9059            4,
9060        );
9061        assert_eq!(
9062            noop.status,
9063            TaskStatus::Held,
9064            "an unverified claim is a request for a human, not a failure"
9065        );
9066        assert!(
9067            !noop.status.runnable(),
9068            "the loop must not requeue this on the same unverified claim"
9069        );
9070        // `Task::release` resets attempts to zero the moment a human looks at
9071        // the evidence and lets it run again, so it does not matter here
9072        // whether the one attempt already spent stays spent - what matters is
9073        // that nothing retries this task unattended in the meantime.
9074        assert_eq!(noop.attempts, 1);
9075    }
9076
9077    #[test]
9078    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
9079        // Parking is the operator asking for the process back - to replace the
9080        // binary, most of all. The run's work is intact on disk, so this is
9081        // not a failed attempt, and charging for it would mean a few upgrades
9082        // could exhaust a budget meant for agents that misbehaved.
9083        let mut parked = task();
9084        parked.start("20260903-183634-2d98".to_owned());
9085        settle(
9086            &mut parked,
9087            Verdict {
9088                status: RunStatus::Implementing,
9089                left_pr: false,
9090                quota_hit: false,
9091                parked: true,
9092                no_viable_candidates: false,
9093            },
9094            "parked after `implementing`",
9095            2,
9096        );
9097        assert_eq!(parked.attempts, 0, "a park is refunded");
9098        assert!(
9099            parked.status.runnable(),
9100            "and the task stays in line so the next loop resumes its run"
9101        );
9102        assert_eq!(parked.status, TaskStatus::Parked);
9103        assert_eq!(
9104            parked.park_reason.as_deref(),
9105            Some("parked after `implementing`"),
9106            "the card says where it stopped"
9107        );
9108        assert_eq!(parked.last_error, None, "nothing failed");
9109
9110        // Without the park flag the same non-terminal status is what it always
9111        // was: `execute` returning mid-flight, which is a bug and spends an
9112        // attempt so a task cannot loop on it forever.
9113        let mut broken = task();
9114        broken.start("20260903-183634-2d98".to_owned());
9115        settle(
9116            &mut broken,
9117            Verdict {
9118                status: RunStatus::Implementing,
9119                left_pr: false,
9120                quota_hit: false,
9121                parked: false,
9122                no_viable_candidates: false,
9123            },
9124            "returned mid-flight",
9125            2,
9126        );
9127        assert_eq!(broken.attempts, 1);
9128    }
9129
9130    #[test]
9131    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
9132        // Run e633: quorum lost because two judges answered with the wrong
9133        // JSON shape, `quota: []`. Refunding that takes the bound off the
9134        // retry loop, and each retry pays for a fresh hour-long implement
9135        // wave before it can fail the same way.
9136        let mut flaky = task();
9137        flaky.start("20260903-123023-e633".to_owned());
9138        settle(
9139            &mut flaky,
9140            Verdict {
9141                status: RunStatus::Stalled,
9142                left_pr: false,
9143                parked: false,
9144                quota_hit: false,
9145                no_viable_candidates: false,
9146            },
9147            "verdict rests on 1 of 3 judges",
9148            2,
9149        );
9150        assert_eq!(
9151            flaky.attempts, 1,
9152            "flakiness spends an attempt, so `max_attempts` still bounds it"
9153        );
9154        assert!(flaky.status.runnable(), "and it is still worth retrying");
9155
9156        // The same status, lost to a rate limit, is the machine's fault.
9157        let mut limited = task();
9158        limited.start("20260903-123023-e633".to_owned());
9159        settle(
9160            &mut limited,
9161            Verdict {
9162                status: RunStatus::Stalled,
9163                left_pr: false,
9164                parked: false,
9165                quota_hit: true,
9166                no_viable_candidates: false,
9167            },
9168            "judge-2, judge-3 out of quota",
9169            2,
9170        );
9171        assert_eq!(limited.attempts, 0, "a quota window is refunded");
9172        assert!(limited.status.runnable());
9173
9174        // And the bound really binds: a task that keeps stalling on flakiness
9175        // reaches a human instead of running the roster forever.
9176        let mut worn = task();
9177        for _ in 0..2 {
9178            worn.release();
9179        }
9180        worn.start("20260903-123023-e633".to_owned());
9181        worn.attempts = 2;
9182        settle(
9183            &mut worn,
9184            Verdict {
9185                status: RunStatus::Stalled,
9186                left_pr: false,
9187                parked: false,
9188                quota_hit: false,
9189                no_viable_candidates: false,
9190            },
9191            "no quorum again",
9192            2,
9193        );
9194        assert_eq!(worn.status, TaskStatus::Held);
9195        assert!(!worn.status.runnable());
9196    }
9197
9198    #[test]
9199    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
9200        // The implement wave loses every seat to the same rate limit and
9201        // `after_implement` bails with nothing viable, which surfaces as
9202        // `Failed` rather than `Stalled`. That is the same machine fact the
9203        // `Stalled`-quota row already refunds, and must be refunded the same
9204        // way, or a quota outage quietly holds every task it touches instead
9205        // of leaving them in line for the reset.
9206        let mut wiped_out = task();
9207        wiped_out.start("20260907-025000-a1b2".to_owned());
9208        settle(
9209            &mut wiped_out,
9210            Verdict {
9211                status: RunStatus::Failed,
9212                left_pr: false,
9213                parked: false,
9214                quota_hit: true,
9215                no_viable_candidates: true,
9216            },
9217            "no candidate produced a change; nothing to judge",
9218            2,
9219        );
9220        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
9221        assert!(
9222            wiped_out.status.runnable(),
9223            "a machine problem must leave the task in line"
9224        );
9225
9226        // This is the exemption that must stay narrow: a candidate that did
9227        // produce a change, and then failed for some other reason, still
9228        // spends the attempt even though a seat elsewhere hit its quota.
9229        // Otherwise every ordinary failure that happens to share a run with
9230        // an unrelated rate limit would be refunded for free.
9231        let mut partial_progress = task();
9232        partial_progress.start("20260907-025500-c3d4".to_owned());
9233        settle(
9234            &mut partial_progress,
9235            Verdict {
9236                status: RunStatus::Failed,
9237                left_pr: false,
9238                parked: false,
9239                quota_hit: true,
9240                no_viable_candidates: false,
9241            },
9242            "gate failed on the winning candidate",
9243            2,
9244        );
9245        assert_eq!(
9246            partial_progress.attempts, 1,
9247            "a candidate that actually produced a change spends the attempt \
9248             even though some other seat hit its quota"
9249        );
9250        assert!(partial_progress.status.runnable());
9251    }
9252
9253    #[test]
9254    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
9255        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
9256        // disk, and that construction must reach the same conclusion as the
9257        // one `attempt` builds from a live run, or a crash at exactly the
9258        // wrong moment gives a recovered task a different policy than one a
9259        // daemon finished settling itself.
9260        let mut t = task();
9261        t.start("20260907-025000-a1b2".to_owned());
9262        let mut state = run_state(RunStatus::Failed);
9263        state.quota.push(QuotaLoss {
9264            cause: crate::agent::QuotaCause::UsageLimit,
9265            agent: String::new(),
9266            seat: "cand-a".to_owned(),
9267            node: "implement".to_owned(),
9268            at: Timestamp::now(),
9269            reset: None,
9270        });
9271        assert!(
9272            state.viable().is_empty(),
9273            "no candidate was added, so nothing is viable"
9274        );
9275        reclaim(&mut t, Some(state), 2, "en");
9276        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
9277        assert!(t.status.runnable());
9278    }
9279
9280    #[test]
9281    fn a_held_task_is_never_offered_to_the_loop() {
9282        let dir = tempfile::tempdir().unwrap();
9283        let queue = Queue::at(dir.path().to_path_buf());
9284        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
9285            let mut t = task();
9286            t.id = format!("2026090{n}-000000-000{n}");
9287            t.priority = priority;
9288            queue.put(&mut t).unwrap();
9289        }
9290        let mut held = task();
9291        held.id = "20260909-000000-9999".to_owned();
9292        held.priority = 99;
9293        held.hold_machine(None);
9294        queue.put(&mut held).unwrap();
9295
9296        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
9297        assert_eq!(order.len(), 3);
9298        assert!(!order.contains(&held.id));
9299        assert_eq!(
9300            order.first().cloned(),
9301            queue.next_runnable().map(|t| t.id),
9302            "the loop's first candidate is exactly what the queue offers"
9303        );
9304        assert_eq!(
9305            order,
9306            vec![
9307                "20260902-000000-0002".to_owned(),
9308                "20260903-000000-0003".to_owned(),
9309                "20260901-000000-0001".to_owned(),
9310            ],
9311            "priority first, then oldest, so nothing starves"
9312        );
9313    }
9314
9315    #[test]
9316    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9317        let dir = tempfile::tempdir().unwrap();
9318        let queue = Queue::at(dir.path().to_path_buf());
9319        let mut old = task();
9320        old.id = "20260101-000000-old0".to_owned();
9321        queue.put(&mut old).unwrap();
9322        let mut fresh = task();
9323        fresh.id = "20260101-000000-new0".to_owned();
9324        queue.put(&mut fresh).unwrap();
9325
9326        // No parseable pid at all, so age is the only signal there is to
9327        // check - unlike a real `Queue::claim`, which always names a real,
9328        // and therefore alive, pid this test cannot fake as dead.
9329        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9330        std::thread::sleep(Duration::from_millis(60));
9331        let live = queue.claim(&fresh.id).unwrap();
9332
9333        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9334        assert_eq!(swept, vec![old.id.clone()]);
9335        assert!(
9336            queue.claim(&old.id).is_ok(),
9337            "an unparseable lock older than the threshold is swept"
9338        );
9339        assert!(
9340            queue.claim(&fresh.id).is_err(),
9341            "a live pid protects its lock regardless of age"
9342        );
9343        drop(live);
9344    }
9345
9346    #[test]
9347    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9348        // A live worker's claim remains authoritative even beyond the sweep's
9349        // age limit. Sweeping it would permit a second competing attempt.
9350        let dir = tempfile::tempdir().unwrap();
9351        let queue = Queue::at(dir.path().to_path_buf());
9352        let mut t = task();
9353        t.id = "20260101-000000-live".to_owned();
9354        queue.put(&mut t).unwrap();
9355
9356        let claim = queue.claim(&t.id).unwrap();
9357        std::thread::sleep(Duration::from_millis(60));
9358
9359        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9360        assert!(
9361            swept.is_empty(),
9362            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9363        );
9364        assert!(
9365            queue.claim(&t.id).is_err(),
9366            "the lock still protects its task"
9367        );
9368        drop(claim);
9369    }
9370
9371    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
9372    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
9373    fn injected_dead_pid() -> u32 {
9374        std::process::id().checked_add(1).unwrap_or(1)
9375    }
9376
9377    #[test]
9378    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9379        let dir = tempfile::tempdir().unwrap();
9380        let queue = Queue::at(dir.path().to_path_buf());
9381        let mut t = task();
9382        t.id = "20260101-000000-dead".to_owned();
9383        queue.put(&mut t).unwrap();
9384        let dead_pid = injected_dead_pid();
9385
9386        // Written directly rather than through `Queue::claim`, which would
9387        // stamp this test process's own very much alive pid and defeat the
9388        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
9389        // like moments after it died, not six hours later.
9390        std::fs::write(
9391            dir.path().join(format!("{}.lock", t.id)),
9392            dead_pid.to_string(),
9393        )
9394        .unwrap();
9395
9396        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9397            pid != dead_pid
9398        });
9399        assert_eq!(
9400            swept,
9401            vec![t.id.clone()],
9402            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9403        );
9404        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9405    }
9406
9407    #[test]
9408    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9409        let dir = tempfile::tempdir().unwrap();
9410        let queue = Queue::at(dir.path().to_path_buf());
9411        let mut t = task();
9412        t.id = "20260101-000000-late".to_owned();
9413        queue.put(&mut t).unwrap();
9414        let dead_pid = injected_dead_pid();
9415
9416        // Tick one, standing in for the sweep `poll` already runs at
9417        // startup: nothing to find yet.
9418        assert!(
9419            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9420            "nothing has claimed the task yet"
9421        );
9422
9423        // A second daemon claims the task and dies before it ever writes
9424        // `running`, well after this loop's own startup sweep already ran.
9425        std::fs::write(
9426            dir.path().join(format!("{}.lock", t.id)),
9427            dead_pid.to_string(),
9428        )
9429        .unwrap();
9430
9431        // Tick two, standing in for a poll long into this daemon's uptime:
9432        // the same function, called again, notices what only just appeared -
9433        // proving the sweep is not a one-shot startup check.
9434        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9435            pid != dead_pid
9436        });
9437        assert_eq!(swept, vec![t.id.clone()]);
9438    }
9439
9440    #[test]
9441    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9442        // `reclaim_orphaned_running` looks up the task's last run, which
9443        // touches `run::home()`; the first call anywhere in this binary wins,
9444        // so this is a no-op if another test already pinned one, and either
9445        // way the run id below is never written under it.
9446        crate::run::pin_test_home();
9447        let dir = tempfile::tempdir().unwrap();
9448        let queue = Queue::at(dir.path().to_path_buf());
9449        let mut t = task();
9450        t.id = "20260101-000000-crsh".to_owned();
9451        t.status = TaskStatus::Running;
9452        t.attempts = 1;
9453        // No `run.json` behind this id: standing in for a run this test does
9454        // not need to make readable, since the point is the lock, not the
9455        // recovery table `reclaim` already has its own tests for.
9456        t.runs.push("20260904-000000-4043".to_owned());
9457        queue.put(&mut t).unwrap();
9458        let dead_pid = injected_dead_pid();
9459
9460        // The crashed daemon's own claim, naming a pid nothing on the
9461        // machine holds anymore.
9462        std::fs::write(
9463            dir.path().join(format!("{}.lock", t.id)),
9464            dead_pid.to_string(),
9465        )
9466        .unwrap();
9467
9468        // Before the lock is swept the task looks claimed, and
9469        // `reclaim_orphaned_running` must leave it alone - this is exactly
9470        // the bug: a `running` task stranded behind a dead daemon's lock,
9471        // invisible to the claim-as-proof check because the lock outlived
9472        // the process that wrote it.
9473        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9474        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9475
9476        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9477            pid != dead_pid
9478        });
9479        assert_eq!(swept, vec![t.id.clone()]);
9480
9481        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9482        assert_eq!(reclaimed, vec![t.id.clone()]);
9483        let after = queue.get(&t.id).unwrap();
9484        assert_eq!(
9485            after.status,
9486            TaskStatus::Held,
9487            "no run.json to recover from, so a human is asked"
9488        );
9489        assert_eq!(
9490            after.runs,
9491            vec!["20260904-000000-4043".to_owned()],
9492            "the crashed run's id is kept as evidence, not discarded"
9493        );
9494    }
9495
9496    #[test]
9497    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9498        let dir = tempfile::tempdir().unwrap();
9499        let queue = Queue::at(dir.path().to_path_buf());
9500        let mut t = task();
9501        t.id = "20260101-000000-unknown".to_owned();
9502        queue.put(&mut t).unwrap();
9503        let dead_pid = injected_dead_pid();
9504        std::fs::write(
9505            dir.path().join(format!("{}.lock", t.id)),
9506            dead_pid.to_string(),
9507        )
9508        .unwrap();
9509
9510        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9511        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9512        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9513    }
9514
9515    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9516        let mut s = run_state(status);
9517        s.config.graph.language = language.to_owned();
9518        s
9519    }
9520
9521    fn unstarted_verdict(status: RunStatus) -> Verdict {
9522        Verdict {
9523            status,
9524            left_pr: false,
9525            quota_hit: false,
9526            parked: false,
9527            no_viable_candidates: false,
9528        }
9529    }
9530
9531    #[test]
9532    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9533        let mut t = task();
9534        t.attempts = 1;
9535        settle_in(
9536            &mut t,
9537            unstarted_verdict(RunStatus::AlreadyInBase),
9538            "already in main",
9539            1,
9540            phrases("en"),
9541            None,
9542        );
9543        assert_eq!(t.status, TaskStatus::Done);
9544        assert_eq!(t.attempts, 0);
9545    }
9546
9547    #[test]
9548    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9549        let reason = |language: &str| {
9550            let mut t = task();
9551            settle_in(
9552                &mut t,
9553                unstarted_verdict(RunStatus::Judging),
9554                "boom",
9555                1,
9556                phrases(language),
9557                None,
9558            );
9559            t.last_error.or(t.hold_reason).unwrap_or_default()
9560        };
9561        assert!(
9562            reason("en").starts_with("the graph stopped at `"),
9563            "{}",
9564            reason("en")
9565        );
9566        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9567        assert!(reason("日本語").contains("boom"));
9568        assert_eq!(reason("fr"), reason("en"));
9569    }
9570
9571    #[test]
9572    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9573        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9574        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9575        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9576        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9577        assert!(ja.contains("[run "), "{ja}");
9578        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9579        assert!(ended.starts_with("run 終了: "), "{ended}");
9580        let mut de = run_state_in(RunStatus::Failed, "de");
9581        let mut en = run_state_in(RunStatus::Failed, "en");
9582        de.id = "same".to_owned();
9583        en.id = "same".to_owned();
9584        assert_eq!(describe(&de), describe(&en));
9585    }
9586
9587    #[test]
9588    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9589        use crate::handover::Refused;
9590        let cases = [
9591            Refused::Foreign {
9592                branch: "b".into(),
9593                path: "/w/x".into(),
9594                why: "made by hand".into(),
9595            },
9596            Refused::Unsafe {
9597                branch: "b".into(),
9598                path: "/w/x".into(),
9599                why: "its worktree has uncommitted changes (a.rs)".into(),
9600            },
9601            Refused::ReleaseFailed {
9602                branch: "b".into(),
9603                path: "/w/x".into(),
9604                run: "ab12".into(),
9605            },
9606        ];
9607        for r in &cases {
9608            let en = (phrases("en").handover_refused)(r);
9609            assert_eq!(en, r.to_string());
9610            let ja = (phrases("ja").handover_refused)(r);
9611            assert!(
9612                !ja.contains("is checked out") && !ja.contains("try again"),
9613                "{ja}"
9614            );
9615            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9616            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9617                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9618            }
9619        }
9620        assert!(phrases("en").handover_hint.contains("release the task"));
9621        assert!(phrases("ja").handover_hint.contains("解放"));
9622    }
9623
9624    #[test]
9625    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9626        let build = |lang: &str| {
9627            let mut s = run_state_in(RunStatus::Blocked, lang);
9628            s.id = "same".to_owned();
9629            s.config.graph.review_rounds = 3;
9630            let mut r = review_round(3);
9631            r.expected = 3;
9632            r.answered = 1;
9633            s.reviews.push(r);
9634            s.event(
9635                "review",
9636                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9637            );
9638            s
9639        };
9640        let en = describe(&build("en"));
9641        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9642        let ja = describe(&build("ja"));
9643        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9644        assert!(!ja.contains("never answered"), "{ja}");
9645        assert!(ja.contains("[run "), "{ja}");
9646
9647        // An incomplete panel whose verification failed is a different stop:
9648        // the real event must survive in ja too.
9649        let mut failed = build("ja");
9650        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9651            command: "cargo test".to_owned(),
9652            code: Some(1),
9653            output_tail: String::new(),
9654            duration_ms: 0,
9655            resource_blocked: false,
9656            ..Default::default()
9657        });
9658        failed.event("review", "stopped; e2e failed: cargo test");
9659        let ja = describe(&failed);
9660        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9661        assert!(!ja.contains("席のレビュアー"), "{ja}");
9662    }
9663
9664    #[test]
9665    fn refusals_and_recovery_prose_follow_the_language() {
9666        let home = crate::run::test_home();
9667        let t = held_task_with("r1");
9668        let q = action_question(
9669            "r1",
9670            ask::ChoiceAction::Resume {
9671                run: "r1".to_owned(),
9672            },
9673        );
9674        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9675            ActionDecision::Refuse(s) => s,
9676            other => panic!("{other:?}"),
9677        };
9678        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9679        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9680        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9681
9682        let mut held = task();
9683        reclaim(&mut held, None, 2, "ja");
9684        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9685        let mut held = task();
9686        reclaim(&mut held, None, 2, "xx");
9687        assert!(held.hold_reason.unwrap().contains("held for a human"));
9688    }
9689
9690    fn run_state(status: RunStatus) -> RunState {
9691        let mut state = RunState::new(
9692            PathBuf::from("/repo"),
9693            "main".to_owned(),
9694            "abc1234def".to_owned(),
9695            "add retries".to_owned(),
9696            Config::default(),
9697        );
9698        state.status = status;
9699        state
9700    }
9701
9702    #[test]
9703    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9704        crate::run::pin_test_home();
9705        let dir = tempfile::tempdir().unwrap();
9706        let mut state = run_state(RunStatus::Blocked);
9707        state.id = "20260101-000000-audit".into();
9708        state.save_under(dir.path()).unwrap();
9709        let mut t = task();
9710        t.start(state.id.clone());
9711        // The final state is newer than disk, as when a worker settles its
9712        // in-memory outcome or recovery is passed an already loaded run.
9713        state.status = RunStatus::Ready;
9714        settle_and_diagnose(
9715            &mut t,
9716            unstarted_verdict(RunStatus::Ready),
9717            "Verified local delivery",
9718            2,
9719            &state,
9720        );
9721        let completion = t.completion_history.last().unwrap();
9722        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9723        assert_eq!(completion.prior_status, TaskStatus::Running);
9724        assert_eq!(
9725            completion.reason.as_deref(),
9726            Some("Verified local delivery")
9727        );
9728        let snapshot = completion.run.as_ref().unwrap();
9729        assert_eq!(snapshot.id, state.id);
9730        assert_eq!(snapshot.status, Some(RunStatus::Ready));
9731        assert_eq!(
9732            RunState::load_under(&state.id, dir.path()).unwrap().status,
9733            RunStatus::Blocked,
9734            "settlement records the actual outcome without rewriting run history"
9735        );
9736    }
9737
9738    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9739        Candidate {
9740            index: 0,
9741            label,
9742            agent: "claude".to_owned(),
9743            branch: format!("magi/x/{label}"),
9744            worktree: PathBuf::from("/repo"),
9745            summary: summary.to_owned(),
9746            stat: String::new(),
9747            files: 0,
9748            commits: usize::from(!empty),
9749            empty,
9750            failed: failed.map(str::to_owned),
9751            verified_noop: None,
9752            duration_ms: 0,
9753            folded: false,
9754        }
9755    }
9756
9757    #[test]
9758    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9759        let mut state = run_state(RunStatus::Blocked);
9760        state.gate = vec![
9761            CommandOutcome {
9762                command: "cargo make check".to_owned(),
9763                code: Some(0),
9764                output_tail: "ok".to_owned(),
9765                duration_ms: 0,
9766                resource_blocked: false,
9767                ..Default::default()
9768            },
9769            CommandOutcome {
9770                command: "cargo test".to_owned(),
9771                code: Some(101),
9772                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9773                duration_ms: 0,
9774                resource_blocked: false,
9775                ..Default::default()
9776            },
9777        ];
9778        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9779        assert!(d.contains("cargo test"), "{d}");
9780        assert!(
9781            !d.contains("cargo make check"),
9782            "a passing check is not a diagnostic: {d}"
9783        );
9784        assert!(d.contains("assertion failed"), "{d}");
9785    }
9786
9787    #[test]
9788    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9789        let mut state = run_state(RunStatus::Blocked);
9790        state.event(
9791            "land",
9792            "stopped: the fixer produced no commit while 2 check(s) were failing \
9793             (build, lint); stopping instead of looping on an unchanged tree",
9794        );
9795        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9796        assert!(d.contains("build"), "{d}");
9797        assert!(d.contains("lint"), "{d}");
9798        assert!(d.contains("fixer produced no commit"), "{d}");
9799    }
9800
9801    #[test]
9802    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9803        // `describe`'s output becomes `Task::last_error` verbatim, and the
9804        // phone renders that in the same alarm-styled box an ordinary
9805        // failure gets. A bare `verified_noop` there would read exactly like
9806        // the failure this status exists to be told apart from.
9807        let state = run_state(RunStatus::VerifiedNoop);
9808        let d = describe(&state);
9809        assert!(
9810            d.contains("agent-verified no-op"),
9811            "expected the display label, not the wire spelling: {d}"
9812        );
9813        assert!(!d.contains("verified_noop"), "{d}");
9814    }
9815
9816    #[test]
9817    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9818        let mut state = run_state(RunStatus::Failed);
9819        state.gate.push(crate::run::CommandOutcome {
9820            command: "cargo test".into(),
9821            code: Some(101),
9822            output_tail: format!(
9823                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9824                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9825            ),
9826            duration_ms: 1,
9827            resource_blocked: false,
9828            ..Default::default()
9829        });
9830        let d = diagnostic(&state).unwrap();
9831        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9832        assert!(d.contains("assertion failed: widget missing"));
9833        assert!(d.contains("widget log"));
9834    }
9835
9836    #[test]
9837    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9838        // The whole point of the feature: a run held as "no candidate produced
9839        // a change" can mean the implementer actually finished the task and
9840        // only left a clean local tree behind - see AGENTS.md on this exact
9841        // failure mode. The diagnostic has to carry what the agent actually
9842        // said, not just the fact that nothing was there to judge.
9843        let mut state = run_state(RunStatus::Failed);
9844        state.candidates = vec![candidate(
9845            'A',
9846            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9847            true,
9848            None,
9849        )];
9850        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9851        assert!(d.contains("candidate A"), "{d}");
9852        assert!(d.contains("tagged v1.2.3"), "{d}");
9853    }
9854
9855    #[test]
9856    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9857        let mut state = run_state(RunStatus::Failed);
9858        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9859        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9860        assert!(d.contains("candidate A"), "{d}");
9861        assert!(d.contains("agent timed out"), "{d}");
9862    }
9863
9864    #[test]
9865    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9866        // A viable candidate existed, the gate never ran, and nothing land
9867        // said matches - `Task::last_error` is left to explain this one alone.
9868        let mut state = run_state(RunStatus::Failed);
9869        state.candidates = vec![candidate('A', "did the work", false, None)];
9870        assert!(diagnostic(&state).is_none());
9871    }
9872
9873    #[test]
9874    fn diagnostic_is_bounded_however_much_a_run_printed() {
9875        let mut state = run_state(RunStatus::Blocked);
9876        state.gate = vec![
9877            CommandOutcome {
9878                command: "cargo test".to_owned(),
9879                code: Some(101),
9880                output_tail: "x".repeat(50_000),
9881                duration_ms: 0,
9882                resource_blocked: false,
9883                ..Default::default()
9884            },
9885            CommandOutcome {
9886                command: "cargo clippy".to_owned(),
9887                code: Some(1),
9888                output_tail: "y".repeat(50_000),
9889                duration_ms: 0,
9890                resource_blocked: false,
9891                ..Default::default()
9892            },
9893        ];
9894        state.candidates = vec![
9895            candidate('A', &"z".repeat(50_000), true, None),
9896            candidate('B', &"w".repeat(50_000), true, None),
9897        ];
9898        let d = diagnostic(&state).expect("plenty here to diagnose");
9899        assert!(
9900            d.len() <= DIAGNOSTIC_MAX,
9901            "diagnostic grew to {} bytes, unbounded",
9902            d.len()
9903        );
9904    }
9905
9906    #[test]
9907    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9908        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9909            let mut t = task();
9910            let mut state = run_state(status);
9911            t.pr_recovery = Some(crate::pr_recovery::Selection {
9912                url: "url".into(),
9913                branch: format!("magi/task-{}", t.id),
9914                head: "a".repeat(40),
9915                source_head: None,
9916                source_run: None,
9917                source_proof: None,
9918                disposition: Some(crate::pr_recovery::Disposition::Land),
9919                instruction: t.instruction.clone(),
9920                approved_at: Timestamp::now(),
9921            });
9922            state.pr_recovery = t.pr_recovery.clone();
9923            t.start(state.id.clone());
9924            settle_and_diagnose(
9925                &mut t,
9926                Verdict {
9927                    status,
9928                    left_pr: false,
9929                    quota_hit: false,
9930                    parked: false,
9931                    no_viable_candidates: false,
9932                },
9933                "delivery stopped",
9934                5,
9935                &state,
9936            );
9937            assert_eq!(t.status, TaskStatus::Held);
9938            let reason = t.hold_reason.as_deref().unwrap();
9939            if status == RunStatus::Ready {
9940                assert!(reason.contains("Selected PR delivery is incomplete"));
9941                assert!(t.recovery_budget.is_none());
9942            } else {
9943                assert!(reason.contains("Selected recovery stopped"));
9944                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9945            }
9946            assert!(t.pr_recovery.is_some());
9947        }
9948    }
9949
9950    #[test]
9951    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9952        let mut state = run_state(RunStatus::Voting);
9953        state.base_sync = Some(crate::run::BaseSync {
9954            tip: "base-tip".into(),
9955            behind: 3,
9956            attempts: 4,
9957            conflict: Some("base stopped".into()),
9958            already_in: None,
9959        });
9960        state.record_base_sync_stop("candidate-head");
9961        let mut t = task();
9962        t.start(state.id.clone());
9963        let verdict = Verdict {
9964            status: RunStatus::Blocked,
9965            left_pr: false,
9966            quota_hit: false,
9967            parked: false,
9968            no_viable_candidates: false,
9969        };
9970        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9971        assert_eq!(
9972            t.status,
9973            TaskStatus::Held,
9974            "unspent task attempts cannot start another competition"
9975        );
9976        let at = t.held_at;
9977        let cause = t.hold_notice_cause.clone();
9978        state.begin_pass();
9979        t.release_operator("test-resume", None);
9980        t.start(state.id.clone());
9981        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9982        assert_eq!(t.status, TaskStatus::Held);
9983        assert_eq!(t.held_at, at);
9984        assert_eq!(t.hold_notice_cause, cause);
9985    }
9986
9987    #[test]
9988    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
9989        let mut state = run_state(RunStatus::Blocked);
9990        state.gate = vec![CommandOutcome {
9991            command: "cargo test".to_owned(),
9992            code: Some(101),
9993            output_tail: "assertion failed".to_owned(),
9994            duration_ms: 0,
9995            resource_blocked: false,
9996            ..Default::default()
9997        }];
9998        let verdict = Verdict {
9999            status: RunStatus::Blocked,
10000            left_pr: false,
10001            quota_hit: false,
10002            parked: false,
10003            no_viable_candidates: false,
10004        };
10005
10006        // Attempt one of two still has a retry coming: no diagnostic yet, the
10007        // task is going to run again and this run's evidence would go stale.
10008        let mut t = task();
10009        t.start("run-1".to_owned());
10010        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
10011        assert_eq!(t.status, TaskStatus::Failed);
10012        assert!(t.diagnostic.is_none());
10013
10014        // Attempt two exhausts the budget: now it is held, and the
10015        // diagnostic is what `magi task show` has to say more than one line.
10016        t.start("run-2".to_owned());
10017        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
10018        assert_eq!(t.status, TaskStatus::Held);
10019        let d = t.diagnostic.expect("a held task must carry its diagnostic");
10020        assert!(d.contains("cargo test"), "{d}");
10021    }
10022
10023    fn verified_noop_run_state() -> RunState {
10024        let mut state = run_state(RunStatus::VerifiedNoop);
10025        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":[]}"#;
10026        let mut c = candidate('A', summary, true, None);
10027        c.verified_noop = Some(summary.to_owned());
10028        state.candidates = vec![c];
10029        state
10030    }
10031
10032    #[test]
10033    fn a_held_task_names_the_open_question_it_is_waiting_on() {
10034        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
10035        // `magi ask` question settled Held with `hold_reason: null`, so the
10036        // notification said nothing actionable. `note_open_question` should
10037        // append the question id to whatever `handed_off` already wrote.
10038        crate::run::pin_test_home();
10039        let home = crate::run::home();
10040        let state = verified_noop_run_state();
10041        let mut q = ask::Question::new(
10042            state.id.clone(),
10043            "implement".to_owned(),
10044            "impl-A".to_owned(),
10045            "is this really a no-op?".to_owned(),
10046            String::new(),
10047            Vec::new(),
10048        );
10049        Questions::at(home.join("questions")).put(&mut q).unwrap();
10050
10051        let verdict = Verdict {
10052            status: RunStatus::VerifiedNoop,
10053            left_pr: false,
10054            quota_hit: false,
10055            parked: false,
10056            no_viable_candidates: true,
10057        };
10058        let mut t = task();
10059        t.start(state.id.clone());
10060        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
10061
10062        assert_eq!(t.status, TaskStatus::Held);
10063        let reason = t.hold_reason.expect("a held task must record why");
10064        assert!(
10065            reason.starts_with("run ended agent-verified no-op"),
10066            "the original settle reason must survive unchanged: {reason}"
10067        );
10068        assert!(
10069            reason.contains(q.short()),
10070            "the open question's id must be named so the notice is actionable: {reason}"
10071        );
10072    }
10073
10074    #[test]
10075    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
10076        crate::run::pin_test_home();
10077        let state = verified_noop_run_state();
10078
10079        let verdict = Verdict {
10080            status: RunStatus::VerifiedNoop,
10081            left_pr: false,
10082            quota_hit: false,
10083            parked: false,
10084            no_viable_candidates: true,
10085        };
10086        let mut t = task();
10087        t.start(state.id.clone());
10088        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
10089
10090        assert_eq!(t.status, TaskStatus::Held);
10091        assert_eq!(
10092            t.hold_reason.as_deref(),
10093            Some("run ended agent-verified no-op"),
10094            "nothing to append when the question was already answered or never asked"
10095        );
10096    }
10097
10098    #[test]
10099    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
10100        crate::run::pin_test_home();
10101
10102        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
10103        // regression prose instead of valid structured evidence.
10104        let mut bad = run_state(RunStatus::VerifiedNoop);
10105        let mut c = candidate(
10106            'A',
10107            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
10108            true,
10109            None,
10110        );
10111        c.verified_noop = Some("Not established.".to_owned());
10112        bad.candidates = vec![c];
10113
10114        let mut t = task();
10115        t.start(bad.id.clone());
10116        let verdict = Verdict {
10117            status: RunStatus::VerifiedNoop,
10118            left_pr: false,
10119            quota_hit: true,
10120            parked: false,
10121            no_viable_candidates: true,
10122        };
10123        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
10124        assert_eq!(
10125            t.status,
10126            TaskStatus::Failed,
10127            "inconsistent verified_noop must retry as Failed when attempts remain"
10128        );
10129        assert_eq!(t.attempts, 1);
10130        assert_eq!(
10131            t.last_error.as_deref(),
10132            Some("no-change result lacks verified evidence")
10133        );
10134        assert!(t.hold_reason.is_none());
10135
10136        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
10137        // attempts exhausted holds as `failed`, never `verified_noop`, and
10138        // never auto-closes to `Done`.
10139        let mut t_exhausted = task();
10140        t_exhausted.start(bad.id.clone());
10141        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
10142        assert_eq!(t_exhausted.status, TaskStatus::Held);
10143        assert_eq!(t_exhausted.attempts, 1);
10144        assert_eq!(
10145            t_exhausted
10146                .hold_notice_cause
10147                .as_ref()
10148                .map(|c| c.stage.as_str()),
10149            Some("failed"),
10150            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
10151        );
10152        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
10153        assert!(
10154            !diag.contains("agent-verified no-op"),
10155            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
10156        );
10157        assert!(diag.contains("Not established"), "{diag}");
10158    }
10159
10160    #[test]
10161    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
10162        let mut state = verified_noop_run_state();
10163        let summary = state.candidates[0].summary.clone();
10164        state.candidates[0].summary = "Already satisfied.".to_owned();
10165        assert!(state.all_candidates_verified_noop());
10166
10167        state.candidates[0].summary = summary;
10168        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
10169        assert!(!state.all_candidates_verified_noop());
10170    }
10171
10172    #[test]
10173    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
10174        crate::run::pin_test_home();
10175        let mut first = run_state(RunStatus::Blocked);
10176        first.id = "20260101-000000-sup1".to_owned();
10177        first.save().unwrap();
10178        let mut second = run_state(RunStatus::Merged);
10179        second.id = "20260101-000000-sup2".to_owned();
10180        second.save().unwrap();
10181
10182        let mut t = task();
10183        t.runs = vec![first.id.clone(), second.id.clone()];
10184        t.status = TaskStatus::Done;
10185
10186        supersede_prior_runs(&t, &crate::run::home());
10187
10188        assert_eq!(
10189            RunState::load(&first.id).unwrap().status,
10190            RunStatus::Superseded,
10191            "the first attempt's Blocked no longer needs anyone's attention"
10192        );
10193        assert_eq!(
10194            RunState::load(&second.id).unwrap().status,
10195            RunStatus::Merged,
10196            "the run that actually succeeded is left exactly as it was"
10197        );
10198    }
10199
10200    #[test]
10201    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
10202        // `is_working_on` alone only proves a *daemon* claim; a `magi run
10203        // --resume` invoked by hand outside the daemon never touches
10204        // `daemon.json` at all, so it would look identical to a genuinely
10205        // idle run without also consulting `RunState::liveness`, which reads
10206        // this run's own recorded `driver_pid` instead.
10207        crate::run::pin_test_home();
10208        let mut first = run_state(RunStatus::Blocked);
10209        first.id = "20260101-000000-sup9".to_owned();
10210        // This test process's own pid: guaranteed alive without needing a
10211        // real second process or daemon.
10212        first.driver_pid = Some(std::process::id());
10213        first.driver_started_at = Some(
10214            crate::proc::process_started_at(std::process::id())
10215                .expect("this test process's own start time must be queryable"),
10216        );
10217        first.save().unwrap();
10218        let mut second = run_state(RunStatus::Merged);
10219        second.id = "20260101-000000-supa".to_owned();
10220        second.save().unwrap();
10221
10222        let mut t = task();
10223        t.runs = vec![first.id.clone(), second.id.clone()];
10224        t.status = TaskStatus::Done;
10225
10226        supersede_prior_runs(&t, &crate::run::home());
10227
10228        assert_eq!(
10229            RunState::load(&first.id).unwrap().status,
10230            RunStatus::Blocked,
10231            "a live driver_pid means something is still actually working this run, \
10232             even though no daemon claims it - rewriting under it would just be \
10233             undone the next time that process saves"
10234        );
10235    }
10236
10237    #[test]
10238    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
10239        // The first resweep must skip a still-live attempt exactly like
10240        // `supersede_prior_runs` itself does; a later resweep, once that
10241        // process is no longer actually driving it, is what closes the gap
10242        // `supersede_prior_runs` alone leaves - a task only ever reaches
10243        // `Done` once, so nothing else would ever look at this run again.
10244        let dir = tempfile::tempdir().unwrap();
10245        let home = dir.path().to_path_buf();
10246        let queue = Queue::at(dir.path().join("queue"));
10247
10248        let mut first = run_state(RunStatus::Blocked);
10249        first.id = "20260101-000000-supd".to_owned();
10250        first.driver_pid = Some(std::process::id());
10251        first.driver_started_at = Some(
10252            crate::proc::process_started_at(std::process::id())
10253                .expect("this test process's own start time must be queryable"),
10254        );
10255        first.save_under(&home).unwrap();
10256        let mut second = run_state(RunStatus::Merged);
10257        second.id = "20260101-000000-supe".to_owned();
10258        second.save_under(&home).unwrap();
10259
10260        let mut t = task();
10261        t.runs = vec![first.id.clone(), second.id.clone()];
10262        t.status = TaskStatus::Done;
10263        queue.put(&mut t).unwrap();
10264
10265        resweep_superseded_attempts(&queue, &home);
10266        assert_eq!(
10267            RunState::load_under(&first.id, &home).unwrap().status,
10268            RunStatus::Blocked,
10269            "still live on the first pass, so still untouched"
10270        );
10271
10272        // Stand in for the manual process no longer being the one driving
10273        // this run: same pid (this test process really is still alive), but
10274        // an identity marker that no longer matches it - see
10275        // `RunState::liveness`'s own doc for why a mismatched
10276        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
10277        let mut stale = RunState::load_under(&first.id, &home).unwrap();
10278        stale.driver_started_at = Some("1".to_owned());
10279        stale.save_under(&home).unwrap();
10280
10281        resweep_superseded_attempts(&queue, &home);
10282        assert_eq!(
10283            RunState::load_under(&first.id, &home).unwrap().status,
10284            RunStatus::Superseded,
10285            "the second pass catches up what the first one correctly skipped"
10286        );
10287    }
10288
10289    #[test]
10290    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
10291        crate::run::pin_test_home();
10292        let mut first = run_state(RunStatus::Blocked);
10293        first.id = "20260101-000000-sup3".to_owned();
10294        first.save().unwrap();
10295        let mut second = run_state(RunStatus::Blocked);
10296        second.id = "20260101-000000-sup4".to_owned();
10297        second.save().unwrap();
10298
10299        let mut t = task();
10300        t.runs = vec![first.id.clone(), second.id.clone()];
10301        // Still retrying: nothing about this task's story is settled yet, so
10302        // neither Blocked run may be relabelled, even though a later attempt
10303        // already exists.
10304        t.status = TaskStatus::Failed;
10305
10306        supersede_prior_runs(&t, &crate::run::home());
10307
10308        assert_eq!(
10309            RunState::load(&first.id).unwrap().status,
10310            RunStatus::Blocked
10311        );
10312        assert_eq!(
10313            RunState::load(&second.id).unwrap().status,
10314            RunStatus::Blocked
10315        );
10316    }
10317
10318    #[test]
10319    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
10320        // `magi task done` (or the API's equivalent) can close a task with no
10321        // run of its own ever having succeeded - there is nothing here that
10322        // counts as "the attempt that finished it", so nothing is rewritten.
10323        crate::run::pin_test_home();
10324        let mut first = run_state(RunStatus::Blocked);
10325        first.id = "20260101-000000-sup5".to_owned();
10326        first.save().unwrap();
10327
10328        let mut t = task();
10329        t.runs = vec![first.id.clone()];
10330        t.status = TaskStatus::Done;
10331
10332        supersede_prior_runs(&t, &crate::run::home());
10333
10334        assert_eq!(
10335            RunState::load(&first.id).unwrap().status,
10336            RunStatus::Blocked,
10337            "a single-attempt task has no earlier run to supersede"
10338        );
10339    }
10340
10341    #[test]
10342    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
10343        for status in [
10344            RunStatus::Blocked,
10345            RunStatus::Stalled,
10346            RunStatus::Failed,
10347            RunStatus::Ready,
10348            RunStatus::Merged,
10349        ] {
10350            let dir = tempfile::tempdir().unwrap();
10351            let home = dir.path();
10352            let mut first = run_state(RunStatus::Blocked);
10353            first.id = "20260101-000000-supb".to_owned();
10354            first.save_under(home).unwrap();
10355            let mut second = run_state(status);
10356            second.id = "20260101-000000-supc".to_owned();
10357            second.save_under(home).unwrap();
10358
10359            let mut t = task();
10360            t.runs = vec![first.id.clone(), second.id.clone()];
10361            t.hold_manual(Some("Unmerged work remains".into()));
10362            let mut context = CompletionContext::new(
10363                CompletionActor::Cli,
10364                Some("Discard the unmerged attempts".into()),
10365                home,
10366                &t,
10367            );
10368            context.discard = true;
10369            t.succeed(context);
10370            assert_eq!(t.completion_history.len(), 1);
10371
10372            supersede_prior_runs(&t, home);
10373
10374            assert_eq!(
10375                RunState::load_under(&first.id, home).unwrap().status,
10376                RunStatus::Blocked,
10377                "an audited manual close is not proof the earlier work landed"
10378            );
10379            assert_eq!(
10380                RunState::load_under(&second.id, home).unwrap().status,
10381                status,
10382                "the latest attempt retains its actual outcome"
10383            );
10384        }
10385    }
10386
10387    #[test]
10388    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10389        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
10390        // to look" - `Failed` and `VerifiedNoop` are already their own
10391        // terminal answers and must not be relabelled into a third one.
10392        crate::run::pin_test_home();
10393        let mut failed = run_state(RunStatus::Failed);
10394        failed.id = "20260101-000000-sup6".to_owned();
10395        failed.save().unwrap();
10396        let mut noop = run_state(RunStatus::VerifiedNoop);
10397        noop.id = "20260101-000000-sup7".to_owned();
10398        noop.save().unwrap();
10399        let mut winner = run_state(RunStatus::Ready);
10400        winner.id = "20260101-000000-sup8".to_owned();
10401        winner.save().unwrap();
10402
10403        let mut t = task();
10404        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10405        t.status = TaskStatus::Done;
10406
10407        supersede_prior_runs(&t, &crate::run::home());
10408
10409        assert_eq!(
10410            RunState::load(&failed.id).unwrap().status,
10411            RunStatus::Failed
10412        );
10413        assert_eq!(
10414            RunState::load(&noop.id).unwrap().status,
10415            RunStatus::VerifiedNoop
10416        );
10417    }
10418
10419    fn approval_question(run: &str) -> ask::Question {
10420        ask::Question::new(
10421            run.to_owned(),
10422            land::APPROVAL_NODE.to_owned(),
10423            "land".to_owned(),
10424            "merge?".to_owned(),
10425            String::new(),
10426            vec!["merge".to_owned(), "hold".to_owned()],
10427        )
10428    }
10429
10430    #[test]
10431    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10432        crate::run::pin_test_home();
10433        let mut state = run_state(RunStatus::Landing);
10434        state.id = "20260101-000000-fre1".to_owned();
10435        state.parked = true;
10436        state.save().unwrap();
10437        ask::Questions::open()
10438            .put(&mut approval_question(&state.id))
10439            .unwrap();
10440
10441        let mut t = task();
10442        t.runs.push(state.id.clone());
10443        assert_eq!(
10444            land_resume_state(&t),
10445            LandResume::StillWaiting,
10446            "nobody has answered and the timeout has not passed"
10447        );
10448    }
10449
10450    #[test]
10451    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10452        crate::run::pin_test_home();
10453        let mut state = run_state(RunStatus::Gating);
10454        state.id = "20260101-000000-gt01".to_owned();
10455        state.parked = true;
10456        state.config.graph.answer_timeout = 60;
10457        state.github_text = Some(crate::run::GithubTextAsk {
10458            rewrite: None,
10459            fingerprint: "f".into(),
10460            title: true,
10461            body: false,
10462            categories: vec!["title-language".into()],
10463            question: None,
10464            asks: 1,
10465            resolved: false,
10466            chosen_title: None,
10467            choice: None,
10468            publication: None,
10469        });
10470        state.save().unwrap();
10471        let store = ask::Questions::open();
10472        let mut q = ask::Question::new(
10473            state.id.clone(),
10474            crate::github_text::ASK_NODE.to_owned(),
10475            crate::github_text::ASK_SEAT.to_owned(),
10476            "s".into(),
10477            String::new(),
10478            vec!["use fallback".into()],
10479        );
10480        store.put(&mut q).unwrap();
10481        let mut t = task();
10482        t.runs.push(state.id.clone());
10483        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10484        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10485        store.put(&mut q).unwrap();
10486        assert_eq!(land_resume_state(&t), LandResume::Ready);
10487        assert!(!store.get(&q.id).unwrap().status.open());
10488        // Once decided, a parked run is an ordinary candidate again.
10489        state.github_text.as_mut().unwrap().resolved = true;
10490        state.save().unwrap();
10491        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10492    }
10493
10494    #[test]
10495    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10496        // `ask::ask_and_wait`'s own deadline used to retire a question
10497        // nobody answered; land's approval bypasses that wait (see
10498        // `land::approval_gate`), so this is now the only place
10499        // `graph.answer_timeout` is enforced for a land approval at all.
10500        crate::run::pin_test_home();
10501        let mut state = run_state(RunStatus::Landing);
10502        state.id = "20260101-000000-exp1".to_owned();
10503        state.parked = true;
10504        state.config.graph.answer_timeout = 60;
10505        state.save().unwrap();
10506
10507        let store = ask::Questions::open();
10508        let mut q = approval_question(&state.id);
10509        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10510        store.put(&mut q).unwrap();
10511
10512        let mut t = task();
10513        t.runs.push(state.id.clone());
10514        assert_eq!(
10515            land_resume_state(&t),
10516            LandResume::Ready,
10517            "an expired question must not be waited on forever"
10518        );
10519
10520        let after = store.get(&q.id).unwrap();
10521        assert!(
10522            !after.status.open(),
10523            "the question is abandoned, not silently ignored"
10524        );
10525        assert!(
10526            after.resolution().is_none(),
10527            "an abandoned question is not read as a decision"
10528        );
10529    }
10530
10531    #[test]
10532    fn reclaim_settles_a_running_task_against_its_last_run() {
10533        let mut t = task();
10534        t.start("20260904-000000-4043".to_owned());
10535        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10536        assert_eq!(
10537            t.status,
10538            TaskStatus::Done,
10539            "a run that actually finished must not stay `running` forever"
10540        );
10541    }
10542
10543    #[test]
10544    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10545        let dir = tempfile::tempdir().unwrap();
10546        let queue = Queue::at(dir.path().join("queue"));
10547        let mut task = task();
10548        let mut run = run_state(RunStatus::Blocked);
10549        run.reserve_under(dir.path()).unwrap();
10550        run.driver_exited = true;
10551        run.save_under(dir.path()).unwrap();
10552        queue.put(&mut task).unwrap();
10553        let stale = task.clone();
10554        task.resume_override = Some(crate::queue::OperatorResume {
10555            question_id: "pending-resume".into(),
10556            at: Timestamp::now(),
10557            conductor_rehold: None,
10558            forced: true,
10559            pinned_run: Some(run.id.clone()),
10560        });
10561        task.start(run.id.clone());
10562        queue.put(&mut task).unwrap();
10563        // Discard every in-memory handoff, as a worker death before execute does.
10564        let mut recovered = queue.get(&task.id).unwrap();
10565        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10566        reclaim(&mut recovered, Some(disk), 2, "en");
10567        queue.put(&mut recovered).unwrap();
10568        assert!(recovered.resume_override.is_none());
10569        assert_eq!(
10570            recovered.dispatched_resumes.get("pending-resume"),
10571            Some(&run.id)
10572        );
10573        let mut stale = stale;
10574        queue.put(&mut stale).unwrap();
10575        assert_eq!(
10576            stale.dispatched_resumes, recovered.dispatched_resumes,
10577            "a stale task writer cannot erase dispatch ownership"
10578        );
10579        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10580        assert!(resumed.decision_starts.is_empty());
10581        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10582        assert!(
10583            resumed.decision_starts.is_empty(),
10584            "handoff is not execution proof"
10585        );
10586        resumed.begin_pass();
10587        resumed.save_under(dir.path()).unwrap();
10588        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10589        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10590        disk.carry_dispatched_resumes(&recovered);
10591        disk.begin_pass();
10592        assert_eq!(
10593            disk.decision_starts.get("pending-resume"),
10594            Some(&0),
10595            "later execution must preserve the original pass receipt"
10596        );
10597    }
10598
10599    #[test]
10600    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10601        let mut t = task();
10602        t.start("20260904-000000-4043".to_owned());
10603        t.last_error = Some("earlier trouble".to_owned());
10604        let mut state = run_state(RunStatus::Judging);
10605        state.parked = true;
10606        reclaim(&mut t, Some(state), 1, "en");
10607        assert_eq!(t.status, TaskStatus::Parked);
10608        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10609        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10610        assert!(t.park_reason.is_some());
10611        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10612        assert!(!t.fresh_start);
10613        assert!(t.status.runnable());
10614    }
10615
10616    #[test]
10617    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10618        let mut t = task();
10619        t.start("20260904-000000-4043".to_owned());
10620        t.last_error = Some("earlier trouble".to_owned());
10621        settle(
10622            &mut t,
10623            Verdict {
10624                status: RunStatus::Judging,
10625                left_pr: false,
10626                quota_hit: false,
10627                parked: true,
10628                no_viable_candidates: false,
10629            },
10630            "parked after `judging`",
10631            1,
10632        );
10633        assert_eq!(t.status, TaskStatus::Parked);
10634        assert_eq!(t.attempts, 0);
10635        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10636        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10637        assert_eq!(t.schema, crate::queue::SCHEMA);
10638        assert!(
10639            crate::notices::task_held(&t).is_none(),
10640            "a park is not news"
10641        );
10642        t.start("20260904-000000-4043".to_owned());
10643        assert_eq!(t.park_reason, None);
10644    }
10645
10646    #[test]
10647    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10648        // A blocked run with attempts left goes back to `Failed`, exactly as
10649        // it would from `attempt` itself - `reclaim` must not invent a second
10650        // policy for a task a daemon merely stopped without reporting.
10651        let mut t = task();
10652        t.start("20260904-000000-4043".to_owned());
10653        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10654        assert_eq!(t.status, TaskStatus::Failed);
10655        assert!(t.status.runnable());
10656    }
10657
10658    #[test]
10659    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10660        let mut t = task();
10661        t.start("20260904-000000-4043".to_owned());
10662        assert_eq!(t.attempts, 1);
10663        let mut run = run_state(RunStatus::Implementing);
10664        run.id = "20260904-000000-4043".to_owned();
10665        run.begin_pass();
10666        let cause = crate::run::ParkCause::Upgrade {
10667            from: "0.121.0".to_owned(),
10668            to: Some("0.121.1".to_owned()),
10669        };
10670        run.end_pass_parked(cause.clone());
10671        run.parked = true;
10672        let verdict = Verdict {
10673            status: run.status,
10674            left_pr: false,
10675            quota_hit: false,
10676            parked: true,
10677            no_viable_candidates: false,
10678        };
10679        // A crash after the checkpoint but before queue settlement must
10680        // recover exactly the same scheduling evidence and refund.
10681        let mut orphan = t.clone();
10682        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10683        assert_eq!(orphan.status, TaskStatus::Parked);
10684        assert_eq!(orphan.attempts, 0);
10685        assert_eq!(
10686            orphan.upgrade_resume_key(),
10687            Some((run.passes[0].started_at, orphan.id.as_str()))
10688        );
10689        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10690        assert_eq!(t.attempts, 0);
10691        assert_eq!(t.passes.len(), 1);
10692        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10693        assert_eq!(t.passes[0].parked, Some(cause));
10694        assert_eq!(t.passes[0].pass_index, 0);
10695        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10696        assert!(t.upgrade_resume_key().is_some());
10697
10698        // A resumed pass that then fails spends its attempt, and the earlier
10699        // pass's entry is untouched.
10700        t.start("20260904-000000-4043".to_owned());
10701        run.begin_pass();
10702        run.status = RunStatus::Failed;
10703        let verdict = Verdict {
10704            status: RunStatus::Failed,
10705            left_pr: false,
10706            quota_hit: false,
10707            parked: false,
10708            no_viable_candidates: false,
10709        };
10710        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10711        assert_eq!(t.passes.len(), 2);
10712        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10713        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10714        assert_eq!(t.passes[1].pass_index, 1);
10715        assert_eq!(t.attempts, 1);
10716    }
10717
10718    #[test]
10719    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10720        let mut t = task();
10721        t.start("20260904-000000-4043".to_owned());
10722        reclaim(&mut t, None, 2, "en");
10723        assert_eq!(t.status, TaskStatus::Held);
10724        assert!(
10725            t.last_error
10726                .as_deref()
10727                .is_some_and(|e| e.contains("running")),
10728            "the operator needs to know why this task was held"
10729        );
10730    }
10731
10732    #[test]
10733    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10734        let dir = tempfile::tempdir().unwrap();
10735        let queue = Queue::at(dir.path().to_path_buf());
10736        let mut task = task();
10737        let run = "20261124-000000-dead";
10738        task.link_run(run);
10739        task.attempts = 2;
10740        task.status = TaskStatus::Running;
10741        task.sync_only = Some(crate::base_sync_only::Request {
10742            run: run.into(),
10743            at: Timestamp::now(),
10744        });
10745        queue.put(&mut task).unwrap();
10746        assert_eq!(
10747            reclaim_orphaned_running(&queue, 3, &Default::default()),
10748            vec![task.id.clone()]
10749        );
10750        let saved = queue.get(&task.id).unwrap();
10751        assert_eq!(saved.status, TaskStatus::Held);
10752        assert_eq!(saved.attempts, 2);
10753        assert_eq!(saved.execution_runs(), [run]);
10754        assert!(
10755            saved
10756                .last_error
10757                .unwrap()
10758                .contains("verification was not allowed")
10759        );
10760        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10761    }
10762
10763    #[test]
10764    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10765        use crate::base_sync_only::{Outcome, Pass, Request};
10766
10767        let mut state = run_state(RunStatus::Blocked);
10768        let mut task = task();
10769        let request = Request {
10770            run: state.id.clone(),
10771            at: Timestamp::now(),
10772        };
10773        task.start(state.id.clone());
10774        task.sync_only = Some(request.clone());
10775        // Dedicated dispatch saves Running with the pre-pass attempt count.
10776        task.attempts = 2;
10777        let mut pass = Pass::new(request, &state);
10778        pass.result = Outcome::AlreadyCurrent;
10779        state.sync_only_passes.push(pass);
10780        state.begin_pass();
10781
10782        reclaim(&mut task, Some(state), 3, "en");
10783
10784        assert_eq!(task.status, TaskStatus::Held);
10785        assert_eq!(task.attempts, 2);
10786        assert!(task.sync_only.is_none());
10787        let detail = task.hold_reason.unwrap();
10788        assert!(detail.contains("HEAD already contains the base"));
10789        assert!(detail.contains("verification was not allowed"));
10790    }
10791
10792    #[test]
10793    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10794        let dir = tempfile::tempdir().unwrap();
10795        let queue = Queue::at(dir.path().to_path_buf());
10796
10797        // No run recorded, so this never has to touch `RunState::load`.
10798        let mut orphaned = task();
10799        orphaned.id = "20260904-000000-orph".to_owned();
10800        orphaned.status = TaskStatus::Running;
10801        orphaned.attempts = 1;
10802        queue.put(&mut orphaned).unwrap();
10803
10804        let mut alive = task();
10805        alive.id = "20260904-000000-live".to_owned();
10806        alive.status = TaskStatus::Running;
10807        alive.attempts = 1;
10808        queue.put(&mut alive).unwrap();
10809        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10810
10811        let mut queued = task();
10812        queued.id = "20260904-000000-wait".to_owned();
10813        queue.put(&mut queued).unwrap();
10814
10815        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10816        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10817
10818        assert_eq!(
10819            queue.get(&orphaned.id).unwrap().status,
10820            TaskStatus::Held,
10821            "nothing was driving it and there was no run to recover"
10822        );
10823        assert_eq!(
10824            queue.get(&alive.id).unwrap().status,
10825            TaskStatus::Running,
10826            "a live claim must protect the task it belongs to"
10827        );
10828        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10829    }
10830
10831    /// Read a run.json back from an explicit `home`, the same way
10832    /// `reclaim_abandoned_runs` itself does - never through the
10833    /// process-global `RunState::load`, which this test's own `home` (an
10834    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10835    /// use at all.
10836    fn read_run_under(home: &Path, id: &str) -> RunState {
10837        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10838        serde_json::from_str(&body).unwrap()
10839    }
10840
10841    #[test]
10842    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10843        let dir = tempfile::tempdir().unwrap();
10844        let home = dir.path().to_path_buf();
10845        let now = Timestamp::now();
10846        let overrun_seat = || crate::run::ActiveSeat {
10847            node: "implement".to_owned(),
10848            started_at: now - jiff::SignedDuration::new(21_000, 0),
10849            timeout_secs: 3_600,
10850            attempt: 0,
10851            task: None,
10852            command: None,
10853            index: None,
10854            total: None,
10855        };
10856
10857        let mut dead = run_state(RunStatus::Implementing);
10858        dead.id = "20260101-000000-dead".to_owned();
10859        dead.active.insert("impl-A".to_owned(), overrun_seat());
10860        // A `driver_pid` the injected query below confirms gone outright —
10861        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10862        dead.driver_pid = Some(4242);
10863        dead.save_under(&home).unwrap();
10864
10865        // Same shape, but a live daemon's heartbeat names it: must be left
10866        // exactly alone, however far past its own timeout the seat sits.
10867        let mut alive = run_state(RunStatus::Implementing);
10868        alive.id = "20260101-000000-aliv".to_owned();
10869        alive.active.insert("impl-A".to_owned(), overrun_seat());
10870        alive.save_under(&home).unwrap();
10871        let mut status = Status::new();
10872        status.current = vec![Current {
10873            worker: None,
10874            task: "20260101-000000-task".to_owned(),
10875            run: alive.id.clone(),
10876        }];
10877        write_status_to(&home.join("daemon.json"), &status).unwrap();
10878
10879        // The abandoned seat left an open question behind: nobody is left to
10880        // read an answer once the run is failed, and this must not wait for
10881        // some later daemon startup's own sweep to notice that.
10882        let questions = Questions::at(home.join("questions"));
10883        let mut q = ask::Question::new(
10884            dead.id.clone(),
10885            "implement".to_owned(),
10886            "impl-A".to_owned(),
10887            "Which storage backend?".to_owned(),
10888            String::new(),
10889            vec!["SQLite".to_owned(), "Redis".to_owned()],
10890        );
10891        questions.put(&mut q).unwrap();
10892
10893        let abandoned = reclaim_abandoned_runs_with(
10894            &home,
10895            now,
10896            |pid| if pid == 4242 { Some(false) } else { None },
10897            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10898        );
10899        assert_eq!(abandoned, vec![dead.id.clone()]);
10900
10901        let reloaded = read_run_under(&home, &dead.id);
10902        assert_eq!(reloaded.status, RunStatus::Failed);
10903        assert!(reloaded.active.is_empty());
10904        assert!(
10905            !questions.get(&q.id).unwrap().status.open(),
10906            "the failed run's own open question must be settled in the same pass"
10907        );
10908
10909        let still_alive = read_run_under(&home, &alive.id);
10910        assert_eq!(
10911            still_alive.status,
10912            RunStatus::Implementing,
10913            "a live daemon's claim protects it"
10914        );
10915        assert!(!still_alive.active.is_empty());
10916    }
10917
10918    /// The exact shape a review round flagged as broken: `magi serve` running
10919    /// in this same `home` scans *every* run on disk, including a manual
10920    /// `magi review` / `magi run` this daemon never started and that
10921    /// therefore claims no heartbeat of its own. Before this scan asked
10922    /// `liveness` rather than just `is_working_on`, a manual run whose active
10923    /// seat merely ran a little past its own timeout — the CLI finishing up,
10924    /// its result still being collected — got wiped and failed by a daemon
10925    /// that had nothing to do with it, out from under a process that was
10926    /// still very much running.
10927    #[test]
10928    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10929        let dir = tempfile::tempdir().unwrap();
10930        let home = dir.path().to_path_buf();
10931        let now = Timestamp::now();
10932
10933        let mut manual = run_state(RunStatus::Reviewing);
10934        manual.id = "20260101-000000-manl".to_owned();
10935        manual.active.insert(
10936            "review-1".to_owned(),
10937            crate::run::ActiveSeat {
10938                node: "review".to_owned(),
10939                started_at: now - jiff::SignedDuration::new(21_000, 0),
10940                timeout_secs: 3_600,
10941                attempt: 0,
10942                task: None,
10943                command: None,
10944                index: None,
10945                total: None,
10946            },
10947        );
10948        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10949        // but a real, still-running process: `liveness` must corroborate this
10950        // as `Live`, not read the missing daemon claim as death.
10951        manual.driver_pid = Some(4242);
10952        manual.driver_started_at = Some("1790000000".to_owned());
10953        manual.save_under(&home).unwrap();
10954
10955        let abandoned = reclaim_abandoned_runs_with(
10956            &home,
10957            now,
10958            |pid| if pid == 4242 { Some(true) } else { None },
10959            |pid| {
10960                if pid == 4242 {
10961                    Some("1790000000".to_owned())
10962                } else {
10963                    None
10964                }
10965            },
10966        );
10967        assert!(
10968            abandoned.is_empty(),
10969            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10970        );
10971
10972        let reloaded = read_run_under(&home, &manual.id);
10973        assert_eq!(reloaded.status, RunStatus::Reviewing);
10974        assert!(!reloaded.active.is_empty());
10975    }
10976
10977    #[test]
10978    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10979        let dir = tempfile::tempdir().unwrap();
10980        let queue = Queue::at(dir.path().to_path_buf());
10981        let mut only = task();
10982        queue.put(&mut only).unwrap();
10983
10984        let _elsewhere = queue.claim(&only.id).unwrap();
10985        let candidates = runnable(&queue);
10986        assert_eq!(candidates.len(), 1, "the task is still runnable");
10987        assert!(
10988            queue.claim(&candidates[0].id).is_err(),
10989            "the loop cannot take a claim somebody else holds"
10990        );
10991
10992        let after = queue.get(&only.id).unwrap();
10993        assert_eq!(after.status, TaskStatus::Queued);
10994        assert_eq!(
10995            after.attempts, 0,
10996            "losing the race is not an attempt at the task"
10997        );
10998        assert_eq!(after.last_error, None);
10999    }
11000
11001    #[test]
11002    fn the_status_file_round_trips_and_its_heartbeat_advances() {
11003        let dir = tempfile::tempdir().unwrap();
11004        let path = dir.path().join("daemon.json");
11005
11006        let mut status = Status::new();
11007        status.idle = false;
11008        status.completed = 7;
11009        status.current = vec![Current {
11010            worker: None,
11011            task: "20260902-000000-t111".to_owned(),
11012            run: "20260902-000001-r111".to_owned(),
11013        }];
11014        write_status_to(&path, &status).unwrap();
11015        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
11016        assert_eq!(first.schema, SCHEMA);
11017        assert_eq!(first.pid, std::process::id());
11018        assert!(!first.idle);
11019        assert_eq!(first.completed, 7);
11020        assert_eq!(first.current, status.current);
11021        assert!(
11022            !path.with_extension("json.tmp").exists(),
11023            "the temp file is renamed, not left behind"
11024        );
11025
11026        std::thread::sleep(Duration::from_millis(5));
11027        status.updated_at = Timestamp::now();
11028        status.polls = 3;
11029        write_status_to(&path, &status).unwrap();
11030        let second: Status =
11031            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
11032        assert!(
11033            second.updated_at > first.updated_at,
11034            "a reader can only detect staleness if the heartbeat moves"
11035        );
11036        assert_eq!(
11037            second.started_at, first.started_at,
11038            "the start time is not a heartbeat"
11039        );
11040        assert_eq!(second.polls, 3);
11041    }
11042
11043    #[test]
11044    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
11045        let dir = tempfile::tempdir().unwrap();
11046
11047        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
11048
11049        let mut status = Status::new();
11050        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
11051        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11052        let stale = read_status(dir.path()).unwrap();
11053        assert!(
11054            !stale.running(Timestamp::now()),
11055            "a minute without a heartbeat is a dead daemon, not a busy one"
11056        );
11057        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
11058
11059        status.updated_at = Timestamp::now();
11060        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11061        let fresh = read_status(dir.path()).unwrap();
11062        assert!(fresh.running(Timestamp::now()));
11063    }
11064
11065    #[test]
11066    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
11067        let dir = tempfile::tempdir().unwrap();
11068        let now = Timestamp::now();
11069        let mine = "20260903-080619-01c2";
11070
11071        assert!(
11072            !is_working_on(dir.path(), mine, now),
11073            "no status file means nobody is working on anything"
11074        );
11075
11076        let mut status = Status::new();
11077        status.current = vec![Current {
11078            worker: None,
11079            task: "20260903-080340-0167".to_owned(),
11080            run: mine.to_owned(),
11081        }];
11082        status.updated_at = now;
11083        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11084        assert!(is_working_on(dir.path(), mine, now));
11085        assert!(
11086            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
11087            "a daemon busy with one run is not working on another"
11088        );
11089
11090        // A killed daemon stops writing heartbeats but leaves the file behind
11091        // naming the run it died in. That run must not be undeletable forever.
11092        status.updated_at = now - jiff::SignedDuration::from_secs(600);
11093        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11094        assert!(
11095            !is_working_on(dir.path(), mine, now),
11096            "a stale heartbeat is a dead daemon, so its run is a leftover"
11097        );
11098    }
11099
11100    #[test]
11101    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
11102        let dir = tempfile::tempdir().unwrap();
11103        let now = Timestamp::now();
11104
11105        assert!(
11106            !is_working_on_short(dir.path(), "01c2", now),
11107            "no status file means nobody is working on anything"
11108        );
11109
11110        let mut status = Status::new();
11111        status.current = vec![Current {
11112            worker: None,
11113            task: "20260903-080340-0167".to_owned(),
11114            run: "20260903-080619-01c2".to_owned(),
11115        }];
11116        status.updated_at = now;
11117        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11118        assert!(
11119            is_working_on_short(dir.path(), "01c2", now),
11120            "the run's short id is the last block of its full id"
11121        );
11122        assert!(
11123            !is_working_on_short(dir.path(), "3cbf", now),
11124            "a daemon busy with one worktree bay is not working on another"
11125        );
11126    }
11127
11128    #[test]
11129    fn a_newer_status_file_still_yields_a_reading() {
11130        let dir = tempfile::tempdir().unwrap();
11131        // A field this build has never heard of must not turn the reading into
11132        // nothing at all; that is the whole reason the reader is permissive.
11133        std::fs::write(
11134            dir.path().join("daemon.json"),
11135            serde_json::json!({
11136                "schema": 2,
11137                "updated_at": Timestamp::now().to_string(),
11138                "idle": true,
11139                "surprise": { "nested": [1, 2, 3] },
11140            })
11141            .to_string(),
11142        )
11143        .unwrap();
11144
11145        let reading = read_status(dir.path()).expect("a forward-compatible read");
11146        assert!(reading.running(Timestamp::now()));
11147        assert!(reading.idle);
11148        assert!(reading.current.is_empty());
11149    }
11150
11151    #[test]
11152    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
11153        // A daemon started before `current` became a list keeps writing this
11154        // shape on every heartbeat until it is restarted. A rolling upgrade
11155        // - a newer `magi web` or `magi doctor` reading an older `magi
11156        // serve`'s heartbeat - must still see the run it is on, not "no
11157        // daemon" from a type mismatch failing the whole struct.
11158        let dir = tempfile::tempdir().unwrap();
11159        std::fs::write(
11160            dir.path().join("daemon.json"),
11161            serde_json::json!({
11162                "schema": 1,
11163                "pid": 4242,
11164                "updated_at": Timestamp::now().to_string(),
11165                "idle": false,
11166                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
11167                "completed": 3,
11168                "polls": 9,
11169            })
11170            .to_string(),
11171        )
11172        .unwrap();
11173
11174        let reading = read_status(dir.path()).expect("an older shape must still parse");
11175        assert!(reading.running(Timestamp::now()));
11176        assert_eq!(
11177            reading.current,
11178            vec![Current {
11179                worker: None,
11180                task: "20260902-140501-aaaa".to_owned(),
11181                run: "20260902-140502-bbbb".to_owned(),
11182            }]
11183        );
11184    }
11185
11186    #[test]
11187    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
11188        let dir = tempfile::tempdir().unwrap();
11189        std::fs::write(
11190            dir.path().join("daemon.json"),
11191            serde_json::json!({
11192                "schema": 1,
11193                "updated_at": Timestamp::now().to_string(),
11194                "idle": true,
11195                "current": null,
11196            })
11197            .to_string(),
11198        )
11199        .unwrap();
11200        let with_null = read_status(dir.path()).expect("null must still parse");
11201        assert!(with_null.current.is_empty());
11202
11203        std::fs::write(
11204            dir.path().join("daemon.json"),
11205            serde_json::json!({
11206                "schema": 1,
11207                "updated_at": Timestamp::now().to_string(),
11208                "idle": true,
11209            })
11210            .to_string(),
11211        )
11212        .unwrap();
11213        let absent = read_status(dir.path()).expect("a missing field must still parse");
11214        assert!(absent.current.is_empty());
11215    }
11216
11217    #[test]
11218    fn a_task_without_a_repository_runs_in_the_daemons_default() {
11219        let fallback = Path::new("/default");
11220        let mut blank = task();
11221        blank.repo = PathBuf::new();
11222        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
11223        let mut dot = task();
11224        dot.repo = PathBuf::from(".");
11225        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
11226        assert_eq!(
11227            repo_for(&task(), fallback),
11228            PathBuf::from("/repo"),
11229            "a task that names a repository keeps it"
11230        );
11231    }
11232
11233    #[test]
11234    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
11235        let dir = tempfile::tempdir().unwrap();
11236        let repo = dir.path();
11237        let path = repo.join("explicit.toml");
11238        std::fs::write(
11239            &path,
11240            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
11241        )
11242        .unwrap();
11243        let opts = Opts {
11244            config: Some(path),
11245            ..Opts::default()
11246        };
11247        let queue = Queue::at(repo.join("queue"));
11248        let mut new = task();
11249        queue.put(&mut new).unwrap();
11250        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
11251        assert_eq!(
11252            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
11253            BuildCache::Isolated
11254        );
11255
11256        let mut old = task();
11257        old.schema = 22;
11258        queue.put(&mut old).unwrap();
11259        let mut old = queue.get(&old.id).unwrap();
11260        let config = resolved(&old);
11261        assert_eq!(config.verify.build_cache, BuildCache::Shared);
11262        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
11263        old.hold_manual(Some("wait".into()));
11264        queue.put(&mut old).unwrap();
11265
11266        let mut saved = queue.get(&old.id).unwrap();
11267        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
11268        saved
11269            .overrides
11270            .as_mut()
11271            .unwrap()
11272            .merge_over(&crate::queue::RunOverrides {
11273                build_cache: Some(BuildCache::Isolated),
11274                ..Default::default()
11275            });
11276        queue.put(&mut saved).unwrap();
11277        assert_eq!(
11278            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
11279            BuildCache::Isolated
11280        );
11281    }
11282
11283    #[test]
11284    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
11285        let dir = tempfile::tempdir().unwrap();
11286        let path = dir.path().join("explicit.toml");
11287        let write = |verify: &str| {
11288            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
11289        };
11290        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
11291        let opts = Opts {
11292            config: Some(path.clone()),
11293            ..Opts::default()
11294        };
11295        let mut task = task();
11296        task.set_urgent(true).unwrap();
11297        let resolved = |task: &Task| {
11298            prepare_for(dir.path(), &opts, task)
11299                .unwrap()
11300                .verify
11301                .build_cache
11302        };
11303        assert_eq!(resolved(&task), BuildCache::Isolated);
11304        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
11305        assert_eq!(resolved(&task), BuildCache::Shared);
11306        task.change_build_cache(None).unwrap();
11307        assert_eq!(resolved(&task), BuildCache::Isolated);
11308        task.set_urgent(false).unwrap();
11309        assert_eq!(resolved(&task), BuildCache::Shared);
11310
11311        // Urgent work must never be the one stopped by isolation: with no
11312        // shared cache to wait behind, or with a verification command isolated
11313        // mode cannot run, an urgent task keeps the configured mode.
11314        task.set_urgent(true).unwrap();
11315        write("e2e = [\"npm test\"]\n");
11316        assert_eq!(resolved(&task), BuildCache::Shared);
11317        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
11318        assert_eq!(resolved(&task), BuildCache::Shared);
11319        // An explicit choice stays strict and is applied as asked.
11320        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
11321        assert_eq!(resolved(&task), BuildCache::Isolated);
11322    }
11323
11324    #[test]
11325    fn task_implementers_edit_inherits_daemon_config_and_merge() {
11326        let dir = tempfile::tempdir().unwrap();
11327        let path = dir.path().join("explicit.toml");
11328        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
11329        let opts = Opts {
11330            config: Some(path),
11331            merge: Some("none".into()),
11332            ..Default::default()
11333        };
11334        let mut t = task();
11335        t.set_implementers(
11336            2,
11337            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11338                .unwrap(),
11339        )
11340        .unwrap();
11341        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11342        assert_eq!(cfg.graph.implementers, 2);
11343        assert_eq!(cfg.graph.judges, 1);
11344        assert_eq!(cfg.merge.mode, MergeMode::None);
11345        t.set_implementers(1, &cfg).unwrap();
11346        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11347        apply_task_implementers(&mut cfg, &t);
11348        assert_eq!(cfg.graph.implementers, 1);
11349        assert_eq!(cfg.graph.judges, 1);
11350        assert_eq!(cfg.merge.mode, MergeMode::None);
11351    }
11352
11353    #[test]
11354    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
11355        let dir = tempfile::tempdir().unwrap();
11356        let repo = dir.path().join("repo");
11357        std::fs::create_dir(&repo).unwrap();
11358        std::fs::write(
11359            repo.join("magi.toml"),
11360            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
11361        )
11362        .unwrap();
11363        let daemon_config = dir.path().join("daemon.toml");
11364        std::fs::write(
11365            &daemon_config,
11366            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
11367        )
11368        .unwrap();
11369        let opts = Opts {
11370            config: Some(daemon_config),
11371            merge: Some("pr".into()),
11372            ..Default::default()
11373        };
11374        let q = Queue::at(dir.path().join("queue"));
11375        let validation: Config =
11376            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11377                .unwrap();
11378        // No provenance field on legacy direct tasks: both shapes stay isolated.
11379        for record in ["{}", r#"{"candidates":2}"#] {
11380            let overrides = serde_json::from_str(record).unwrap();
11381            let filing = crate::direct::Filing {
11382                instruction: "work".into(),
11383                title: "direct".into(),
11384                repo: repo.clone(),
11385                source: crate::queue::Source::Human,
11386                solo: false,
11387                overrides,
11388                review_of: None,
11389                sources: Default::default(),
11390            };
11391            let filed =
11392                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11393            let crate::direct::Filed::Standalone {
11394                mut task,
11395                claim: _claim,
11396            } = filed
11397            else {
11398                panic!("local filing")
11399            };
11400            let before = prepare_for(&repo, &opts, &task).unwrap();
11401            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11402            assert_eq!(
11403                before.merge.mode,
11404                MergeMode::None,
11405                "daemon --merge must not leak"
11406            );
11407            for n in [2, 1, 2] {
11408                task.set_implementers(n, &validation).unwrap();
11409                q.put(&mut task).unwrap();
11410                task = q.get(&task.id).unwrap();
11411                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11412                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11413                apply_task_implementers(&mut cfg, &task);
11414                assert_eq!(cfg.graph.implementers, usize::from(n));
11415                assert_eq!(cfg.graph.judges, 2);
11416                assert_eq!(cfg.merge.mode, MergeMode::None);
11417            }
11418        }
11419    }
11420
11421    #[test]
11422    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11423        let cfg: Config =
11424            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11425                .unwrap();
11426        let mut t = task();
11427        t.review_of = Some("review-target".into());
11428        t.hold_manual(Some("retry".into()));
11429        let mut previous = RunState::new(
11430            PathBuf::from("/repo"),
11431            "main".into(),
11432            "abc1234".into(),
11433            "review".into(),
11434            cfg.clone(),
11435        );
11436        previous.config.graph.implementers = 2;
11437        for count in [1, 3] {
11438            t.set_implementers(count, &cfg).unwrap();
11439            t.release();
11440            assert_eq!(t.review_of.as_deref(), Some("review-target"));
11441            for proposed in [
11442                Starter::Resume(previous.id.clone()),
11443                Starter::Review("recovery-target".into()),
11444            ] {
11445                assert_eq!(
11446                    starter_with_implementers(&t, Some(&previous), proposed),
11447                    Starter::Review("review-target".into())
11448                );
11449            }
11450            let mut configured = cfg.clone();
11451            apply_task_implementers(&mut configured, &t);
11452            assert_eq!(configured.graph.implementers, usize::from(count));
11453            assert_eq!(previous.config.graph.implementers, 2);
11454        }
11455    }
11456
11457    #[test]
11458    fn task_implementers_dispatch_and_resume_agree() {
11459        let mut t = task();
11460        let cfg: crate::config::Config =
11461            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11462                .unwrap();
11463        let mut run = RunState::new(
11464            PathBuf::from("/repo"),
11465            "main".into(),
11466            "abc1234".into(),
11467            "work".into(),
11468            cfg.clone(),
11469        );
11470        run.config.graph.implementers = 2;
11471        for n in [2, 1, 3, 2] {
11472            t.set_implementers(n, &cfg).unwrap();
11473            let mut dispatched = cfg.clone();
11474            apply_task_implementers(&mut dispatched, &t);
11475            assert_eq!(dispatched.graph.implementers, usize::from(n));
11476            assert_eq!(implementers_match(&t, &run), n == 2);
11477            for proposed in [
11478                Starter::Resume(run.id.clone()),
11479                Starter::Review("old-branch".into()),
11480            ] {
11481                let expected = if n == 2 {
11482                    proposed.clone()
11483                } else {
11484                    Starter::Start
11485                };
11486                assert_eq!(
11487                    starter_with_implementers(&t, Some(&run), proposed),
11488                    expected
11489                );
11490            }
11491            assert_eq!(
11492                run.config.graph.implementers, 2,
11493                "history must not be rewritten"
11494            );
11495        }
11496        t.solo = false;
11497        t.overrides = None;
11498        assert!(implementers_match(&t, &run));
11499    }
11500
11501    #[test]
11502    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11503        // Three seats said out loud. What `solo` promises is one candidate
11504        // *whatever the config asks for*, so the contrast has to be a number
11505        // this test owns - it used to be `Config::default()`'s, which became
11506        // 1 when one implementation became the default and left the two
11507        // halves of this test asserting the same thing.
11508        let mut solo_cfg = Config::default();
11509        solo_cfg.graph.implementers = 3;
11510        let mut solo_task = task();
11511        solo_task.solo = true;
11512        apply_task_implementers(&mut solo_cfg, &solo_task);
11513        assert_eq!(solo_cfg.graph.implementers, 1);
11514
11515        let mut plain_cfg = Config::default();
11516        plain_cfg.graph.implementers = 3;
11517        let plain_task = task();
11518        assert!(!plain_task.solo);
11519        apply_task_implementers(&mut plain_cfg, &plain_task);
11520        assert_eq!(
11521            plain_cfg.graph.implementers, 3,
11522            "a task that did not ask to run alone keeps the config's candidates"
11523        );
11524    }
11525
11526    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11527        QuotaLoss {
11528            cause: crate::agent::QuotaCause::UsageLimit,
11529            agent: String::new(),
11530            seat: seat.into(),
11531            node: "judge".into(),
11532            at: at.parse().unwrap(),
11533            reset: reset.map(str::to_string),
11534        }
11535    }
11536
11537    #[test]
11538    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11539        let now = Timestamp::now();
11540        for reset in [None, Some("in 1h")] {
11541            let auth = crate::agent::Quota {
11542                cause: crate::agent::QuotaCause::Authentication,
11543                agent: "alpha".into(),
11544                reset: reset.map(str::to_owned),
11545            };
11546            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11547            assert_eq!(cooldown_until(&[loss], now), None);
11548        }
11549    }
11550
11551    #[test]
11552    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11553        let old: Vec<QuotaLoss> = (1..=4)
11554            .map(|i| {
11555                loss(
11556                    &format!("judge-{i}"),
11557                    "2026-09-23T05:23:00Z",
11558                    Some("2:40pm (Asia/Tokyo)"),
11559                )
11560            })
11561            .collect();
11562        let fresh = losses_this_attempt(&old, &old);
11563        assert!(fresh.is_empty());
11564        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11565        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
11566    }
11567
11568    #[test]
11569    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11570        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11571        let now = Timestamp::now();
11572        let mut after = old.clone();
11573        after.push(loss("judge-2", &now.to_string(), None));
11574        let fresh = losses_this_attempt(&old, &after);
11575        assert_eq!(fresh, vec![after[1].clone()]);
11576        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11577        assert_eq!(
11578            until,
11579            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11580        );
11581    }
11582
11583    #[test]
11584    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11585        // `recover_stall` removes judge-1's loss and the retry then hits quota
11586        // again: the vector is the same length, so an index diff sees nothing.
11587        let before = vec![
11588            loss("judge-1", "2026-09-23T05:23:00Z", None),
11589            loss("judge-2", "2026-09-23T05:24:00Z", None),
11590        ];
11591        let after = vec![
11592            loss("judge-2", "2026-09-23T05:24:00Z", None),
11593            loss("judge-1", "2026-09-24T01:00:00Z", None),
11594        ];
11595        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11596    }
11597
11598    #[test]
11599    fn merge_overrides_are_parsed_or_refused() {
11600        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11601        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11602        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11603        assert!(merge_mode("squash").is_err());
11604    }
11605
11606    #[test]
11607    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11608        let now = Timestamp::now();
11609        let fallback = Duration::from_secs(300);
11610        let cap = Duration::from_secs(1800);
11611
11612        // No reset hint at all: the fallback.
11613        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11614
11615        // A reset ten minutes out, well inside the cap: waited for exactly.
11616        let soon = now + jiff::SignedDuration::from_secs(600);
11617        assert_eq!(
11618            quota_wait(Some(soon), now, fallback, cap),
11619            Duration::from_secs(600)
11620        );
11621
11622        // A reset already in the past is not trusted: the fallback, not a
11623        // zero or negative wait that would spin the loop right back around.
11624        let past = now - jiff::SignedDuration::from_secs(60);
11625        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11626
11627        // A reset further out than the cap is trusted for direction but not
11628        // for magnitude: a parsing slip must not sleep the loop for a day.
11629        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11630        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11631    }
11632
11633    #[test]
11634    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11635        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11636
11637        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11638        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11639
11640        // Same clock reading, but it has already gone by today: read as
11641        // tomorrow's, since the CLI would not still be reporting a limit past
11642        // its own stated reset.
11643        let already_past =
11644            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11645        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11646
11647        assert!(
11648            parse_reset_hint("session limit reached", now, now).is_none(),
11649            "free text with no recognised shape is not guessed at"
11650        );
11651        assert!(
11652            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11653            "an unresolvable zone name is not guessed at either"
11654        );
11655    }
11656
11657    #[test]
11658    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11659        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11660
11661        let at = parse_reset_hint(
11662            "You've hit your usage limit. Visit \
11663             https://chatgpt.com/codex/settings/usage to purchase more \
11664             credits or try again at Sep 19th, 2026 5:10 PM.",
11665            now,
11666            now,
11667        )
11668        .expect("the codex reset wording is a recognised shape");
11669        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11670
11671        // The month is explicit, so a date already earlier in the same
11672        // sentence-implied year than `now` is trusted as written rather than
11673        // rolled forward a year the way the bracketed shape rolls a
11674        // same-day clock reading to tomorrow.
11675        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11676            .expect("an explicit year needs no rollover");
11677        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11678
11679        assert!(
11680            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11681            "a two-digit year is not the documented shape and is not guessed at"
11682        );
11683        assert!(
11684            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11685            "a four-letter month name is not the documented three-letter abbreviation"
11686        );
11687        assert!(
11688            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11689            "an explicit zone on the dated shape is a format nobody has \
11690             documented, and is refused rather than guessed at as UTC"
11691        );
11692    }
11693
11694    #[test]
11695    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11696        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11697        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11698
11699        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11700        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11701
11702        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11703        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11704
11705        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11706            assert!(
11707                parse_reset_hint(bad, now, recorded).is_none(),
11708                "{bad:?} must not be guessed at"
11709            );
11710        }
11711    }
11712
11713    /// A loop whose queue lives in a temp tree and whose poll interval is far
11714    /// longer than the test's patience, so anything that waits out a poll
11715    /// instead of noticing the stop fails rather than merely being slow.
11716    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11717        let config = dir.join("magi.toml");
11718        std::fs::write(
11719            &config,
11720            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11721        )
11722        .unwrap();
11723        let opts = Opts {
11724            poll: Duration::from_secs(30),
11725            config: Some(config),
11726            // The explicit fixture config keeps startup cleanup from reading
11727            // machine configuration. This fictional repository likewise
11728            // keeps any best-effort git cleanup away from this checkout.
11729            repo: dir.join("repo"),
11730            ..Opts::default()
11731        };
11732        // The status file goes in a directory that does not exist yet, so its
11733        // creation is itself evidence the loop published one. `worktrees`
11734        // must be just as fictional: the janitor reclaims worktrees under it
11735        // for real, and a test that let it fall through to
11736        // `crate::run::default_worktree_root()` would have it reclaim
11737        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11738        // which is exactly what happened before this function took the
11739        // parameter at all.
11740        let home = dir.join("home");
11741        // These control-only fixtures do not launch native workers. Give the
11742        // independently tested maintenance services a fresh cadence receipt.
11743        let stamps = home.join("service-ticks");
11744        std::fs::create_dir_all(&stamps).unwrap();
11745        for service in ["waiter", "deputies", "release-watch"] {
11746            std::fs::write(
11747                stamps.join(service),
11748                Timestamp::now().as_second().to_string(),
11749            )
11750            .unwrap();
11751        }
11752        for operation in [
11753            "conductor",
11754            "maintenance",
11755            "housekeeping",
11756            "disk-pressure",
11757            "cache",
11758            "fetch",
11759            "chat-goals",
11760        ] {
11761            std::fs::write(
11762                stamps.join(format!("daemon-{operation}")),
11763                serde_json::to_vec(&Timestamp::now()).unwrap(),
11764            )
11765            .unwrap();
11766        }
11767        let worktrees = dir.join("wt");
11768        (
11769            opts,
11770            Queue::at(dir.join("queue")),
11771            home.join("daemon.json"),
11772            home,
11773            worktrees,
11774        )
11775    }
11776
11777    #[tokio::test]
11778    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11779        let dir = tempfile::tempdir().unwrap();
11780        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11781        let mut waiting = task();
11782        waiting.repo = opts.repo.clone();
11783        waiting.hold_machine(crate::disk::gate(1, 100));
11784        waiting.mark_disk_capacity();
11785        waiting.attempts = 2;
11786        queue.put(&mut waiting).unwrap();
11787        let mut busy = task();
11788        busy.status = TaskStatus::Running;
11789        queue.put(&mut busy).unwrap();
11790        let payload = serde_json::to_value(ServiceWorker {
11791            opts,
11792            queue: queue.root().to_owned(),
11793            worktrees_root: worktrees,
11794            operation: "maintenance".into(),
11795        })
11796        .unwrap();
11797        run_service_worker(&home, payload.clone()).await.unwrap();
11798        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11799        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11800        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11801        run_service_worker(&home, payload).await.unwrap();
11802        assert!(
11803            crate::worker::active(&home).unwrap().is_empty(),
11804            "monitoring only queues; normal dispatch owns launches"
11805        );
11806        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11807    }
11808
11809    #[tokio::test]
11810    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11811        let dir = tempfile::tempdir().unwrap();
11812        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11813        let cfg = Config::default();
11814        start_service(
11815            &home,
11816            &opts,
11817            &queue,
11818            &worktrees,
11819            "housekeeping",
11820            Some(&cfg),
11821            true,
11822        )
11823        .await
11824        .unwrap();
11825        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11826        let read = |path: &Path| -> serde_json::Value {
11827            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11828        };
11829        assert_eq!(read(&receipt)["detail"], "cadence not due");
11830        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11831        start_service(
11832            &home,
11833            &opts,
11834            &queue,
11835            &worktrees,
11836            "housekeeping",
11837            Some(&cfg),
11838            true,
11839        )
11840        .await
11841        .unwrap();
11842        assert_eq!(
11843            read(&receipt)["detail"],
11844            "active work or runnable task queue"
11845        );
11846        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11847        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11848        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11849        start_service(
11850            &home,
11851            &opts,
11852            &queue,
11853            &worktrees,
11854            "disk-pressure",
11855            Some(&cfg),
11856            false,
11857        )
11858        .await
11859        .unwrap();
11860        assert_eq!(
11861            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11862            "no active work; idle housekeeping owns scan"
11863        );
11864        assert!(crate::worker::active(&home).unwrap().is_empty());
11865    }
11866
11867    #[tokio::test]
11868    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11869        let dir = tempfile::tempdir().unwrap();
11870        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11871        let queue = Queue::at(home.join("queue"));
11872        let mut task = task();
11873        task.repo = opts.repo.clone();
11874        task.chat = Some("decision-chat".into());
11875        task.hold_machine(Some("waiting for a decision".into()));
11876        queue.put(&mut task).unwrap();
11877        let questions = Questions::at(home.join("questions"));
11878        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11879        question.node = crate::conduct::NODE.into();
11880        question.status = ask::QuestionStatus::Open;
11881        question.answer = None;
11882        question.answered_at = None;
11883        questions.put(&mut question).unwrap();
11884        questions
11885            .update(&question.id, |q| {
11886                q.answer(ask::Answer::Choice("resume で続行する".into()))
11887            })
11888            .unwrap();
11889
11890        let talks = crate::talk::Talks::at(home.join("talks"));
11891        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11892        decision_chat.pending = "Keep this unsent status question".into();
11893        talks.put(&mut decision_chat).unwrap();
11894        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11895        talk.goals.push(serde_json::from_value(serde_json::json!({
11896            "id":"goal","purpose":"follow the retained job","scope":"one task",
11897            "condition":{"description":"land the result","kind":"runs_merged"},
11898            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11899            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11900            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11901        })).unwrap());
11902        talks.put(&mut talk).unwrap();
11903
11904        // A retained service lease models an observation still waiting on its
11905        // external dependency. Admission must neither await nor repeat it.
11906        let directory = home.join("workers/jobs/abcdef");
11907        std::fs::create_dir_all(&directory).unwrap();
11908        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11909        crate::pr_head::try_lock_file(&lease).unwrap();
11910        let mut job = crate::worker::Job {
11911            id: "abcdef".into(),
11912            sequence: 1,
11913            kind: "daemon-service".into(),
11914            key: "service:daemon-chat-goals".into(),
11915            payload: serde_json::Value::Null,
11916            generation: "fixture".into(),
11917            version: None,
11918            status: crate::worker::Status::Running,
11919            result: None,
11920            pid: Some(std::process::id()),
11921            created_at: Timestamp::now().as_second() as u64,
11922            finished_at: None,
11923        };
11924        let record = directory.join("job.json");
11925        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11926        let status = Arc::new(Mutex::new(Status::new()));
11927        let stop = Stop::new();
11928        let mut dispatch = Box::pin(poll(
11929            &opts,
11930            &queue,
11931            &status,
11932            &home,
11933            &worktrees,
11934            &stop,
11935            DispatchLimits {
11936                max_concurrent: 1,
11937                pause_for_interrupts: false,
11938                recovery_cfg: None,
11939            },
11940        ));
11941        std::future::poll_fn(|cx| {
11942            assert!(dispatch.as_mut().poll(cx).is_pending());
11943            std::task::Poll::Ready(())
11944        })
11945        .await;
11946        assert!(lock(&status).polls > 0);
11947        let saved = queue.get(&task.id).unwrap();
11948        assert_eq!(saved.status, TaskStatus::Done);
11949        assert!(saved.action_applied(&question.id));
11950        assert!(
11951            talks
11952                .get("decision-chat")
11953                .unwrap()
11954                .pending
11955                .contains("Keep this unsent status question")
11956        );
11957        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11958        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11959        assert_eq!(
11960            goal.started,
11961            Some(1),
11962            "only the observation worker may reconcile its goal"
11963        );
11964        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11965
11966        stop.stop();
11967        dispatch.await.unwrap();
11968        job.status = crate::worker::Status::Finished;
11969        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11970        drop(lease);
11971    }
11972
11973    #[test]
11974    fn a_stop_is_idempotent_and_once_set_stays_set() {
11975        let stop = Stop::new();
11976        assert!(!stop.stopped());
11977
11978        stop.stop();
11979        assert!(stop.stopped());
11980        stop.stop();
11981        assert!(stop.stopped(), "a second stop is not a toggle");
11982
11983        let shared = stop.clone();
11984        assert!(
11985            shared.stopped(),
11986            "a clone is the same stop; that is how the loop and its caller share one"
11987        );
11988    }
11989
11990    #[tokio::test]
11991    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
11992        for operation in ["conductor", "maintenance", "housekeeping"] {
11993            let dir = tempfile::tempdir().unwrap();
11994            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
11995            opts.once = true;
11996            opts.poll = Duration::from_millis(1);
11997            // This test exercises answer scheduling, not explicit discard:
11998            // ordinary Done requires a completed retained execution.
11999            let mut state = run_state(RunStatus::Ready);
12000            state.reserve_under(&home).unwrap();
12001            state.save_under(&home).unwrap();
12002            let mut task = task();
12003            task.runs.push(state.id.clone());
12004            queue.put(&mut task).unwrap();
12005            let claim = queue.claim(&task.id).unwrap();
12006
12007            // Model a live service holding the task's claim across the
12008            // scheduler's dispatch scan. No real subprocess or timed race.
12009            let directory = home.join("workers/jobs/abcdef");
12010            std::fs::create_dir_all(&directory).unwrap();
12011            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
12012            crate::pr_head::try_lock_file(&lease).unwrap();
12013            let mut job = crate::worker::Job {
12014                id: "abcdef".into(),
12015                sequence: 1,
12016                kind: "daemon-service".into(),
12017                key: format!("service:daemon-{operation}"),
12018                payload: serde_json::Value::Null,
12019                generation: "fixture".into(),
12020                version: None,
12021                status: crate::worker::Status::Running,
12022                result: None,
12023                pid: Some(std::process::id()),
12024                created_at: Timestamp::now().as_second() as u64,
12025                finished_at: None,
12026            };
12027            let record = directory.join("job.json");
12028            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
12029
12030            let status = Arc::new(Mutex::new(Status::new()));
12031            let stop = Stop::new();
12032            let mut drain = Box::pin(poll(
12033                &opts,
12034                &queue,
12035                &status,
12036                &home,
12037                &worktrees,
12038                &stop,
12039                DispatchLimits {
12040                    max_concurrent: 1,
12041                    pause_for_interrupts: false,
12042                    recovery_cfg: None,
12043                },
12044            ));
12045            std::future::poll_fn(|cx| {
12046                use std::future::Future;
12047                assert!(
12048                    drain.as_mut().poll(cx).is_pending(),
12049                    "--once must wait for {operation} to release its queue claim"
12050                );
12051                std::task::Poll::Ready(())
12052            })
12053            .await;
12054            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
12055
12056            // An answer arrives while the service still owns the claim. A
12057            // fresh scheduling pass must apply it before declaring idle.
12058            let questions = Questions::at(home.join("questions"));
12059            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
12060            questions.put(&mut q).unwrap();
12061            drop(claim);
12062            // Model services that took longer than their cadence, without a
12063            // wall-clock sleep. The final scans must not respawn them even
12064            // though their receipts now permit another periodic invocation.
12065            let expired =
12066                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
12067            for service in [operation, "housekeeping"] {
12068                std::fs::write(
12069                    home.join("service-ticks").join(format!("daemon-{service}")),
12070                    &expired,
12071                )
12072                .unwrap();
12073            }
12074            job.status = crate::worker::Status::Finished;
12075            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
12076            drop(lease);
12077            tokio::time::timeout(Duration::from_secs(2), drain)
12078                .await
12079                .expect("the settled service must allow the drain to finish")
12080                .unwrap();
12081            let after = queue.get(&task.id).unwrap();
12082            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
12083            assert!(after.action_applied(&q.id));
12084            for service in [operation, "housekeeping"] {
12085                assert_eq!(
12086                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
12087                        .unwrap(),
12088                    expired,
12089                    "the final once rescan must not restart {service}"
12090                );
12091            }
12092        }
12093    }
12094
12095    #[test]
12096    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
12097        let stop = Stop::new();
12098        stop.busy.store(1, Ordering::SeqCst);
12099        assert!(
12100            !stop.finishing(),
12101            "a busy loop nobody has asked to stop is just running"
12102        );
12103
12104        stop.stop();
12105        assert!(
12106            stop.finishing(),
12107            "a stop asked for mid-run has not landed until the run is settled"
12108        );
12109
12110        stop.busy.store(0, Ordering::SeqCst);
12111        assert!(
12112            !stop.finishing(),
12113            "once the run is settled the stop has landed and there is nothing to finish"
12114        );
12115    }
12116
12117    #[test]
12118    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
12119        let stop = Stop::new();
12120        stop.busy.store(2, Ordering::SeqCst);
12121        stop.stop();
12122        assert!(stop.finishing(), "two runs still in flight");
12123
12124        stop.busy.store(1, Ordering::SeqCst);
12125        assert!(
12126            stop.finishing(),
12127            "one run finished, but a sibling is still working"
12128        );
12129
12130        stop.busy.store(0, Ordering::SeqCst);
12131        assert!(
12132            !stop.finishing(),
12133            "the last run out is what actually lands the stop"
12134        );
12135    }
12136
12137    #[tokio::test]
12138    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
12139        let dir = tempfile::tempdir().unwrap();
12140        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12141        let stop = Stop::new();
12142        stop.stop();
12143
12144        let began = std::time::Instant::now();
12145        tokio::time::timeout(
12146            Duration::from_secs(2),
12147            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12148        )
12149        .await
12150        .expect("a stopped loop must return, not sit out its poll interval")
12151        .expect("the loop's own setup and teardown must not fail");
12152        assert!(
12153            began.elapsed() < opts.poll,
12154            "returned only after {:?}, which is a poll interval, not a stop",
12155            began.elapsed()
12156        );
12157    }
12158
12159    #[tokio::test]
12160    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
12161        let dir = tempfile::tempdir().unwrap();
12162        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12163        let stop = Stop::new();
12164
12165        // Asked for after the loop is already parked on its empty queue, which
12166        // is the case an operator tapping stop on a phone actually hits.
12167        let asker = {
12168            let stop = stop.clone();
12169            tokio::spawn(async move {
12170                tokio::time::sleep(Duration::from_millis(20)).await;
12171                stop.stop();
12172            })
12173        };
12174
12175        let began = std::time::Instant::now();
12176        tokio::time::timeout(
12177            Duration::from_secs(2),
12178            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12179        )
12180        .await
12181        .expect("a stop asked for while idle must wake the wait")
12182        .expect("the loop's own setup and teardown must not fail");
12183        asker.await.unwrap();
12184        assert!(
12185            began.elapsed() < opts.poll,
12186            "returned only after {:?}, so the stop waited on the sleep",
12187            began.elapsed()
12188        );
12189    }
12190
12191    #[tokio::test]
12192    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
12193        let dir = tempfile::tempdir().unwrap();
12194        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12195        let stop = Stop::new();
12196        stop.stop();
12197
12198        tokio::time::timeout(
12199            Duration::from_secs(2),
12200            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12201        )
12202        .await
12203        .expect("a stopped loop must return")
12204        .expect("the loop's own setup and teardown must not fail");
12205
12206        assert!(
12207            home.is_dir(),
12208            "the loop did publish a status file, so its removal is the teardown and not an absence"
12209        );
12210        assert!(
12211            !status_file.exists(),
12212            "a stopped loop clears its status file"
12213        );
12214        assert!(
12215            read_status(&home).is_none(),
12216            "a reader must see no daemon at all, not a heartbeat that merely stopped"
12217        );
12218    }
12219
12220    #[tokio::test]
12221    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
12222        let dir = tempfile::tempdir().unwrap();
12223        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12224
12225        let mut settled = RunState::new(
12226            dir.path().join("repo"),
12227            "main".to_owned(),
12228            "abc1234".to_owned(),
12229            "fixture".to_owned(),
12230            Config::default(),
12231        );
12232        settled.status = RunStatus::Ready;
12233        let run_dir = home.join("runs").join(&settled.id);
12234        std::fs::create_dir_all(&run_dir).unwrap();
12235        std::fs::write(
12236            run_dir.join("run.json"),
12237            serde_json::to_string_pretty(&settled).unwrap(),
12238        )
12239        .unwrap();
12240        let questions = Questions::at(home.join("questions"));
12241        let mut question = ask::Question::new(
12242            settled.id.clone(),
12243            "review".to_owned(),
12244            "reviewer-1".to_owned(),
12245            "Continue?".to_owned(),
12246            String::new(),
12247            Vec::new(),
12248        );
12249        questions.put(&mut question).unwrap();
12250
12251        run_service_worker(
12252            &home,
12253            serde_json::to_value(ServiceWorker {
12254                opts,
12255                queue: queue.root().to_path_buf(),
12256                worktrees_root: worktrees,
12257                operation: "housekeeping".to_owned(),
12258            })
12259            .unwrap(),
12260        )
12261        .await
12262        .unwrap();
12263
12264        assert_eq!(
12265            questions.get(&question.id).unwrap().status,
12266            ask::QuestionStatus::Abandoned,
12267            "the independent housekeeping worker settles ended-run questions"
12268        );
12269    }
12270
12271    #[test]
12272    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
12273        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12274
12275        assert!(
12276            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
12277            "never checked before: due at once"
12278        );
12279
12280        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
12281        assert!(
12282            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
12283            "well inside the interval: not due yet"
12284        );
12285
12286        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
12287        assert!(
12288            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
12289            "exactly at the edge: not yet due, same convention as `clean::due`"
12290        );
12291
12292        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12293        assert!(
12294            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
12295            "past the interval: due again"
12296        );
12297    }
12298
12299    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
12300    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
12301    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
12302    /// and the congestion test below both need, and must not drift apart.
12303    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
12304        let config = dir.join("magi.toml");
12305        // A literal (single-quoted) TOML string, not a basic one: the cache
12306        // path is a Windows path full of backslashes, and a basic string
12307        // would have TOML try to interpret `\U` (from `\Users\...`) as a
12308        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
12309        // `{{ vars.cache }}` rendering documents.
12310        std::fs::write(
12311            &config,
12312            format!(
12313                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
12314                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
12315                cache_dir.display()
12316            ),
12317        )
12318        .unwrap();
12319        Opts {
12320            config: Some(config),
12321            repo: dir.join("repo"),
12322            ..Opts::default()
12323        }
12324    }
12325
12326    #[tokio::test]
12327    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
12328        let dir = tempfile::tempdir().unwrap();
12329        let home = dir.path().join("home");
12330        let cache_dir = dir.path().join("cache");
12331        std::fs::create_dir_all(&cache_dir).unwrap();
12332        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12333        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12334
12335        // Nobody has asked this daemon to stop, which is the ordinary case;
12336        // the skip that a stop buys is asserted by its own test below.
12337        let running = Stop::new();
12338        let mut last_checked = None;
12339        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12340        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
12341            .await;
12342        assert_eq!(
12343            crate::disk::dir_size(&cache_dir),
12344            0,
12345            "over the cap on the first check ever: pruned at once, no idle queue required"
12346        );
12347        assert_eq!(last_checked, Some(t0));
12348
12349        // A fresh oversized file lands, but the next check is not due yet.
12350        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
12351        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
12352        maybe_prune_cache_between_runs(
12353            &opts.repo,
12354            &opts,
12355            &home,
12356            &running,
12357            &mut last_checked,
12358            too_soon,
12359        )
12360        .await;
12361        assert_eq!(
12362            crate::disk::dir_size(&cache_dir),
12363            10,
12364            "too soon since the last check: left alone rather than rescanned every call"
12365        );
12366        assert_eq!(
12367            last_checked,
12368            Some(t0),
12369            "an idle check does not reset the clock"
12370        );
12371
12372        // Once the interval elapses, the same oversized cache is caught again.
12373        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12374        maybe_prune_cache_between_runs(
12375            &opts.repo,
12376            &opts,
12377            &home,
12378            &running,
12379            &mut last_checked,
12380            due_again,
12381        )
12382        .await;
12383        assert_eq!(
12384            crate::disk::dir_size(&cache_dir),
12385            0,
12386            "due again: pruned back under the cap"
12387        );
12388    }
12389
12390    /// A stop must not queue behind housekeeping. The prune below is a
12391    /// synchronous walk of the whole cache with no await point in it, so a
12392    /// loop that entered it could not get back to its own `stopped()` test
12393    /// until the walk finished - and because no run is in flight at this
12394    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
12395    /// the stop had already landed. The idle branch has always made this same
12396    /// check before reaching `janitor`; the between-runs path makes it too.
12397    #[tokio::test]
12398    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12399        let dir = tempfile::tempdir().unwrap();
12400        let home = dir.path().join("home");
12401        let cache_dir = dir.path().join("cache");
12402        std::fs::create_dir_all(&cache_dir).unwrap();
12403        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12404        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12405
12406        let stop = Stop::new();
12407        stop.stop();
12408        assert!(
12409            !stop.finishing(),
12410            "no run is in flight at a between-runs boundary, so nothing else \
12411             would tell the operator this stop had not taken effect yet"
12412        );
12413
12414        let mut last_checked = None;
12415        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12416        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12417            .await;
12418        assert_eq!(
12419            crate::disk::dir_size(&cache_dir),
12420            10,
12421            "over its cap, and due for the first check ever, but a stop outranks \
12422             it: the cap is a standing policy the next start measures again"
12423        );
12424        assert_eq!(
12425            last_checked, None,
12426            "a check that never happened must not claim the interval"
12427        );
12428    }
12429
12430    /// A backlog must not starve cache pruning. The finite cache worker runs
12431    /// independently of queue drain and must not consume any task attempts.
12432    #[tokio::test]
12433    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12434        let dir = tempfile::tempdir().unwrap();
12435        let cache_dir = dir.path().join("cache");
12436        std::fs::create_dir_all(&cache_dir).unwrap();
12437        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12438
12439        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12440        opts.poll = Duration::from_millis(20);
12441        opts.max_attempts = 1_000;
12442
12443        let queue = Queue::at(dir.path().join("queue"));
12444        for i in 0..128 {
12445            let mut task = Task::new(
12446                format!("queued work {i}"),
12447                format!("queued work {i}"),
12448                opts.repo.clone(),
12449                Source::Human,
12450            );
12451            queue.put(&mut task).unwrap();
12452        }
12453
12454        let home = dir.path().join("home");
12455        let worktrees = dir.path().join("wt");
12456        run_service_worker(
12457            &home,
12458            serde_json::to_value(ServiceWorker {
12459                opts,
12460                queue: queue.root().to_path_buf(),
12461                worktrees_root: worktrees,
12462                operation: "cache".to_owned(),
12463            })
12464            .unwrap(),
12465        )
12466        .await
12467        .unwrap();
12468        let after = queue.list();
12469        assert_eq!(after.len(), 128);
12470        assert!(
12471            after
12472                .iter()
12473                .all(|task| task.status.runnable() && task.attempts == 0)
12474        );
12475
12476        assert_eq!(
12477            crate::disk::dir_size(&cache_dir),
12478            0,
12479            "an oversized cache must not be left to grow unboundedly just because the \
12480             queue kept the loop busy the whole time"
12481        );
12482    }
12483
12484    #[test]
12485    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12486        let dir = tempfile::tempdir().unwrap();
12487        let queue = Queue::at(dir.path().join("queue"));
12488        let questions = Questions::at(dir.path().join("questions"));
12489        let mut task = task();
12490        queue.put(&mut task).unwrap();
12491
12492        let mut task_question = ask::Question::new(
12493            task.id.clone(),
12494            crate::conduct::NODE.to_owned(),
12495            "conduct".to_owned(),
12496            "Which backend?".to_owned(),
12497            String::new(),
12498            Vec::new(),
12499        );
12500        questions.put(&mut task_question).unwrap();
12501        task.block(vec![task_question.id.clone()], None);
12502        queue.put(&mut task).unwrap();
12503
12504        let mut run_question = ask::Question::new(
12505            "20260101-000000-run1".to_owned(),
12506            "review".to_owned(),
12507            "reviewer-1".to_owned(),
12508            "Run question".to_owned(),
12509            String::new(),
12510            Vec::new(),
12511        );
12512        questions.put(&mut run_question).unwrap();
12513
12514        // A question from another node whose `run` happens to equal this
12515        // task's id — the same field, filled in for an unrelated reason. Only
12516        // `crate::conduct::NODE` questions use `run` as a task id; this one
12517        // must never be touched by this reconciliation, even after release.
12518        let mut coincidental = ask::Question::new(
12519            task.id.clone(),
12520            "review".to_owned(),
12521            "reviewer-1".to_owned(),
12522            "Unrelated review question".to_owned(),
12523            String::new(),
12524            Vec::new(),
12525        );
12526        questions.put(&mut coincidental).unwrap();
12527
12528        reconcile_task_questions(&queue, &questions);
12529        assert!(questions.get(&task_question.id).unwrap().status.open());
12530        assert!(questions.get(&run_question.id).unwrap().status.open());
12531        assert!(questions.get(&coincidental.id).unwrap().status.open());
12532
12533        task.release();
12534        queue.put(&mut task).unwrap();
12535        reconcile_task_questions(&queue, &questions);
12536        assert_eq!(
12537            questions.get(&task_question.id).unwrap().status,
12538            ask::QuestionStatus::Abandoned
12539        );
12540        assert!(
12541            questions.get(&run_question.id).unwrap().status.open(),
12542            "run questions remain the run janitor's responsibility"
12543        );
12544        assert!(
12545            questions.get(&coincidental.id).unwrap().status.open(),
12546            "a non-conductor question must not be abandoned just because its \
12547             run id coincides with a task id"
12548        );
12549    }
12550
12551    #[test]
12552    fn a_freshly_started_running_task_is_never_stalled() {
12553        let dir = tempfile::tempdir().unwrap();
12554        let mut t = task();
12555        t.start("run-1".to_owned());
12556        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
12557        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
12558        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12559    }
12560
12561    #[test]
12562    fn a_long_running_task_with_no_live_daemon_is_stalled() {
12563        let dir = tempfile::tempdir().unwrap();
12564        let mut t = task();
12565        t.start("run-1".to_owned());
12566        t.updated_at = Timestamp::now()
12567            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12568        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12569        assert_eq!(
12570            stalled_tasks(
12571                &Queue::at(dir.path().join("q")),
12572                dir.path(),
12573                Timestamp::now()
12574            )
12575            .len(),
12576            0,
12577            "the task was never written to this queue"
12578        );
12579    }
12580
12581    #[test]
12582    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12583        let dir = tempfile::tempdir().unwrap();
12584        let mut t = task();
12585        t.id = "20260903-080340-0167".to_owned();
12586        t.start("20260903-080619-01c2".to_owned());
12587        t.updated_at = Timestamp::now()
12588            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12589
12590        let mut status = Status::new();
12591        status.current = vec![Current {
12592            worker: None,
12593            task: t.id.clone(),
12594            run: "20260903-080619-01c2".to_owned(),
12595        }];
12596        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12597
12598        assert!(
12599            !is_stalled(&t, dir.path(), Timestamp::now()),
12600            "a live daemon's own heartbeat rules out stalled, however long the task has run"
12601        );
12602    }
12603
12604    /// Rewrite a task's `updated_at` on disk directly, bypassing
12605    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
12606    /// a fixture look like it has genuinely been `running` for a while.
12607    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12608        let path = queue.path_of(id);
12609        let body = std::fs::read_to_string(&path).unwrap();
12610        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12611        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12612        v["updated_at"] = serde_json::Value::String(old.to_string());
12613        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12614    }
12615
12616    #[test]
12617    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12618        // The realistic `poll()` ordering, not `is_stalled` in isolation:
12619        // `reclaim_orphaned_running` runs first, on every poll, and settles
12620        // any `running` task whose claim it can actually take. For most
12621        // crashes that is immediate - a dead pid is proof enough for
12622        // `sweep_stale_claims` to drop the lock the same tick, and the very
12623        // next claim attempt succeeds. But a lock whose pid cannot be parsed
12624        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
12625        // `sweep_stale_claims`'s own doc), so the lock - and the claim
12626        // failure behind it - can legitimately outlive many polls. This is
12627        // exactly the gap `stalled_tasks` exists to surface well before that
12628        // six-hour sweep would: reclaim leaves the task `running`, and it
12629        // must still reach the conductor as stalled.
12630        let dir = tempfile::tempdir().unwrap();
12631        let queue = Queue::at(dir.path().join("queue"));
12632        let home = dir.path().join("home");
12633
12634        let mut t = task();
12635        t.id = "20260101-000001-lock".to_owned();
12636        t.start("run-1".to_owned());
12637        queue.put(&mut t).unwrap();
12638        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12639        std::fs::write(
12640            dir.path().join("queue").join(format!("{}.lock", t.id)),
12641            "not a pid",
12642        )
12643        .unwrap();
12644
12645        let now = Timestamp::now();
12646        assert!(
12647            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12648            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12649             and reclaim must leave the task alone"
12650        );
12651        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12652
12653        let stalled = stalled_tasks(&queue, &home, now);
12654        assert_eq!(
12655            stalled.len(),
12656            1,
12657            "reclaim's inability to claim it yet must not hide it from the conductor"
12658        );
12659        assert_eq!(stalled[0].id, t.id);
12660    }
12661
12662    #[test]
12663    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12664        let dir = tempfile::tempdir().unwrap();
12665        crate::run::set_home(dir.path().join("run-home"));
12666        let queue = Queue::at(dir.path().join("queue"));
12667        let home = dir.path().join("home");
12668        let questions = Questions::at(dir.path().join("questions"));
12669
12670        let mut t = task();
12671        t.id = "20260101-000003-dead".to_owned();
12672        t.start("missing-run".to_owned());
12673        queue.put(&mut t).unwrap();
12674        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12675
12676        // This is the real poll ordering: retain the deterministic stalled
12677        // input before a claim proves the owner is gone and reclaims it.
12678        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12679        assert_eq!(
12680            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12681            [&t.id]
12682        );
12683        assert_eq!(
12684            reclaim_orphaned_running(&queue, 2, &Default::default()),
12685            [t.id.clone()]
12686        );
12687        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12688
12689        // Reclaim drops its guard before conductor decisions are applied, so
12690        // the decision for the captured stalled input has a real write path.
12691        crate::conduct::apply(
12692            &queue,
12693            &questions,
12694            &crate::conduct::Verdict {
12695                decisions: vec![crate::conduct::Decision {
12696                    id: t.id.clone(),
12697                    recovery: Some(crate::conduct::Recovery::Requeue),
12698                    ..crate::conduct::Decision::default()
12699                }],
12700            },
12701        )
12702        .unwrap();
12703        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12704    }
12705
12706    #[test]
12707    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12708        let dir = tempfile::tempdir().unwrap();
12709        let queue = Queue::at(dir.path().join("queue"));
12710        let home = dir.path().join("home");
12711
12712        let mut fresh = task();
12713        fresh.id = "20260101-000001-aaaa".to_owned();
12714        fresh.start("run-1".to_owned());
12715        queue.put(&mut fresh).unwrap();
12716
12717        let mut old = task();
12718        old.id = "20260101-000002-bbbb".to_owned();
12719        old.start("run-2".to_owned());
12720        queue.put(&mut old).unwrap();
12721        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12722
12723        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12724        assert_eq!(stalled.len(), 1);
12725        assert_eq!(stalled[0].id, old.id);
12726    }
12727
12728    #[test]
12729    fn queued_and_finished_task_views_partition_by_status() {
12730        let dir = tempfile::tempdir().unwrap();
12731        let queue = Queue::at(dir.path().join("queue"));
12732
12733        let mut queued = task();
12734        queued.id = "20260101-000001-aaaa".to_owned();
12735        queue.put(&mut queued).unwrap();
12736
12737        let mut failed = task();
12738        failed.id = "20260101-000002-bbbb".to_owned();
12739        failed.start("run-1".to_owned());
12740        failed.fail("gate red", 5);
12741        queue.put(&mut failed).unwrap();
12742
12743        let mut held = task();
12744        held.id = "20260101-000003-cccc".to_owned();
12745        held.hold_machine(None);
12746        queue.put(&mut held).unwrap();
12747
12748        let mut running = task();
12749        running.id = "20260101-000004-dddd".to_owned();
12750        running.start("run-2".to_owned());
12751        queue.put(&mut running).unwrap();
12752
12753        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12754        assert_eq!(queued_ids, [queued.id.clone()]);
12755
12756        let mut finished_ids: Vec<String> =
12757            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12758        finished_ids.sort_unstable();
12759        let mut want = vec![failed.id.clone(), held.id.clone()];
12760        want.sort_unstable();
12761        assert_eq!(finished_ids, want);
12762    }
12763
12764    #[test]
12765    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12766        for short in [false, true] {
12767            let dir = tempfile::tempdir().unwrap();
12768            let queue = Queue::at(dir.path().join("queue"));
12769            let questions = ask::Questions::at(dir.path().join("questions"));
12770            let mut running = task();
12771            running.id = "20261013-192213-feb2".into();
12772            running.start("existing-run".into());
12773            queue.put(&mut running).unwrap();
12774            let mut middle = task();
12775            middle.id = "20261013-193611-ca5b".into();
12776            middle.block(
12777                vec![if short {
12778                    "feb2".into()
12779                } else {
12780                    running.id.clone()
12781                }],
12782                None,
12783            );
12784            queue.put(&mut middle).unwrap();
12785            let mut waiting = task();
12786            waiting.id = "20261013-202849-ee37".into();
12787            waiting.block(
12788                vec![if short {
12789                    "ca5b".into()
12790                } else {
12791                    middle.id.clone()
12792                }],
12793                Some("wait for implementation".into()),
12794            );
12795            queue.put(&mut waiting).unwrap();
12796            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12797            let inv = crate::blockers::Inventory::load(&queue, &questions);
12798            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12799            assert!(inv.stuck().is_empty());
12800            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12801            assert!(report.quarantined.is_empty());
12802            assert!(report.asked.is_empty());
12803            resolve_blockers(&queue, &questions);
12804            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12805            assert!(questions.list().is_empty());
12806            // Finishing the transitive prerequisite alone does not satisfy
12807            // the task's direct dependency.
12808            running.succeed(CompletionContext::new(
12809                CompletionActor::DaemonSettle,
12810                None,
12811                dir.path(),
12812                &running,
12813            ));
12814            queue.put(&mut running).unwrap();
12815            resolve_blockers(&queue, &questions);
12816            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12817            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12818            middle = queue.get(&middle.id).unwrap();
12819            middle.succeed(CompletionContext::new(
12820                CompletionActor::DaemonSettle,
12821                None,
12822                dir.path(),
12823                &middle,
12824            ));
12825            queue.put(&mut middle).unwrap();
12826            resolve_blockers(&queue, &questions);
12827            let after = queue.get(&waiting.id).unwrap();
12828            assert_eq!(after.status, TaskStatus::Queued);
12829            assert!(after.blocked_by.is_empty());
12830            assert_eq!(after.instruction, waiting.instruction);
12831        }
12832    }
12833
12834    #[test]
12835    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12836        for future_schema in [false, true] {
12837            let name = "20261013-193611-ca5b";
12838            let mut future = task();
12839            future.id = name.into();
12840            future.schema = crate::queue::SCHEMA + 1;
12841            let contents = if future_schema {
12842                serde_json::to_string(&future).unwrap()
12843            } else {
12844                "corrupt".into()
12845            };
12846            let dir = tempfile::tempdir().unwrap();
12847            let queue = Queue::at(dir.path().join("queue"));
12848            let questions = ask::Questions::at(dir.path().join("questions"));
12849            let mut waiting = task();
12850            waiting.id = "20261013-202849-ee37".into();
12851            waiting.block(vec!["ca5b".into()], None);
12852            queue.put(&mut waiting).unwrap();
12853            std::fs::write(queue.path_of(name), contents).unwrap();
12854            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12855            assert!(
12856                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12857            );
12858            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12859            assert!(report.asked.is_empty());
12860            resolve_blockers(&queue, &questions);
12861            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12862            assert!(questions.list().is_empty());
12863        }
12864        let dir = tempfile::tempdir().unwrap();
12865        let queue = Queue::at(dir.path().join("queue"));
12866        let questions = ask::Questions::at(dir.path().join("questions"));
12867        let mut waiting = task();
12868        waiting.id = "20261013-202849-ee37".into();
12869        waiting.block(vec!["ca5b".into()], None);
12870        queue.put(&mut waiting).unwrap();
12871        let mut done = task();
12872        done.id = "20261013-193611-ca5b".into();
12873        done.succeed(CompletionContext::new(
12874            CompletionActor::Cli,
12875            None,
12876            dir.path(),
12877            &done,
12878        ));
12879        queue.put(&mut done).unwrap();
12880        // An unreadable second match must not disappear from uniqueness
12881        // checks just because Queue::list skips it.
12882        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12883        assert!(queue.get("ca5b").is_err());
12884        assert_eq!(
12885            crate::queue::dependency(&queue, &questions, "ca5b"),
12886            crate::queue::Dependency::Ambiguous
12887        );
12888        resolve_blockers(&queue, &questions);
12889        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12890        assert!(report.asked.is_empty());
12891        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12892        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12893    }
12894
12895    #[test]
12896    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12897        for held in [false, true] {
12898            for question in [false, true] {
12899                for reference in ["ca5b", "20261013-193611-ca5b"] {
12900                    let dir = tempfile::tempdir().unwrap();
12901                    let queue = Queue::at(dir.path().join("queue"));
12902                    let questions = ask::Questions::at(dir.path().join("questions"));
12903                    let mut prerequisite = task();
12904                    prerequisite.id = "20261013-193611-ca5b".into();
12905                    prerequisite.start("existing-run".into());
12906                    queue.put(&mut prerequisite).unwrap();
12907                    let mut waiting = task();
12908                    waiting.id = "20261013-202849-ee37".into();
12909                    if held {
12910                        waiting.hold_machine(Some("waiting for separate consent".into()));
12911                    }
12912                    queue.put(&mut waiting).unwrap();
12913                    let reason = "Deleting saved data requires separate owner consent";
12914                    crate::conduct::apply(
12915                        &queue,
12916                        &questions,
12917                        &crate::conduct::Verdict {
12918                            decisions: vec![crate::conduct::Decision {
12919                                id: waiting.id.clone(),
12920                                blocked_by: vec![reference.into()],
12921                                question: question.then(|| "May the saved data be deleted?".into()),
12922                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12923                                reason: Some(reason.into()),
12924                                ..crate::conduct::Decision::default()
12925                            }],
12926                        },
12927                    )
12928                    .unwrap();
12929                    let before = queue.get(&waiting.id).unwrap();
12930                    if question {
12931                        assert_eq!(before.status, TaskStatus::Blocked);
12932                        let q = questions.get(&before.blocked_by[0]).unwrap();
12933                        assert_eq!(q.summary, "May the saved data be deleted?");
12934                        assert!(q.status.open());
12935                    } else {
12936                        assert_eq!(before.status, TaskStatus::Held);
12937                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12938                        assert!(recorded_reason.starts_with(reason));
12939                        if held {
12940                            assert!(recorded_reason.contains("waiting for separate consent"));
12941                        }
12942                    }
12943                    prerequisite.succeed(CompletionContext::new(
12944                        CompletionActor::DaemonSettle,
12945                        None,
12946                        dir.path(),
12947                        &prerequisite,
12948                    ));
12949                    queue.put(&mut prerequisite).unwrap();
12950                    resolve_blockers(&queue, &questions);
12951                    let after = queue.get(&waiting.id).unwrap();
12952                    assert_eq!(after.status, before.status);
12953                    assert_eq!(after.blocked_by, before.blocked_by);
12954                    assert_eq!(after.hold_reason, before.hold_reason);
12955                    assert_eq!(after.instruction, waiting.instruction);
12956                    if question {
12957                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12958                    }
12959                    assert!(
12960                        queue.next_runnable().is_none(),
12961                        "dependency completion is not consent"
12962                    );
12963                }
12964            }
12965        }
12966    }
12967
12968    #[test]
12969    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12970        let dir = tempfile::tempdir().unwrap();
12971        let queue = Queue::at(dir.path().join("queue"));
12972        let questions = ask::Questions::at(dir.path().join("questions"));
12973
12974        let mut dep = task();
12975        dep.id = "20260101-000001-dep0".to_owned();
12976        dep.succeed(CompletionContext::new(
12977            CompletionActor::DaemonSettle,
12978            None,
12979            dir.path(),
12980            &dep,
12981        ));
12982        queue.put(&mut dep).unwrap();
12983
12984        let mut still_going = task();
12985        still_going.id = "20260101-000002-dep1".to_owned();
12986        queue.put(&mut still_going).unwrap();
12987
12988        let mut blocked = task();
12989        blocked.id = "20260101-000003-main".to_owned();
12990        blocked.block(
12991            vec![dep.id.clone(), still_going.id.clone()],
12992            Some("waits on both".to_owned()),
12993        );
12994        queue.put(&mut blocked).unwrap();
12995
12996        resolve_blockers(&queue, &questions);
12997
12998        let after = queue.get(&blocked.id).unwrap();
12999        assert_eq!(
13000            after.status,
13001            TaskStatus::Blocked,
13002            "one dependency is still outstanding"
13003        );
13004        assert_eq!(after.blocked_by, [still_going.id.clone()]);
13005    }
13006
13007    #[test]
13008    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
13009        let dir = tempfile::tempdir().unwrap();
13010        let queue = Queue::at(dir.path().join("queue"));
13011        let questions = ask::Questions::at(dir.path().join("questions"));
13012
13013        let mut q = crate::ask::Question::new(
13014            "20260101-000001-main".to_owned(),
13015            crate::conduct::NODE.to_owned(),
13016            "conduct".to_owned(),
13017            "Which backend?".to_owned(),
13018            String::new(),
13019            Vec::new(),
13020        );
13021        questions.put(&mut q).unwrap();
13022        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
13023            .unwrap();
13024        questions.put(&mut q).unwrap();
13025
13026        let mut blocked = task();
13027        blocked.id = "20260101-000001-main".to_owned();
13028        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
13029        queue.put(&mut blocked).unwrap();
13030
13031        resolve_blockers(&queue, &questions);
13032
13033        let after = queue.get(&blocked.id).unwrap();
13034        assert_eq!(
13035            after.status,
13036            TaskStatus::Queued,
13037            "the only blocker resolved"
13038        );
13039        assert_eq!(after.answers.len(), 1);
13040        assert_eq!(after.answers[0].question, "Which backend?");
13041        assert_eq!(after.answers[0].answer, "SQLite");
13042
13043        // And the run this task starts next is told about it.
13044        let instruction = instruction_for(&after);
13045        assert!(instruction.contains("Which backend?"));
13046        assert!(instruction.contains("SQLite"));
13047    }
13048
13049    #[test]
13050    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
13051        let dir = tempfile::tempdir().unwrap();
13052        let queue = Queue::at(dir.path().join("queue"));
13053        let questions = ask::Questions::at(dir.path().join("questions"));
13054
13055        let mut q = crate::ask::Question::new(
13056            "20260101-000001-main".to_owned(),
13057            crate::conduct::NODE.to_owned(),
13058            "conduct".to_owned(),
13059            "Is the setup done?".to_owned(),
13060            String::new(),
13061            Vec::new(),
13062        );
13063        q.abandon("no answer within 60s of asking");
13064        questions.put(&mut q).unwrap();
13065
13066        let mut blocked = task();
13067        blocked.id = "20260101-000001-main".to_owned();
13068        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
13069        queue.put(&mut blocked).unwrap();
13070
13071        resolve_blockers(&queue, &questions);
13072
13073        let after = queue.get(&blocked.id).unwrap();
13074        assert_eq!(
13075            after.status,
13076            TaskStatus::Held,
13077            "never left blocked on nothing"
13078        );
13079        assert!(!after.operator_held(), "a machine hold, for triage");
13080        assert!(
13081            after
13082                .hold_reason
13083                .as_deref()
13084                .unwrap_or_default()
13085                .contains("went unanswered")
13086        );
13087    }
13088
13089    #[test]
13090    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
13091        // Reproduces the reported bug (task 3958): a task held out of
13092        // attempts, blocked on a `crate::conduct` follow-up question, must
13093        // come back `held` once that question is answered - never `queued`,
13094        // whatever the answer said - or it silently re-enters the
13095        // competition queue with its attempts already exhausted.
13096        let dir = tempfile::tempdir().unwrap();
13097        let queue = Queue::at(dir.path().join("queue"));
13098        let questions = ask::Questions::at(dir.path().join("questions"));
13099
13100        let mut q = crate::ask::Question::new(
13101            "20260101-000001-main".to_owned(),
13102            crate::conduct::NODE.to_owned(),
13103            "conduct".to_owned(),
13104            "How should this be handled?".to_owned(),
13105            String::new(),
13106            Vec::new(),
13107        );
13108        questions.put(&mut q).unwrap();
13109        q.answer(crate::ask::Answer::Text(
13110            "leave it held, a human will look at it later".to_owned(),
13111        ))
13112        .unwrap();
13113        questions.put(&mut q).unwrap();
13114
13115        let mut held = task();
13116        held.id = "20260101-000001-main".to_owned();
13117        held.hold_machine(Some("out of attempts".to_owned()));
13118        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
13119        queue.put(&mut held).unwrap();
13120
13121        resolve_blockers(&queue, &questions);
13122
13123        let after = queue.get(&held.id).unwrap();
13124        assert_eq!(after.status, TaskStatus::Held);
13125        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
13126        assert_eq!(
13127            after.answers[0].answer,
13128            "leave it held, a human will look at it later"
13129        );
13130    }
13131
13132    #[test]
13133    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
13134        let dir = tempfile::tempdir().unwrap();
13135        let queue = Queue::at(dir.path().join("queue"));
13136        let questions = ask::Questions::at(dir.path().join("questions"));
13137        let mut dep = task();
13138        dep.id = "20260101-000001-gone".to_owned();
13139        queue.put(&mut dep).unwrap();
13140        let mut blocked = task();
13141        blocked.id = "20260101-000003-main".to_owned();
13142        blocked.block(vec![dep.id.clone()], None);
13143        queue.put(&mut blocked).unwrap();
13144
13145        // Claimed, so `remove` cannot rewrite it and the resolver must.
13146        let claim = queue.claim(&blocked.id).unwrap();
13147        queue.remove(&dep.id, false, &questions).unwrap();
13148        drop(claim);
13149        resolve_blockers(&queue, &questions);
13150
13151        let after = queue.get(&blocked.id).unwrap();
13152        assert_eq!(after.status, TaskStatus::Queued);
13153        assert!(after.blocked_by.is_empty());
13154    }
13155
13156    #[test]
13157    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
13158        // Reproduces the reported bug: a task blocked on a task id that was
13159        // removed (`magi task rm`, or deleted by hand) can never see that id
13160        // reach `Done`, so the ordinary per-id loop has nothing to notice and
13161        // would otherwise leave the task `blocked` forever with no way for an
13162        // operator to find out why.
13163        let dir = tempfile::tempdir().unwrap();
13164        let queue = Queue::at(dir.path().join("queue"));
13165        let questions = ask::Questions::at(dir.path().join("questions"));
13166
13167        let mut still_going = task();
13168        still_going.id = "20260101-000002-dep1".to_owned();
13169        queue.put(&mut still_going).unwrap();
13170
13171        let mut blocked = task();
13172        blocked.id = "20260101-000003-main".to_owned();
13173        blocked.block(
13174            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
13175            Some("waits on both".to_owned()),
13176        );
13177        queue.put(&mut blocked).unwrap();
13178
13179        resolve_blockers(&queue, &questions);
13180
13181        let after = queue.get(&blocked.id).unwrap();
13182        assert_eq!(
13183            after.status,
13184            TaskStatus::Held,
13185            "a missing dependency must not leave the task blocked forever"
13186        );
13187        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
13188        assert!(after.blocked_by.is_empty());
13189        let reason = after.hold_reason.as_deref().unwrap_or_default();
13190        assert!(
13191            reason.contains("20260101-000001-gone"),
13192            "the missing id must be named so an operator can tell what happened: {reason}"
13193        );
13194        assert!(
13195            reason.contains(&still_going.id),
13196            "the still-valid dependency must not silently vanish from the record: {reason}"
13197        );
13198    }
13199
13200    #[test]
13201    fn instruction_for_is_unchanged_without_any_answers() {
13202        let t = task();
13203        assert_eq!(instruction_for(&t), t.instruction);
13204    }
13205
13206    #[test]
13207    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
13208        let dir = tempfile::tempdir().unwrap();
13209        let q = Queue::at(dir.path().join("queue"));
13210        let src = dir.path().join("shot.png");
13211        std::fs::write(&src, "x").unwrap();
13212        let mut t = task();
13213        q.attach(&mut t, &[src]).unwrap();
13214        let paths = task_attachments(&q, &t).unwrap();
13215        assert_eq!(paths.len(), 1);
13216        assert!(paths[0].is_absolute() && paths[0].is_file());
13217        std::fs::remove_file(&paths[0]).unwrap();
13218        let err = task_attachments(&q, &t).unwrap_err().to_string();
13219        assert!(err.contains("shot.png"), "{err}");
13220    }
13221
13222    #[tokio::test]
13223    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
13224        let dir = tempfile::tempdir().unwrap();
13225        let queue_path = dir.path().join("queue");
13226        let queue = Queue::at(queue_path.clone());
13227        let mut t = task();
13228        t.source = Source::Agent {
13229            run: "originating-chat".into(),
13230            node: crate::queue::CHAT_NODE.into(),
13231        };
13232        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
13233            stage: "config-fetch",
13234            target: "origin/main".into(),
13235        });
13236        record_config_failure(&mut t, &fetch);
13237        t.hold_machine(Some(format!("{fetch:#}")));
13238        let fetch_key = t.chat_notice_due().unwrap();
13239        t.chat_notices.push(fetch_key.clone());
13240        queue.put(&mut t).unwrap();
13241
13242        let queue = Queue::at(queue_path);
13243        let mut t = queue.get(&t.id).unwrap();
13244        let a = dir.path().join("a.toml");
13245        let b = dir.path().join("b.toml");
13246        for (path, text, new_cause) in [
13247            (&a, "[graph", true),
13248            (&a, "[verify", false),
13249            (&a, "[graph]\nimplementers = 'invalid-type'", true),
13250            (&b, "[graph]\nimplementers = 'invalid-type'", true),
13251        ] {
13252            t.release_operator("test", None);
13253            std::fs::write(path, text).unwrap();
13254            let error = Config::discover_fetched(dir.path(), Some(path))
13255                .await
13256                .unwrap_err();
13257            record_config_failure(&mut t, &error);
13258            t.hold_machine(Some(format!("{error:#}")));
13259            let due = t.chat_notice_due();
13260            assert_eq!(due.is_some(), new_cause, "{error:#}");
13261            if let Some(key) = due {
13262                assert_ne!(key, fetch_key);
13263                t.chat_notices.push(key);
13264            }
13265        }
13266        t.succeed(CompletionContext::new(
13267            CompletionActor::DaemonSettle,
13268            None,
13269            dir.path(),
13270            &t,
13271        ));
13272        assert_eq!(
13273            t.chat_notice_due(),
13274            Some(format!(
13275                "done:{}",
13276                t.completion_history.last().unwrap().occurrence
13277            ))
13278        );
13279    }
13280
13281    #[test]
13282    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
13283        let dir = tempfile::tempdir().unwrap();
13284        let queue_path = dir.path().join("queue");
13285        let queue = Queue::at(queue_path.clone());
13286        let mut t = task();
13287        t.source = crate::queue::Source::Agent {
13288            run: "originating-chat".into(),
13289            node: crate::queue::CHAT_NODE.into(),
13290        };
13291        let a = dir.path().join("a.png");
13292        let b = dir.path().join("b.png");
13293        std::fs::write(&a, "a").unwrap();
13294        std::fs::write(&b, "b").unwrap();
13295        queue.attach(&mut t, &[a, b]).unwrap();
13296        let paths = task_attachments(&queue, &t).unwrap();
13297        for path in &paths {
13298            std::fs::remove_file(path).unwrap();
13299        }
13300        let missing = task_attachments(&queue, &t).unwrap_err();
13301        t.attempts += 1;
13302        let reason = missing.to_string();
13303        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13304        let first = t.chat_notice_due().expect("first attachment notice");
13305        t.chat_notices.push(first.clone());
13306        queue.put(&mut t).unwrap();
13307
13308        let queue = Queue::at(queue_path.clone());
13309        let mut t = queue.get(&t.id).unwrap();
13310        assert!(t.chat_notice_due().is_none(), "restart does not replay");
13311        t.release_operator("test", None);
13312        t.attempts += 1;
13313        let missing = task_attachments(&queue, &t).unwrap_err();
13314        t.fail_startup_target(
13315            "startup-attachments",
13316            missing.name,
13317            "same missing attachment with regenerated wording",
13318            1,
13319        );
13320        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
13321
13322        std::fs::write(&paths[0], "restored").unwrap();
13323        t.release_operator("test", None);
13324        t.attempts += 1;
13325        let missing = task_attachments(&queue, &t).unwrap_err();
13326        let reason = missing.to_string();
13327        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13328        let second = t
13329            .chat_notice_due()
13330            .expect("different attachment must notify");
13331        assert_ne!(first, second);
13332        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
13333    }
13334
13335    #[test]
13336    fn resumed_instruction_is_unchanged_without_any_answers() {
13337        let t = task();
13338        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
13339    }
13340
13341    #[test]
13342    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
13343        let mut t = task();
13344        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13345        // The run's own instruction on disk predates the answer: it is the
13346        // plain original text `Runner::start` saved before the operator was
13347        // ever asked anything.
13348        let old = t.instruction.clone();
13349
13350        let refreshed = resumed_instruction(&old, &t);
13351        assert!(refreshed.starts_with(&old), "the original text is kept");
13352        assert!(refreshed.contains("Which backend?"));
13353        assert!(refreshed.contains("SQLite"));
13354    }
13355
13356    #[test]
13357    fn resumed_instruction_keeps_an_original_answers_heading() {
13358        let mut t = task();
13359        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
13360        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13361
13362        let refreshed = resumed_instruction(&t.instruction, &t);
13363
13364        assert!(
13365            refreshed.starts_with(&t.instruction),
13366            "an answers heading in the original instruction is not the appended block"
13367        );
13368        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
13369        assert!(refreshed.contains("Which backend?"));
13370        assert!(refreshed.contains("SQLite"));
13371
13372        let repeated = resumed_instruction(&refreshed, &t);
13373        assert_eq!(
13374            repeated, refreshed,
13375            "only the final appended block is refreshed"
13376        );
13377    }
13378
13379    #[test]
13380    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
13381        let mut t = task();
13382        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13383
13384        // A first resume appends the block; a second resume of the same run,
13385        // with no new answer in between, must reproduce exactly the same
13386        // text rather than appending the block a second time.
13387        let once = resumed_instruction(&t.instruction, &t);
13388        let twice = resumed_instruction(&once, &t);
13389        assert_eq!(once, twice);
13390        assert_eq!(once.matches("Which backend?").count(), 1);
13391
13392        // A later answer replaces the block wholesale rather than growing it.
13393        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13394        let refreshed = resumed_instruction(&once, &t);
13395        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13396        assert!(refreshed.contains("Which backend?"));
13397        assert!(refreshed.contains("Which cache?"));
13398    }
13399
13400    #[test]
13401    fn prepare_instruction_covers_all_three_starters() {
13402        let mut t = task();
13403        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13404
13405        // Start: a fresh run gets the task text plus every answer so far —
13406        // exactly `instruction_for`.
13407        assert_eq!(
13408            prepare_instruction(&Starter::Start, None, &t),
13409            Some(instruction_for(&t))
13410        );
13411
13412        // Resume: the run's prior instruction is refreshed with the answer,
13413        // not discarded and not left stale.
13414        let old = t.instruction.clone();
13415        assert_eq!(
13416            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13417            Some(resumed_instruction(&old, &t))
13418        );
13419
13420        // Review: a review-only pass builds its own instruction from the
13421        // branch's history in `crate::graph`, with no task statement at all -
13422        // this boundary must leave it alone.
13423        assert_eq!(
13424            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13425            None
13426        );
13427    }
13428
13429    #[test]
13430    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13431        assert_eq!(
13432            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13433            Starter::Review("magi/eba2/A".to_owned())
13434        );
13435    }
13436
13437    #[test]
13438    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13439        assert_eq!(
13440            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13441            Starter::Start,
13442            "a vanished review branch must not fall back to resuming the old run either"
13443        );
13444    }
13445
13446    #[test]
13447    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13448        let mut t = task();
13449        t.start("old-run".to_owned());
13450        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13451        t.release();
13452        let branch = t.review_branch.take();
13453        assert_eq!(
13454            choose_starter(branch.as_deref(), true, Some("old-run")),
13455            Starter::Review("magi/eba2/A".to_owned()),
13456            "a review wins over resuming the old run"
13457        );
13458    }
13459
13460    #[test]
13461    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13462        assert_eq!(
13463            choose_starter(None, false, Some("some-run")),
13464            Starter::Resume("some-run".to_owned())
13465        );
13466        assert_eq!(choose_starter(None, false, None), Starter::Start);
13467    }
13468
13469    #[test]
13470    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13471        let mut released = task();
13472        released.start("stalled-run".to_owned());
13473        released.requeue();
13474        let unfinished = (!released.fresh_start)
13475            .then(|| Some("stalled-run".to_owned()))
13476            .flatten();
13477        assert_eq!(
13478            choose_starter(None, false, unfinished.as_deref()),
13479            Starter::Start,
13480            "release keeps run history but must not resume it"
13481        );
13482        assert_eq!(released.runs, ["stalled-run"]);
13483    }
13484
13485    #[test]
13486    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13487        let dir = tempfile::tempdir().unwrap();
13488        let queue = Queue::at(dir.path().join("queue"));
13489        let mut state = run_state(RunStatus::Blocked);
13490        state.merge_decision = Some(crate::merge_decision::Decision {
13491            question: "hold-inquiry".into(),
13492            target: crate::merge_decision::Target {
13493                pr: "https://example.test/pull/1".into(),
13494                head: "reviewed-head".into(),
13495                language: "en".into(),
13496            },
13497            choice: land::HOLD.into(),
13498            closed: false,
13499            replacement_run: None,
13500            replacement_pr: None,
13501        });
13502        let mut t = task();
13503        t.start(state.id.clone());
13504        settle_and_diagnose(
13505            &mut t,
13506            Verdict {
13507                status: RunStatus::Blocked,
13508                left_pr: true,
13509                quota_hit: false,
13510                parked: false,
13511                no_viable_candidates: false,
13512            },
13513            "held",
13514            2,
13515            &state,
13516        );
13517        queue.put(&mut t).unwrap();
13518        t.release_operator("chat", None);
13519        t.edit("revised".into(), "revised instruction".into())
13520            .unwrap();
13521        queue.put(&mut t).unwrap();
13522        drop(state);
13523        assert_eq!(
13524            queue
13525                .get(&t.id)
13526                .unwrap()
13527                .decision_effects
13528                .get("hold-inquiry"),
13529            Some(&format!("decision: {}", land::HOLD))
13530        );
13531    }
13532
13533    fn stopped_public_run(status: RunStatus) -> RunState {
13534        let mut state = run_state(status);
13535        state.driver_exited = true;
13536        state.config.graph.land = true;
13537        state.config.graph.review_rounds = 1;
13538        state.reviews = vec![review_round(1)];
13539        state.merge = Some(crate::run::MergeOutcome {
13540            mode: MergeMode::Pr,
13541            ok: false,
13542            detail: "landing stopped".into(),
13543            empty: false,
13544        });
13545        state.pr = Some(crate::run::PrRecord {
13546            url: "https://example.test/pull/1".into(),
13547            number: 1,
13548            state: "open".into(),
13549            checks: "red".into(),
13550            round: 1,
13551            rounds: 1,
13552            red_at_merge: Vec::new(),
13553        });
13554        state
13555    }
13556
13557    #[test]
13558    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13559        for status in [RunStatus::Blocked, RunStatus::Gating] {
13560            let home = tempfile::tempdir().unwrap();
13561            let mut state = stopped_public_run(status);
13562            state.save_under(home.path()).unwrap();
13563            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13564            assert!(!exhausted_review_budget(&state));
13565            let mut task = held_task_with(&state.id);
13566            task.release();
13567            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13568            assert_eq!(
13569                choose_starter(None, false, unfinished.as_deref()),
13570                Starter::Resume(state.id.clone())
13571            );
13572            let question = action_question(&state.id, resume_action(&state.id));
13573            assert_eq!(
13574                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13575                    state.clone()
13576                )),
13577                ActionDecision::Resume(state.id.clone())
13578            );
13579            // The control-plane command uses this same preflight before pinning.
13580            assert_eq!(
13581                crate::resume::validate(home.path(), &state.id).unwrap().id,
13582                state.id
13583            );
13584            let queue = Queue::at(home.path().join("queue"));
13585            let mut controlled = Task::new(
13586                "resume land".into(),
13587                state.instruction.clone(),
13588                state.repo.clone(),
13589                Source::Agent {
13590                    run: "talk".into(),
13591                    node: crate::queue::CHAT_NODE.into(),
13592                },
13593            );
13594            controlled.runs.push(state.id.clone());
13595            controlled.hold_machine(Some("land stopped".into()));
13596            queue.put(&mut controlled).unwrap();
13597            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13598            assert_eq!(resumed.status, TaskStatus::Queued);
13599            assert_eq!(
13600                resumed.resume_override.unwrap().pinned_run,
13601                Some(state.id.clone())
13602            );
13603            assert_eq!(resumed.attempts, 0);
13604        }
13605    }
13606
13607    #[test]
13608    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13609        for review_rounds in [0, 1] {
13610            let home = tempfile::tempdir().unwrap();
13611            let mut state = run_state(RunStatus::Blocked);
13612            state.config.graph.review_rounds = review_rounds;
13613            if review_rounds > 0 {
13614                let mut review = review_round(1);
13615                review.clean = true;
13616                state.reviews = vec![review];
13617            }
13618            state.gate_ran = true;
13619            state.gate = vec![crate::run::CommandOutcome {
13620                command: "verify".into(),
13621                code: Some(1),
13622                output_tail: "gate failed after repair budget exhausted".into(),
13623                duration_ms: 0,
13624                resource_blocked: false,
13625                ..Default::default()
13626            }];
13627            state.save_under(home.path()).unwrap();
13628            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13629            assert!(exhausted_review_budget(&state));
13630            let mut task = held_task_with(&state.id);
13631            task.release();
13632            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13633            let question = action_question(&state.id, resume_action(&state.id));
13634            assert_ne!(
13635                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13636                    state.clone()
13637                )),
13638                ActionDecision::Resume(state.id.clone())
13639            );
13640            let error = crate::resume::validate(home.path(), &state.id)
13641                .unwrap_err()
13642                .to_string();
13643            assert!(!error.contains("review budget exhausted"), "{error}");
13644            assert!(
13645                error.contains(if review_rounds == 0 {
13646                    "review is disabled"
13647                } else {
13648                    "gate already ran"
13649                }),
13650                "{error}"
13651            );
13652
13653            // An unexecuted gate still has work to do with or without reviews.
13654            state.gate_ran = false;
13655            state.gate.clear();
13656            assert!(!exhausted_review_budget(&state));
13657            assert_eq!(
13658                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13659                Some(state.id)
13660            );
13661        }
13662    }
13663
13664    #[test]
13665    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
13666        let home = tempfile::tempdir().unwrap();
13667        let mut state = run_state(RunStatus::Blocked);
13668        state.config.graph.review_rounds = 1;
13669        let mut unresolved = review_round(1);
13670        unresolved.blocking = 1;
13671        unresolved.e2e.push(crate::run::CommandOutcome {
13672            command: "verify".into(),
13673            code: Some(1),
13674            output_tail: "previous verification failed".into(),
13675            duration_ms: 0,
13676            resource_blocked: false,
13677            artifact: None,
13678            failure_evidence: None,
13679            rerun_comparison: None,
13680        });
13681        state.reviews.push(unresolved);
13682        state.base_sync = Some(crate::run::BaseSync {
13683            tip: "base".into(),
13684            behind: 1,
13685            attempts: 0,
13686            conflict: None,
13687            already_in: None,
13688        });
13689        state.reserve_base_operation("winner", "base");
13690        state.resource_block = Some(crate::run::ResourceBlock {
13691            cause: crate::run::ResourceBlockCause::Other,
13692            node: "rebase".into(),
13693            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
13694            detail: "recording exec failed".into(),
13695            at: jiff::Timestamp::now(),
13696        });
13697        state.save_under(home.path()).unwrap();
13698        assert_eq!(
13699            crate::resume::validate(home.path(), &state.id).unwrap().id,
13700            state.id
13701        );
13702        assert_eq!(
13703            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
13704            crate::repair_budget::legacy::Class::SequencerInfrastructure
13705        );
13706        state.finish_base_operation(None);
13707        state.save_under(home.path()).unwrap();
13708        assert!(crate::resume::validate(home.path(), &state.id).is_err());
13709    }
13710
13711    #[test]
13712    fn resource_blocked_verification_resumes_the_same_run() {
13713        for (kind, stage) in [
13714            ("cache", "clean"),
13715            ("coordination", "clean"),
13716            ("cache", "review-e2e"),
13717            ("coordination", "no-reviews"),
13718            ("coordination", "handoff"),
13719        ] {
13720            let home = tempfile::tempdir().unwrap();
13721            let mut state = run_state(RunStatus::Blocked);
13722            state.config.graph.review_rounds = 1;
13723            let mut review = review_round(1);
13724            review.clean = true;
13725            state.reviews = vec![review];
13726            if stage == "review-e2e" {
13727                let review = &mut state.reviews[0];
13728                review.clean = false;
13729                review.blocking = 1;
13730                review.e2e = vec![crate::run::CommandOutcome {
13731                    command: "verify".into(),
13732                    code: None,
13733                    output_tail: "resource wait expired".into(),
13734                    duration_ms: 0,
13735                    resource_blocked: true,
13736                    ..Default::default()
13737                }];
13738            } else if stage == "no-reviews" {
13739                state.config.graph.review_rounds = 0;
13740                state.reviews.clear();
13741            } else if stage == "handoff" {
13742                // A completed final verification can hand off to the gate
13743                // even when the review still carries contested findings.
13744                let review = &mut state.reviews[0];
13745                review.clean = false;
13746                review.blocking = 1;
13747                review.e2e = vec![crate::run::CommandOutcome {
13748                    command: "verify".into(),
13749                    code: Some(0),
13750                    output_tail: String::new(),
13751                    duration_ms: 0,
13752                    resource_blocked: false,
13753                    ..Default::default()
13754                }];
13755            }
13756            state.gate_ran = false;
13757            state.resource_block = Some(crate::run::ResourceBlock {
13758                cause: crate::run::ResourceBlockCause::Other,
13759                node: if stage == "review-e2e" {
13760                    "review"
13761                } else {
13762                    "gate"
13763                }
13764                .into(),
13765                kind: kind.into(),
13766                detail: "resource wait expired".into(),
13767                at: jiff::Timestamp::now(),
13768            });
13769            state.save_under(home.path()).unwrap();
13770            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13771            assert!(!exhausted_review_budget(&state));
13772            let mut task = held_task_with(&state.id);
13773            task.release();
13774            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13775            assert_eq!(
13776                choose_starter(None, false, unfinished.as_deref()),
13777                Starter::Resume(state.id.clone())
13778            );
13779            let question = action_question(&state.id, resume_action(&state.id));
13780            assert_eq!(
13781                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13782                    state.clone()
13783                )),
13784                ActionDecision::Resume(state.id.clone())
13785            );
13786            assert_eq!(
13787                crate::resume::validate(home.path(), &state.id).unwrap().id,
13788                state.id
13789            );
13790            let queue = Queue::at(home.path().join("queue"));
13791            let mut controlled = Task::new(
13792                "resume verification".into(),
13793                state.instruction.clone(),
13794                state.repo.clone(),
13795                Source::Agent {
13796                    run: "talk".into(),
13797                    node: crate::queue::CHAT_NODE.into(),
13798                },
13799            );
13800            controlled.runs.push(state.id.clone());
13801            controlled.hold_machine(Some("verification resource unavailable".into()));
13802            queue.put(&mut controlled).unwrap();
13803            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13804            assert_eq!(resumed.status, TaskStatus::Queued);
13805            assert_eq!(
13806                resumed.resume_override.unwrap().pinned_run,
13807                Some(state.id.clone())
13808            );
13809            assert_eq!(resumed.attempts, 0);
13810
13811            // A genuinely unresolved final review still exhausts the budget.
13812            state.config.graph.review_rounds = 1;
13813            let mut unresolved = review_round(1);
13814            unresolved.blocking = 1;
13815            state.reviews = vec![unresolved];
13816            state.resource_block = None;
13817            state.save_under(home.path()).unwrap();
13818            assert!(exhausted_review_budget(&state));
13819            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13820        }
13821    }
13822
13823    #[tokio::test]
13824    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13825        if !crate::standalone_test(
13826            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13827        ) {
13828            return;
13829        }
13830        let home = tempfile::tempdir().unwrap();
13831        let mut owner = stopped_public_run(RunStatus::Blocked);
13832        owner.save_under(home.path()).unwrap();
13833        let history = vec![owner.id.clone()];
13834        let repo = owner.repo.clone();
13835        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13836        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13837        let initial =
13838            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13839        assert!(
13840            initial.is_pending(),
13841            "a busy record must not hold or resume the task"
13842        );
13843        owner.retired_to = Some("20260101-000001-bbbb".into());
13844        owner.save_under(home.path()).unwrap();
13845        drop(lock);
13846        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13847            .await
13848            .expect("ownership lock released")
13849            .expect("read settled owner");
13850        assert!(
13851            result.is_none(),
13852            "the retired owner must not be resumed from a stale read"
13853        );
13854    }
13855
13856    #[tokio::test]
13857    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13858        if !crate::standalone_test(
13859            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13860        ) {
13861            return;
13862        }
13863        let home = tempfile::tempdir().unwrap();
13864        let mut owner = stopped_public_run(RunStatus::Blocked);
13865        let repo = tempfile::tempdir().unwrap();
13866        crate::git::git(repo.path(), &["init"]).await.unwrap();
13867        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13868        owner.id = "20260101-000000-aaaa".into();
13869        owner.save_under(home.path()).unwrap();
13870        let mut successor = run_state(RunStatus::Blocked);
13871        successor.id = "20260101-000001-bbbb".into();
13872        successor.save_under(home.path()).unwrap();
13873        let runs = vec![owner.id.clone(), successor.id.clone()];
13874        assert_eq!(
13875            public_resume_owner(home.path(), &runs, &owner.repo)
13876                .await
13877                .unwrap()
13878                .unwrap()
13879                .id,
13880            owner.id
13881        );
13882        let subdir = owner.repo.join("nested");
13883        std::fs::create_dir(&subdir).unwrap();
13884        assert_eq!(
13885            public_resume_owner(home.path(), &runs, &subdir)
13886                .await
13887                .unwrap()
13888                .unwrap()
13889                .id,
13890            owner.id
13891        );
13892        #[cfg(unix)]
13893        {
13894            let alias = home.path().join("repo-alias");
13895            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13896            assert_eq!(
13897                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13898                    .await
13899                    .unwrap()
13900                    .unwrap()
13901                    .id,
13902                owner.id
13903            );
13904        }
13905        let different = tempfile::tempdir().unwrap();
13906        crate::git::git(different.path(), &["init"]).await.unwrap();
13907        assert!(
13908            public_resume_owner(home.path(), &runs, different.path())
13909                .await
13910                .is_err()
13911        );
13912        std::fs::remove_file(
13913            home.path()
13914                .join("runs")
13915                .join(&successor.id)
13916                .join("run.json"),
13917        )
13918        .unwrap();
13919        assert!(
13920            public_resume_owner(home.path(), &runs, &owner.repo)
13921                .await
13922                .is_err()
13923        );
13924    }
13925
13926    #[test]
13927    fn an_ordinary_release_keeps_a_resumable_run_available() {
13928        let mut released = task();
13929        released.start("stalled-run".to_owned());
13930        released.release();
13931        let unfinished = (!released.fresh_start)
13932            .then(|| Some("stalled-run".to_owned()))
13933            .flatten();
13934        assert_eq!(
13935            choose_starter(None, false, unfinished.as_deref()),
13936            Starter::Resume("stalled-run".to_owned()),
13937            "manual release must preserve the normal resume path"
13938        );
13939    }
13940
13941    #[test]
13942    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13943        use crate::handover::{ResumeRefusal, resume_refusal_under};
13944        let home = tempfile::tempdir().unwrap();
13945        let mut exhausted = run_state(RunStatus::Blocked);
13946        exhausted.driver_exited = true;
13947        exhausted.config.graph.review_rounds = 3;
13948        exhausted.reviews = (1..=3).map(review_round).collect();
13949        for refusal in [
13950            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13951            ResumeRefusal::Status(RunStatus::Ready),
13952            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13953            ResumeRefusal::Retired("retirement-successor".into()),
13954            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13955        ] {
13956            let mut state = exhausted.clone();
13957            let expected = match refusal {
13958                ResumeRefusal::Status(_) => {
13959                    state.status = RunStatus::Ready;
13960                    "status `ready`"
13961                }
13962                ResumeRefusal::Released(ref target) => {
13963                    state.released_to = Some(target.clone());
13964                    "execution was released"
13965                }
13966                ResumeRefusal::Retired(ref target) => {
13967                    state.retired_to = Some(target.clone());
13968                    "execution was retired"
13969                }
13970                ResumeRefusal::OwnershipTransferred(ref target) => {
13971                    state.pr_taken_over_by = Some(target.clone());
13972                    "PR ownership was transferred"
13973                }
13974                _ => "review budget exhausted (3/3 rounds used)",
13975            };
13976            assert_eq!(
13977                resume_refusal_under(&state, Some(home.path())),
13978                Some(refusal.clone())
13979            );
13980            assert_eq!(
13981                refusal.successor(),
13982                state
13983                    .released_to
13984                    .as_deref()
13985                    .or(state.retired_to.as_deref())
13986                    .or(state.pr_taken_over_by.as_deref())
13987            );
13988            state.save_under(home.path()).unwrap();
13989            let queue = Queue::at(home.path().join("queue"));
13990            let mut task = Task::new(
13991                "retained implementation".into(),
13992                state.instruction.clone(),
13993                state.repo.clone(),
13994                Source::Agent {
13995                    run: "talk".into(),
13996                    node: crate::queue::CHAT_NODE.into(),
13997                },
13998            );
13999            task.runs.push(state.id.clone());
14000            task.hold_machine(Some("stopped".into()));
14001            queue.put(&mut task).unwrap();
14002            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
14003            let before_run = serde_json::to_value(&state).unwrap();
14004            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
14005                .unwrap_err()
14006                .to_string();
14007            assert!(error.contains(expected), "{error}");
14008            assert!(!error.contains("only a stalled or blocked"), "{error}");
14009            if matches!(refusal, ResumeRefusal::Status(_)) {
14010                assert!(
14011                    error.contains("is final; there is nothing left to resume"),
14012                    "{error}"
14013                );
14014            }
14015            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
14016                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
14017                assert!(error.contains("review-only successor with a new review budget"));
14018                assert!(error.contains("does not resume this run"));
14019            }
14020            for target in [
14021                &state.released_to,
14022                &state.retired_to,
14023                &state.pr_taken_over_by,
14024            ]
14025            .into_iter()
14026            .flatten()
14027            {
14028                let short = if state.retired_to.as_ref() == Some(target) {
14029                    target.as_str()
14030                } else {
14031                    crate::run::short_of(target)
14032                };
14033                assert!(
14034                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
14035                    "{error}"
14036                );
14037                if short != target {
14038                    assert!(!error.contains(target), "full successor id leaked: {error}");
14039                }
14040            }
14041            assert_eq!(
14042                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
14043                before_task
14044            );
14045            assert_eq!(
14046                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
14047                    .unwrap(),
14048                before_run
14049            );
14050            let question = action_question(&state.id, resume_action(&state.id));
14051            for phrases in [&PHRASES_EN, &PHRASES_JA] {
14052                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
14053                    RunState::load_under(id, home.path())
14054                });
14055                let ActionDecision::Refuse(detail) = decision else {
14056                    panic!(
14057                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
14058                        state.id,
14059                        home.path().display()
14060                    );
14061                };
14062                assert!(detail.contains(expected), "{detail}");
14063            }
14064        }
14065        // Preserve predicate ordering, while keeping every recorded destination visible.
14066        exhausted.status = RunStatus::Ready;
14067        exhausted.released_to = Some("released".into());
14068        exhausted.retired_to = Some("retired".into());
14069        exhausted.pr_taken_over_by = Some("owner".into());
14070        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
14071        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
14072        let detail = reason.diagnostic(&exhausted);
14073        for target in ["released", "retired", "owner"] {
14074            assert!(detail.contains(&format!("magi show {target}")));
14075        }
14076    }
14077
14078    #[test]
14079    fn resume_action_ignores_question_checkpoints_in_another_home() {
14080        crate::run::pin_test_home();
14081        let home = tempfile::tempdir().unwrap();
14082        let mut state = run_state(RunStatus::Blocked);
14083        // The private directory reserves this fixture's identity even while
14084        // other tests write questions into the process-wide store.
14085        state.id = format!(
14086            "resume-context-{}",
14087            home.path().file_name().unwrap().to_str().unwrap()
14088        );
14089        state.driver_exited = true;
14090        state.config.graph.review_rounds = 1;
14091        state.reviews = vec![review_round(1)];
14092        state.save_under(home.path()).unwrap();
14093        let task = held_task_with(&state.id);
14094        let answer = action_question(&state.id, resume_action(&state.id));
14095        let mut checkpoint = approval_question(&state.id);
14096        let foreign = Questions::open();
14097        foreign.put(&mut checkpoint).unwrap();
14098        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
14099        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
14100            RunState::load_under(id, home.path())
14101        });
14102        let matching: Vec<_> = foreign
14103            .list()
14104            .into_iter()
14105            .filter(|q| q.run == state.id && q.status.open())
14106            .collect();
14107        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
14108        assert!(
14109            matches!(decision, ActionDecision::Refuse(_)),
14110            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
14111            state.id,
14112            home.path().display(),
14113            crate::run::test_home().display()
14114        );
14115        assert_eq!(
14116            refusal,
14117            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
14118        );
14119        let local = Questions::at(home.path().join("questions"));
14120        for status in [
14121            ask::QuestionStatus::Open,
14122            ask::QuestionStatus::Answered,
14123            ask::QuestionStatus::Abandoned,
14124        ] {
14125            let mut question = checkpoint.clone();
14126            match status {
14127                ask::QuestionStatus::Open => {}
14128                ask::QuestionStatus::Answered => {
14129                    question
14130                        .answer(ask::Answer::Choice(question.choices[0].clone()))
14131                        .unwrap();
14132                }
14133                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
14134            }
14135            local.put(&mut question).unwrap();
14136            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
14137                RunState::load_under(id, home.path())
14138            });
14139            if status.open() {
14140                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
14141            } else {
14142                assert!(
14143                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
14144                    "status={status:?}, decision={decision:?}"
14145                );
14146            }
14147        }
14148    }
14149
14150    #[test]
14151    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
14152        let home = tempfile::tempdir().unwrap();
14153        let mut state = run_state(RunStatus::Stalled);
14154        state.id = format!(
14155            "resume-driver-{}",
14156            home.path().file_name().unwrap().to_str().unwrap()
14157        );
14158        state.driver_claimed = Some(false);
14159        state.save_under(home.path()).unwrap();
14160        let task = held_task_with(&state.id);
14161        let question = action_question(&state.id, resume_action(&state.id));
14162        let decide = || {
14163            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
14164                RunState::load_under(id, home.path())
14165            })
14166        };
14167        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
14168        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
14169        let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
14170        match decide() {
14171            ActionDecision::Refuse(detail) => {
14172                assert!(
14173                    detail.starts_with("run already has a live driver: "),
14174                    "{detail}"
14175                );
14176                assert!(
14177                    detail.contains(&expected_lock.display().to_string()),
14178                    "{detail}"
14179                );
14180            }
14181            other => panic!("expected live driver refusal, got {other:?}"),
14182        }
14183        drop(lease);
14184        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
14185    }
14186
14187    #[test]
14188    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
14189        let home = tempfile::tempdir().unwrap();
14190        let mut state = run_state(RunStatus::Blocked);
14191        state.driver_exited = true;
14192        state.config.graph.review_rounds = 1;
14193        state.reviews = vec![review_round(1)];
14194        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
14195        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
14196            let mut saved = state.clone();
14197            match checkpoint {
14198                "publication" => saved.pr_publication_pending = true,
14199                "approval" => {
14200                    saved.land_approval = Some(crate::run::LandApproval {
14201                        question: "approval".into(),
14202                        head: "head".into(),
14203                    })
14204                }
14205                "armed" => saved.land_armed_head = Some("head".into()),
14206                "landing" => saved.status = RunStatus::Landing,
14207                _ => {
14208                    let mut question = ask::Question::new(
14209                        saved.id.clone(),
14210                        "review".into(),
14211                        "review-1".into(),
14212                        "continue?".into(),
14213                        String::new(),
14214                        vec!["continue".into()],
14215                    );
14216                    ask::Questions::at(home.path().join("questions"))
14217                        .put(&mut question)
14218                        .unwrap();
14219                }
14220            }
14221            saved.save_under(home.path()).unwrap();
14222            assert!(
14223                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
14224                "{checkpoint}"
14225            );
14226            assert!(
14227                crate::resume::validate(home.path(), &saved.id).is_ok(),
14228                "{checkpoint}"
14229            );
14230        }
14231    }
14232
14233    #[test]
14234    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
14235        let mut state = run_state(RunStatus::Blocked);
14236        state.config.graph.review_rounds = 3;
14237        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
14238        assert!(exhausted_review_budget(&state));
14239
14240        // One round still unused: resuming can still ask a reviewer something.
14241        state.reviews.pop();
14242        assert!(!exhausted_review_budget(&state));
14243
14244        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
14245        // count: only a `Blocked` run re-enters the review loop on resume.
14246        let mut stalled = run_state(RunStatus::Stalled);
14247        stalled.config.graph.review_rounds = 1;
14248        stalled.reviews = vec![review_round(1)];
14249        assert!(!exhausted_review_budget(&stalled));
14250    }
14251
14252    fn review_round(round: usize) -> crate::run::ReviewRound {
14253        crate::run::ReviewRound {
14254            round,
14255            head: "deadbeef".to_owned(),
14256            verified_head: None,
14257            verified_at: None,
14258            reviews: Vec::new(),
14259            e2e: Vec::new(),
14260            verify_retried: false,
14261            e2e_deferred: false,
14262            e2e_defer_reason: None,
14263            fix: None,
14264            blocking: 0,
14265            answered: 1,
14266            expected: 1,
14267            clean: false,
14268            progressed: true,
14269            vote_split: false,
14270            reconsideration: Vec::new(),
14271            verdict: None,
14272        }
14273    }
14274
14275    #[test]
14276    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
14277        let mut run = RunState::new(
14278            PathBuf::from("/repo"),
14279            "main".to_owned(),
14280            "abc1234def".to_owned(),
14281            "add retries".to_owned(),
14282            Config::default(),
14283        );
14284        run.status = RunStatus::Judging;
14285        run.parked = true;
14286        let mut task = Task::new(
14287            "add retries".to_owned(),
14288            "add retries".to_owned(),
14289            PathBuf::from("/repo"),
14290            crate::queue::Source::Human,
14291        );
14292        task.status = TaskStatus::Failed;
14293        task.runs = vec![run.id.clone()];
14294        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
14295        assert!(with(&task, &run), "parked after judging is the case");
14296        let mut parked_task = task.clone();
14297        parked_task.status = TaskStatus::Parked;
14298        assert!(with(&parked_task, &run), "the Parked status is the case");
14299
14300        let mut not_parked = run.clone();
14301        not_parked.parked = false;
14302        not_parked.status = RunStatus::Stalled;
14303        assert!(!with(&task, &not_parked), "a stall is the conductor's");
14304
14305        let mut fresh = task.clone();
14306        fresh.fresh_start = true;
14307        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
14308
14309        let mut review = task.clone();
14310        review.review_branch = Some("magi/x/A".to_owned());
14311        assert!(!with(&review, &run), "review is ranked before resume");
14312
14313        let mut held = task.clone();
14314        held.status = TaskStatus::Held;
14315        assert!(!with(&held, &run), "a hold stays visible to the conductor");
14316
14317        let mut released = run.clone();
14318        released.released_to = Some("20260901-000000-new1".to_owned());
14319        assert!(!with(&task, &released), "nothing left to resume into");
14320
14321        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
14322            "unreadable"
14323        )));
14324    }
14325
14326    #[test]
14327    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
14328        let mut released = RunState::new(
14329            PathBuf::from("/repo"),
14330            "main".to_owned(),
14331            "abc1234def".to_owned(),
14332            "add retries".to_owned(),
14333            Config::default(),
14334        );
14335        released.status = RunStatus::Blocked;
14336        assert_eq!(
14337            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14338            Some(released.id.clone())
14339        );
14340        released.released_to = Some("20260901-000000-new1".to_owned());
14341        assert_eq!(
14342            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14343            None,
14344            "there is nothing left to resume it into"
14345        );
14346    }
14347
14348    #[test]
14349    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
14350        // Mirrors the failure this exists to close: a task's last run ended
14351        // `Blocked` with the review budget spent, `crate::conduct` chose
14352        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
14353        // evidence), and without this check `attempt` would go on treating
14354        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
14355        // review loop iterates zero times over an already-spent budget, so
14356        // the resumed run settles right back to `Blocked` having asked nobody
14357        // anything, and `Requeue`'s promised fresh competition never happens.
14358        let mut exhausted = RunState::new(
14359            PathBuf::from("/repo"),
14360            "main".to_owned(),
14361            "abc1234def".to_owned(),
14362            "add retries".to_owned(),
14363            Config::default(),
14364        );
14365        exhausted.status = RunStatus::Blocked;
14366        exhausted.config.graph.review_rounds = 1;
14367        exhausted.reviews = vec![review_round(1)];
14368
14369        assert_eq!(
14370            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
14371            None,
14372            "an exhausted `Blocked` run must not be offered as resumable"
14373        );
14374
14375        // A `Blocked` run with rounds still unused is genuinely worth
14376        // resuming, and must still be found.
14377        let mut has_budget_left = RunState::new(
14378            PathBuf::from("/repo"),
14379            "main".to_owned(),
14380            "abc1234def".to_owned(),
14381            "add retries".to_owned(),
14382            Config::default(),
14383        );
14384        has_budget_left.status = RunStatus::Blocked;
14385        has_budget_left.config.graph.review_rounds = 3;
14386        has_budget_left.reviews = vec![review_round(1)];
14387
14388        assert_eq!(
14389            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
14390                Ok(has_budget_left.clone())
14391            }),
14392            Some(has_budget_left.id.clone())
14393        );
14394    }
14395
14396    #[test]
14397    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
14398        let mut run = RunState::new(
14399            PathBuf::from("/repo"),
14400            "main".to_owned(),
14401            "abc1234def".to_owned(),
14402            "add retries".to_owned(),
14403            Config::default(),
14404        );
14405        run.status = RunStatus::Blocked;
14406        run.config.graph.review_rounds = 1;
14407        run.reviews = vec![review_round(1)];
14408        run.pr_publication_pending = true;
14409        assert_eq!(
14410            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
14411            Some(run.id.clone()),
14412            "a spent review budget must not turn a failed publication into a re-competition"
14413        );
14414    }
14415
14416    #[test]
14417    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
14418        let mut task = Task::new(
14419            "recover work".into(),
14420            "recover work".into(),
14421            PathBuf::from("/repo"),
14422            crate::queue::Source::Human,
14423        );
14424        let mut history = std::collections::BTreeMap::new();
14425        for index in 0..8 {
14426            let mut run = run_state(RunStatus::Blocked);
14427            run.id = format!("20260101-000000-{index:04}");
14428            run.base_commit = format!("upstream-{index}");
14429            // Seven empty newer attempts must not erase the old recovery owner.
14430            if index > 0 {
14431                run.candidates.clear();
14432            }
14433            task.runs.extend([run.id.clone(), run.id.clone()]);
14434            history.insert(run.id.clone(), run);
14435            task.requeue();
14436        }
14437        let check = |task: &Task, starter: &Starter, limit| {
14438            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
14439        };
14440        assert!(
14441            check(&task, &Starter::Start, 8)
14442                .unwrap()
14443                .contains("8 unretired")
14444        );
14445        assert!(check(&task, &Starter::Start, 9).is_none());
14446        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
14447        task.release_operator("owner", None);
14448        assert_eq!(task.attempts, 0);
14449        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14450        assert!(check(&restored, &Starter::Start, 8).is_some());
14451        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14452        assert!(check(&restored, &Starter::Start, 0).is_none());
14453    }
14454
14455    #[test]
14456    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14457        let tmp = tempfile::tempdir().unwrap();
14458        let mut task = Task::new(
14459            "recover selected PR".into(),
14460            "preserve implementation".into(),
14461            tmp.path().join("repo"),
14462            crate::queue::Source::Human,
14463        );
14464        let mut failed = run_state(RunStatus::Failed);
14465        failed.id = "20260101-000000-fail".into();
14466        failed.candidates.clear();
14467        failed.prep_complete = Some(false);
14468        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14469        failed.startup = Some(crate::run::Startup {
14470            kind: "pr-recovery".into(),
14471            branch: Some("selected-public-head".into()),
14472            stage: "worktree-setup".into(),
14473            complete: false,
14474            failure: Some("setup modified a tracked file and failed".into()),
14475        });
14476        // Setup may fail before a candidate is recorded; its dirty worktree
14477        // still needs protection and consumes the independent retained bound.
14478        let worktree = failed.worktree_root().join("under-review");
14479        std::fs::create_dir_all(&worktree).unwrap();
14480        let retained_edit = worktree.join("implementation");
14481        std::fs::write(&retained_edit, "retained setup edit").unwrap();
14482        task.record_startup_failure(crate::run::StartupFailure {
14483            run: failed.id.clone(),
14484            stage: "worktree-setup".into(),
14485        });
14486        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14487        assert!(task.runs.is_empty() && task.passes.is_empty());
14488        assert_eq!(task.attempts, 0);
14489        let starter = Starter::Review("selected-public-head".into());
14490        assert!(
14491            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14492                .unwrap()
14493                .contains("1 unretired")
14494        );
14495        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14496        assert!(
14497            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14498                .unwrap()
14499                .contains("Cannot verify")
14500        );
14501        // Older or mixed writers can link the same reservation in both lists.
14502        let mut mixed = task.clone();
14503        mixed.runs.push(failed.id.clone());
14504        mixed
14505            .startup_failures
14506            .push(task.startup_failures[0].clone());
14507        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14508        failed.retired_to = Some("verified-recovery-owner".into());
14509        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14510        assert!(
14511            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14512                panic!("resuming the existing owner must not allocate a new attempt")
14513            })
14514            .is_none()
14515        );
14516        assert_eq!(
14517            std::fs::read_to_string(retained_edit).unwrap(),
14518            "retained setup edit"
14519        );
14520        assert!(task.runs.is_empty() && task.passes.is_empty());
14521        assert_eq!(task.attempts, 0);
14522    }
14523
14524    #[test]
14525    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14526        let mut task = Task::new(
14527            "recover work".into(),
14528            "recover work".into(),
14529            PathBuf::from("/repo"),
14530            crate::queue::Source::Human,
14531        );
14532        let mut run = run_state(RunStatus::Superseded);
14533        run.candidates.clear();
14534        task.runs.push(run.id.clone());
14535        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14536        run.retired_to = Some("authority".into());
14537        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14538        run.retired_to = None;
14539        run.released_to = Some("authority".into());
14540        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14541        assert!(
14542            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14543                .unwrap()
14544                .contains("Cannot verify")
14545        );
14546        // Resuming an existing owner needs no new inventory or worktree budget.
14547        assert!(
14548            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14549                panic!("resume must not load historical attempts")
14550            })
14551            .is_none()
14552        );
14553    }
14554
14555    #[test]
14556    fn retired_resume_requires_a_valid_same_repository_authority() {
14557        let mut source = run_state(RunStatus::Blocked);
14558        let mut empty = run_state(RunStatus::Blocked);
14559        empty.retired_to = Some(source.id.clone());
14560        let runs = vec![source.id.clone(), empty.id.clone()];
14561        let resolve = |source: &RunState, empty: &RunState| {
14562            unfinished_run_with(&runs, "fixture", |id| {
14563                if id == source.id {
14564                    Ok(source.clone())
14565                } else if id == empty.id {
14566                    Ok(empty.clone())
14567                } else {
14568                    bail!("unreadable authority")
14569                }
14570            })
14571        };
14572        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14573        assert_eq!(
14574            choose_starter(None, false, resolve(&source, &empty).as_deref()),
14575            Starter::Resume(source.id.clone())
14576        );
14577        source.retired_to = Some(empty.id.clone());
14578        assert!(
14579            resolve(&source, &empty).is_none(),
14580            "cycles do not revive obsolete runs"
14581        );
14582        source.retired_to = None;
14583        source.repo = PathBuf::from("/another-repository");
14584        assert!(resolve(&source, &empty).is_none());
14585        source.repo = empty.repo.clone();
14586        source.released_to = Some("later".into());
14587        assert!(resolve(&source, &empty).is_none());
14588        empty.retired_to = Some("unlisted-run".into());
14589        assert!(resolve(&source, &empty).is_none());
14590    }
14591
14592    #[test]
14593    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14594        // A task whose history holds an *older* run that still looks
14595        // resumable (say, a competition `Runner::review` was started
14596        // alongside after that older run went `Stalled`) and a *newest* run
14597        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
14598        // on this task must mean a fresh competition — falling back to the
14599        // stale, superseded `Stalled` run instead would resurrect history
14600        // nothing asked to revisit and silently defeat the requeue.
14601        let mut older_stalled = RunState::new(
14602            PathBuf::from("/repo"),
14603            "main".to_owned(),
14604            "abc1234def".to_owned(),
14605            "add retries".to_owned(),
14606            Config::default(),
14607        );
14608        older_stalled.status = RunStatus::Stalled;
14609
14610        let mut newest_exhausted = RunState::new(
14611            PathBuf::from("/repo"),
14612            "main".to_owned(),
14613            "abc1234def".to_owned(),
14614            "add retries".to_owned(),
14615            Config::default(),
14616        );
14617        newest_exhausted.status = RunStatus::Blocked;
14618        newest_exhausted.config.graph.review_rounds = 1;
14619        newest_exhausted.reviews = vec![review_round(1)];
14620
14621        assert_eq!(
14622            unfinished_run_with(
14623                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14624                "t",
14625                |_| Ok(newest_exhausted.clone())
14626            ),
14627            None,
14628            "the newest run is exhausted, so nothing here is worth resuming - \
14629             least of all the older, already-superseded run"
14630        );
14631    }
14632
14633    #[test]
14634    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14635        assert_eq!(
14636            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14637                Err(anyhow::anyhow!("fixture is absent"))
14638            }),
14639            None
14640        );
14641    }
14642
14643    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14644        let mut q = ask::Question::new(
14645            run.to_owned(),
14646            "implement".to_owned(),
14647            "impl-A".to_owned(),
14648            "continue?".to_owned(),
14649            String::new(),
14650            vec!["resume で続行する".to_owned(), "other".to_owned()],
14651        );
14652        q.actions.insert("resume で続行する".to_owned(), action);
14653        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14654            .unwrap();
14655        q
14656    }
14657
14658    fn held_task_with(run: &str) -> Task {
14659        let mut t = task();
14660        t.runs = vec![run.to_owned()];
14661        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14662        t
14663    }
14664
14665    fn resume_action(run: &str) -> ask::ChoiceAction {
14666        ask::ChoiceAction::Resume { run: run.into() }
14667    }
14668
14669    #[test]
14670    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14671        let home = crate::run::test_home();
14672        for parked in [false, true] {
14673            let mut t = task();
14674            t.start("A".into());
14675            t.start("B".into());
14676            assert_eq!(t.runs, vec!["A", "B"]);
14677            t.start("A".into());
14678            let mut resumed = run_state(RunStatus::Blocked);
14679            resumed.id = "A".into();
14680            resumed.parked = parked;
14681            resumed.driver_exited = true;
14682            t.hold_machine(Some("resumed run stopped".into()));
14683            let q = action_question("A", resume_action("A"));
14684            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14685            assert_eq!(
14686                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14687                    assert_eq!(id, "A");
14688                    Ok(resumed.clone())
14689                }),
14690                ActionDecision::Resume("A".into())
14691            );
14692            assert_eq!(
14693                action_standing(&t, &action_question("B", resume_action("B"))),
14694                ActionStanding::Stale
14695            );
14696            t.release_operator("cli", None);
14697            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14698                assert_eq!(id, "A");
14699                Ok(resumed.clone())
14700            });
14701            assert_eq!(
14702                choose_starter(None, false, unfinished.as_deref()),
14703                Starter::Resume("A".into())
14704            );
14705            assert_eq!(t.runs, vec!["B", "A"]);
14706        }
14707    }
14708
14709    #[test]
14710    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14711        let home = crate::run::test_home();
14712        let mut state = crate::land::tests::repair_state(true, true);
14713        state.status = RunStatus::Landing;
14714        state.parked = true;
14715        state.driver_exited = true;
14716        let mut q = ask::Question::new(
14717            state.id.clone(),
14718            land::APPROVAL_NODE.into(),
14719            "land".into(),
14720            "Merge?".into(),
14721            String::new(),
14722            vec![land::APPROVE.into(), land::HOLD.into()],
14723        );
14724        q.id = state.id.clone();
14725        state.land_approval = Some(crate::run::LandApproval {
14726            question: q.id.clone(),
14727            head: "current-head".into(),
14728        });
14729        assert!(land::upgrade_repair_choice(&mut q, &state));
14730        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14731        let mut task = held_task_with(&state.id);
14732        task.status = TaskStatus::Parked;
14733        assert_eq!(
14734            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14735            ActionDecision::Resume(state.id.clone())
14736        );
14737        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14738        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14739        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14740        assert_eq!(
14741            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14742            ActionDecision::Resume(state.id.clone()),
14743            "a repair answer newer than the manual hold resumes the existing owner"
14744        );
14745        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14746        for answered_at in [q.answered_at, None] {
14747            let mut older = q.clone();
14748            older.answered_at = answered_at;
14749            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14750                panic!("a later manual hold must prevent dispatch")
14751            });
14752            let ActionDecision::Refuse(reason) = refused else {
14753                panic!("expected an actionable refusal, got {refused:?}");
14754            };
14755            assert!(reason.contains("later operator decision"));
14756            assert!(reason.contains(&format!("magi task release {}", task.id)));
14757        }
14758        task.operator_decided_at = None;
14759        let mut superseded = state.clone();
14760        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14761        assert_eq!(
14762            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14763            ActionDecision::Stale
14764        );
14765        for case in 1..4 {
14766            let mut changed = state.clone();
14767            match case {
14768                1 => changed.status = RunStatus::Blocked,
14769                2 => changed.released_to = Some("new-owner".into()),
14770                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14771            }
14772            assert!(matches!(
14773                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14774                ActionDecision::Refuse(_)
14775            ));
14776        }
14777        assert!(matches!(
14778            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14779                "missing owner"
14780            )),
14781            ActionDecision::Refuse(_)
14782        ));
14783        task.runs.push("replacement".into());
14784        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14785        assert_eq!(
14786            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14787                "old owner must not load"
14788            )),
14789            ActionDecision::Stale
14790        );
14791    }
14792
14793    #[test]
14794    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14795        let mut state = crate::land::tests::repair_state(true, true);
14796        state.status = RunStatus::Landing;
14797        state.parked = true;
14798        state.driver_exited = true;
14799        let mut q = ask::Question::new(
14800            state.id.clone(),
14801            land::APPROVAL_NODE.into(),
14802            "land".into(),
14803            "Merge?".into(),
14804            String::new(),
14805            vec![land::APPROVE.into(), land::HOLD.into()],
14806        );
14807        q.id = state.id.clone();
14808        state.land_approval = Some(crate::run::LandApproval {
14809            question: q.id.clone(),
14810            head: "current-head".into(),
14811        });
14812        state.save().unwrap();
14813        land::upgrade_repair_choice(&mut q, &state);
14814        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14815        Questions::open().put(&mut q).unwrap();
14816        let tmp = tempfile::tempdir().unwrap();
14817        let queue = Queue::at(tmp.path().join("queue"));
14818        let mut task = held_task_with(&state.id);
14819        task.status = TaskStatus::Parked;
14820        queue.put(&mut task).unwrap();
14821        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14822        let free = Arc::new(tokio::sync::Semaphore::new(1));
14823        assert!(matches!(
14824            claim_dispatch(&queue, &task, false, &empty, &free),
14825            Err(SkipReason::OrdinaryCapacity)
14826        ));
14827        assert!(matches!(
14828            claim_dispatch(&queue, &task, true, &free, &free),
14829            Err(SkipReason::CoolingDown)
14830        ));
14831        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14832        assert!(claim.permit.is_some());
14833        assert!(matches!(
14834            claim_dispatch(&queue, &task, false, &free, &free),
14835            Err(SkipReason::ClaimUnavailable)
14836        ));
14837        drop(claim);
14838        Questions::open()
14839            .update(&q.id, |q| {
14840                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14841                Ok(())
14842            })
14843            .unwrap();
14844        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14845        assert!(claim.permit.is_none());
14846        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14847    }
14848
14849    #[test]
14850    fn decide_action_resumes_only_the_latest_resumable_run() {
14851        let home = crate::run::test_home();
14852        let t = held_task_with("r1");
14853        let q = action_question("r1", resume_action("r1"));
14854        let load = |s: RunState| move |_: &str| Ok(s);
14855        assert_eq!(
14856            decide_action(
14857                &home,
14858                &t,
14859                &q,
14860                &PHRASES_EN,
14861                load(run_state(RunStatus::Blocked))
14862            ),
14863            ActionDecision::Resume("r1".into())
14864        );
14865        // Not the latest run of the task.
14866        let q_other = action_question("r1", resume_action("r0"));
14867        assert!(matches!(
14868            decide_action(
14869                &home,
14870                &t,
14871                &q_other,
14872                &PHRASES_EN,
14873                load(run_state(RunStatus::Blocked))
14874            ),
14875            ActionDecision::Refuse(_)
14876        ));
14877        // A finished run cannot make progress.
14878        assert!(matches!(
14879            decide_action(
14880                &home,
14881                &t,
14882                &q,
14883                &PHRASES_EN,
14884                load(run_state(RunStatus::Ready))
14885            ),
14886            ActionDecision::Refuse(_)
14887        ));
14888        // A released one either.
14889        let mut released = run_state(RunStatus::Blocked);
14890        released.released_to = Some("elsewhere".into());
14891        assert!(matches!(
14892            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14893            ActionDecision::Refuse(_)
14894        ));
14895        // Unreadable state is a refusal, never a fresh competition.
14896        assert!(matches!(
14897            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14898            ActionDecision::Refuse(_)
14899        ));
14900    }
14901
14902    #[test]
14903    fn decide_action_ignores_a_question_about_an_earlier_run() {
14904        let home = crate::run::test_home();
14905        let mut t = held_task_with("r1");
14906        t.runs.push("r2".to_owned());
14907        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14908        assert_eq!(
14909            decide_action(
14910                &home,
14911                &t,
14912                &action_question("r1", ask::ChoiceAction::Done),
14913                &PHRASES_EN,
14914                never
14915            ),
14916            ActionDecision::Stale
14917        );
14918    }
14919
14920    #[test]
14921    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14922        let home = crate::run::test_home();
14923        let mut t = held_task_with("r1");
14924        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14925        assert_eq!(
14926            decide_action(
14927                &home,
14928                &t,
14929                &action_question("r1", ask::ChoiceAction::Requeue),
14930                &PHRASES_EN,
14931                never
14932            ),
14933            ActionDecision::Requeue
14934        );
14935        let done_q = action_question("r1", ask::ChoiceAction::Done);
14936        assert_eq!(
14937            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14938            ActionDecision::Done
14939        );
14940        t.mark_action_applied(&done_q.id);
14941        assert_eq!(
14942            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14943            ActionDecision::Skip
14944        );
14945
14946        // A plain answer (no action for that label) does nothing.
14947        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14948        plain.actions.clear();
14949        assert_eq!(
14950            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14951            ActionDecision::Skip
14952        );
14953        // A running task is left alone.
14954        let mut running = held_task_with("r1");
14955        running.status = TaskStatus::Running;
14956        assert_eq!(
14957            decide_action(
14958                &home,
14959                &running,
14960                &action_question("r1", ask::ChoiceAction::Done),
14961                &PHRASES_EN,
14962                never
14963            ),
14964            ActionDecision::Skip
14965        );
14966    }
14967
14968    #[test]
14969    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14970        crate::run::pin_test_home();
14971        for legacy in [false, true] {
14972            let dir = tempfile::tempdir().unwrap();
14973            let queue = Queue::at(dir.path().join("queue"));
14974            let questions = Questions::at(dir.path().join("questions"));
14975            let run = "20260101-000000-hold";
14976            let mut task = held_task_with(run);
14977            task.status = TaskStatus::Parked;
14978            let mut q = ask::Question::new(
14979                run.into(),
14980                land::APPROVAL_NODE.into(),
14981                "land".into(),
14982                "Repair?".into(),
14983                String::new(),
14984                vec![land::REPAIR.into()],
14985            );
14986            q.actions.insert(land::REPAIR.into(), resume_action(run));
14987            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14988            // Deterministically order the answer before the actual manual hold.
14989            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14990            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
14991            questions.put(&mut q).unwrap();
14992            task.hold_manual(Some("Keep this PR paused".into()));
14993            if legacy {
14994                task.hold_source = None;
14995            }
14996            queue.put(&mut task).unwrap();
14997
14998            apply_task_choice_actions(&queue, &questions, dir.path());
14999            let after = queue.get(&task.id).unwrap();
15000            assert!(after.operator_held());
15001            assert_eq!(after.hold_source, task.hold_source);
15002            assert_eq!(after.operator_decided_at, task.operator_decided_at);
15003            assert_eq!(after.runs, task.runs);
15004            assert_eq!(after.instruction, task.instruction);
15005            assert!(after.resume_override.is_none());
15006            assert!(after.action_applied(&q.id));
15007            let reason = after.hold_reason.as_deref().unwrap();
15008            assert!(reason.starts_with("Keep this PR paused"));
15009            assert!(reason.contains("later operator decision"));
15010            assert!(reason.contains(&format!("magi task release {}", task.id)));
15011
15012            for recovery in [
15013                crate::conduct::Recovery::Review,
15014                crate::conduct::Recovery::Requeue,
15015            ] {
15016                crate::conduct::apply(
15017                    &queue,
15018                    &questions,
15019                    &crate::conduct::Verdict {
15020                        decisions: vec![crate::conduct::Decision {
15021                            id: task.id.clone(),
15022                            recovery: Some(recovery),
15023                            ..Default::default()
15024                        }],
15025                    },
15026                )
15027                .unwrap();
15028            }
15029            // Reconciliation is idempotent, and automatic recovery cannot
15030            // reopen this owner after it observes the rejected repair answer.
15031            apply_task_choice_actions(&queue, &questions, dir.path());
15032            let still_held = queue.get(&task.id).unwrap();
15033            assert!(still_held.operator_held());
15034            assert_eq!(still_held.hold_reason, after.hold_reason);
15035            assert_eq!(still_held.runs, task.runs);
15036            assert!(still_held.review_branch.is_none());
15037            assert!(!still_held.fresh_start);
15038            assert!(queue.next_runnable().is_none());
15039        }
15040    }
15041
15042    #[test]
15043    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
15044        for held in [false, true] {
15045            for retry in [false, true] {
15046                let dir = tempfile::tempdir().unwrap();
15047                let queue = Queue::at(dir.path().join("queue"));
15048                let questions = Questions::at(dir.path().join("questions"));
15049                let home = dir.path().join("home");
15050                let mut t = task();
15051                if held {
15052                    t.hold_machine(Some("driver state unknown".into()));
15053                }
15054                queue.put(&mut t).unwrap();
15055                let verdict = serde_json::from_value(serde_json::json!({
15056                    "decisions": [{
15057                        "id": t.id,
15058                        "question": "Driver state unknown; retry the checks or hold?",
15059                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
15060                        "actions": {
15061                            "daemon: recheck and retry": {"do": "requeue"},
15062                            "daemon: hold the task": {"do": "hold"}
15063                        }
15064                    }]
15065                }))
15066                .unwrap();
15067                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
15068                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
15069                let mut q = questions.list().pop().unwrap();
15070                let choice = if retry {
15071                    "daemon: recheck and retry"
15072                } else {
15073                    "daemon: hold the task"
15074                };
15075                assert_eq!(q.actions.len(), 2);
15076                q.answer(ask::Answer::Choice(choice.into())).unwrap();
15077                questions.put(&mut q).unwrap();
15078
15079                // A Web answer does not remove the deputy's fresh lease.
15080                questions.beat(&q.id, ask::WaiterKind::Deputy);
15081                for _ in 0..2 {
15082                    resolve_blockers(&queue, &questions);
15083                    apply_task_choice_actions(&queue, &questions, &home);
15084                    let waiting = queue.get(&t.id).unwrap();
15085                    assert_eq!(waiting.status, TaskStatus::Blocked);
15086                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
15087                    assert!(waiting.answers.is_empty());
15088                    assert!(!waiting.action_applied(&q.id));
15089                    assert!(runnable(&queue).is_empty());
15090                    let free = Arc::new(tokio::sync::Semaphore::new(1));
15091                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
15092                }
15093                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
15094
15095                // Releasing the blocker and applying the operation share one save.
15096                resolve_blockers(&queue, &questions);
15097                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
15098                apply_task_choice_actions(&queue, &questions, &home);
15099                let after = queue.get(&t.id).unwrap();
15100                assert_eq!(
15101                    after.status,
15102                    if retry {
15103                        TaskStatus::Queued
15104                    } else {
15105                        TaskStatus::Held
15106                    }
15107                );
15108                assert!(after.action_applied(&q.id));
15109                assert_eq!(after.operator_held(), !retry);
15110                assert_eq!(after.answers.len(), 1);
15111
15112                // A later operator decision must not replay this answer.
15113                let mut changed = after;
15114                if retry {
15115                    changed.hold_manual(Some("later hold".into()));
15116                } else {
15117                    changed.release_operator("test", None);
15118                }
15119                let expected = changed.status;
15120                queue.put(&mut changed).unwrap();
15121                apply_task_choice_actions(&queue, &questions, &home);
15122                assert_eq!(queue.get(&t.id).unwrap().status, expected);
15123            }
15124        }
15125    }
15126
15127    #[test]
15128    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
15129        let dir = tempfile::tempdir().unwrap();
15130        let queue = Queue::at(dir.path().join("queue"));
15131        let questions = Questions::at(dir.path().join("questions"));
15132        let home = dir.path().join("home");
15133        let mut state = run_state(RunStatus::Blocked);
15134        state.id = "20260101-000000-act1".to_owned();
15135        state.save_under(&home).unwrap();
15136
15137        let mut t = held_task_with(&state.id);
15138        queue.put(&mut t).unwrap();
15139        let mut q = action_question(&state.id, resume_action(&state.id));
15140        questions.put(&mut q).unwrap();
15141
15142        apply_task_choice_actions(&queue, &questions, &home);
15143        let after = queue.get(&t.id).unwrap();
15144        assert_eq!(after.status, TaskStatus::Queued);
15145        assert!(!after.fresh_start);
15146        assert!(after.action_applied(&q.id));
15147        let pin = after.resume_override.clone().unwrap();
15148        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
15149        assert!(pin.forced);
15150
15151        // Held again later: the same answer does not release it a second time.
15152        let mut again = queue.get(&t.id).unwrap();
15153        again.hold_machine(Some("later".into()));
15154        queue.put(&mut again).unwrap();
15155        apply_task_choice_actions(&queue, &questions, &home);
15156        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15157    }
15158
15159    #[test]
15160    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
15161        let dir = tempfile::tempdir().unwrap();
15162        let home = dir.path();
15163        let queue = Queue::at(home.join("queue"));
15164        let questions = Questions::at(home.join("questions"));
15165        let mut state = run_state(RunStatus::Blocked);
15166        state.save_under(home).unwrap();
15167        let mut task = held_task_with(&state.id);
15168        queue.put(&mut task).unwrap();
15169        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
15170        questions.put(&mut question).unwrap();
15171
15172        apply_task_choice_actions(&queue, &questions, home);
15173
15174        let after = queue.get(&task.id).unwrap();
15175        assert_eq!(after.status, TaskStatus::Held);
15176        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
15177        assert_eq!(after.runs, task.runs);
15178        assert!(after.completion_history.is_empty());
15179        assert!(!after.decision_effects.contains_key(&question.id));
15180        assert_eq!(
15181            RunState::load_under(&state.id, home).unwrap().status,
15182            RunStatus::Blocked
15183        );
15184    }
15185
15186    #[test]
15187    fn a_delivered_answer_is_still_acted_on_exactly_once() {
15188        let dir = tempfile::tempdir().unwrap();
15189        let queue = Queue::at(dir.path().join("queue"));
15190        let questions = Questions::at(dir.path().join("questions"));
15191        let home = dir.path().join("home");
15192        let mut state = run_state(RunStatus::Blocked);
15193        state.id = "20260101-000000-act2".to_owned();
15194        state.save_under(&home).unwrap();
15195
15196        let mut t = held_task_with(&state.id);
15197        queue.put(&mut t).unwrap();
15198        let mut q = action_question(&state.id, resume_action(&state.id));
15199        q.answer_delivered = true;
15200        questions.put(&mut q).unwrap();
15201
15202        // Delivered, and the agent then died: the task is still held, so the
15203        // chosen action applies.
15204        apply_task_choice_actions(&queue, &questions, &home);
15205        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15206        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
15207
15208        // Held again: the same answer does nothing a second time.
15209        let mut again = queue.get(&t.id).unwrap();
15210        again.hold_machine(Some("later".into()));
15211        queue.put(&mut again).unwrap();
15212        apply_task_choice_actions(&queue, &questions, &home);
15213        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15214    }
15215
15216    #[test]
15217    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
15218        let dir = tempfile::tempdir().unwrap();
15219        let queue = Queue::at(dir.path().join("queue"));
15220        let questions = Questions::at(dir.path().join("questions"));
15221        let home = dir.path().join("home");
15222        let mut state = run_state(RunStatus::Blocked);
15223        state.id = "20260101-000000-act3".to_owned();
15224        state.save_under(&home).unwrap();
15225        let mut t = held_task_with(&state.id);
15226        queue.put(&mut t).unwrap();
15227        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
15228        questions.put(&mut q).unwrap();
15229
15230        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
15231        apply_task_choice_actions(&queue, &questions, &home);
15232        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15233
15234        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
15235        apply_task_choice_actions(&queue, &questions, &home);
15236        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15237    }
15238
15239    #[test]
15240    fn action_standing_tells_the_reasons_apart() {
15241        let mut t = held_task_with("r1");
15242        let q = action_question("r1", ask::ChoiceAction::Requeue);
15243        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
15244        let mut plain = q.clone();
15245        plain.actions.clear();
15246        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
15247
15248        // Applied wins over everything, even a running task.
15249        t.mark_action_applied(&q.id);
15250        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
15251
15252        // A newer attempt running: the old question is Stale, not Busy.
15253        let mut t = held_task_with("r1");
15254        t.start("r2".to_owned());
15255        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
15256        // The same question about the latest run just waits.
15257        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
15258        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15259        t.status = TaskStatus::Blocked;
15260        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15261
15262        // A conductor question is keyed by the task, never stale.
15263        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
15264        c.node = crate::conduct::NODE.to_owned();
15265        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
15266        assert!(!ActionStanding::Busy.daemon_owns());
15267    }
15268
15269    #[test]
15270    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
15271        let dir = tempfile::tempdir().unwrap();
15272        let queue = Queue::at(dir.path().join("queue"));
15273        let questions = Questions::at(dir.path().join("questions"));
15274        let home = dir.path().join("home");
15275        // Execution finished before task settlement; Done is not a discard.
15276        let mut state = run_state(RunStatus::Ready);
15277        state.id = "20260101-000000-act4".to_owned();
15278        state.save_under(&home).unwrap();
15279        let mut t = held_task_with(&state.id);
15280        t.status = TaskStatus::Running;
15281        queue.put(&mut t).unwrap();
15282        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
15283        q.cwd = Some(dir.path().display().to_string());
15284        questions.put(&mut q).unwrap();
15285
15286        // While the task runs the daemon will not act, so the waiter still
15287        // delivers the word to the dead asker's seat ...
15288        let running = queue.get(&t.id).unwrap();
15289        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
15290        assert!(matches!(
15291            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
15292            crate::waiter::Action::Deliver(_)
15293        ));
15294        // ... and the daemon waits while the task runs, then applies once.
15295        apply_task_choice_actions(&queue, &questions, &home);
15296        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
15297        let mut back = queue.get(&t.id).unwrap();
15298        back.hold_machine(Some("later".into()));
15299        queue.put(&mut back).unwrap();
15300        apply_task_choice_actions(&queue, &questions, &home);
15301        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
15302        let mut again = queue.get(&t.id).unwrap();
15303        again.hold_machine(Some("again".into()));
15304        queue.put(&mut again).unwrap();
15305        apply_task_choice_actions(&queue, &questions, &home);
15306        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15307    }
15308
15309    #[test]
15310    fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
15311     {
15312        let dir = tempfile::tempdir().unwrap();
15313        let home = dir.path();
15314        let queue = Queue::at(home.join("queue"));
15315        let mut state = run_state(RunStatus::Blocked);
15316        state.id = "20261125-084544-669a".to_owned();
15317        state.driver_exited = true;
15318        state.driver_pid = None;
15319        state.driver_started_at = None;
15320        state.save_under(home).unwrap();
15321
15322        let mut t = held_task_with(&state.id);
15323        queue.put(&mut t).unwrap();
15324
15325        // Simulate a task worker that finished and was archived to results/,
15326        // while daemon.json still has a fresh heartbeat referencing that worker.
15327        let worker_id = "fc769e65-0000-4000-8000-000000000001";
15328        let retained_dir = home.join("workers").join("results").join(worker_id);
15329        std::fs::create_dir_all(&retained_dir).unwrap();
15330        let finished_job = crate::worker::Job {
15331            id: worker_id.to_owned(),
15332            sequence: 1,
15333            kind: "task".to_owned(),
15334            key: format!("task:{}", t.id),
15335            payload: serde_json::json!({
15336                "queue": home.join("queue"),
15337                "task": t.id,
15338                "opts": Opts::default(),
15339                "standalone": false,
15340            }),
15341            generation: "a".repeat(64),
15342            version: Some("0.260.0".to_owned()),
15343            status: crate::worker::Status::Finished,
15344            result: Some("completed".to_owned()),
15345            pid: Some(37456),
15346            created_at: 1,
15347            finished_at: Some(2),
15348        };
15349        std::fs::write(
15350            retained_dir.join("job.json"),
15351            serde_json::to_vec(&finished_job).unwrap(),
15352        )
15353        .unwrap();
15354
15355        let now = Timestamp::now();
15356        let mut status = Status::new();
15357        status.updated_at = now;
15358        status.current = vec![Current {
15359            worker: Some(worker_id.to_owned()),
15360            task: t.id.clone(),
15361            run: state.id.clone(),
15362        }];
15363        write_status_to(&home.join("daemon.json"), &status).unwrap();
15364
15365        assert!(
15366            claim_for_run(home, &state.id, now).is_none(),
15367            "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
15368        );
15369        assert!(crate::resume::validate(home, &state.id).is_ok());
15370
15371        // Legacy heartbeat without worker id remains protected.
15372        status.current = vec![Current {
15373            worker: None,
15374            task: t.id.clone(),
15375            run: state.id.clone(),
15376        }];
15377        write_status_to(&home.join("daemon.json"), &status).unwrap();
15378        let legacy_err = crate::resume::validate(home, &state.id)
15379            .unwrap_err()
15380            .to_string();
15381        assert!(
15382            legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
15383            "{legacy_err}"
15384        );
15385        assert!(legacy_err.contains("worker=none"), "{legacy_err}");
15386
15387        // Heartbeat naming a missing/unreadable worker record remains protected.
15388        let missing_id = "fc769e65-0000-4000-8000-000000000002";
15389        status.current = vec![Current {
15390            worker: Some(missing_id.to_owned()),
15391            task: t.id.clone(),
15392            run: state.id.clone(),
15393        }];
15394        write_status_to(&home.join("daemon.json"), &status).unwrap();
15395        let missing_err = crate::resume::validate(home, &state.id)
15396            .unwrap_err()
15397            .to_string();
15398        assert!(
15399            missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
15400            "{missing_err}"
15401        );
15402        assert!(missing_err.contains(missing_id), "{missing_err}");
15403        assert!(missing_err.contains("status=unknown"), "{missing_err}");
15404
15405        // Heartbeat naming a Running (non-terminal) worker whose lease is not held
15406        // still remains protected conservatively until fenced to a terminal status.
15407        let running_id = "fc769e65-0000-4000-8000-000000000003";
15408        let running_dir = home.join("workers").join("jobs").join(running_id);
15409        std::fs::create_dir_all(&running_dir).unwrap();
15410        let running_job = crate::worker::Job {
15411            id: running_id.to_owned(),
15412            status: crate::worker::Status::Running,
15413            pid: Some(42424),
15414            finished_at: None,
15415            result: None,
15416            ..finished_job
15417        };
15418        std::fs::write(
15419            running_dir.join("job.json"),
15420            serde_json::to_vec(&running_job).unwrap(),
15421        )
15422        .unwrap();
15423        std::fs::write(running_dir.join("live.lock"), b"").unwrap();
15424        status.current = vec![Current {
15425            worker: Some(running_id.to_owned()),
15426            task: t.id.clone(),
15427            run: state.id.clone(),
15428        }];
15429        write_status_to(&home.join("daemon.json"), &status).unwrap();
15430        let running_err = crate::resume::validate(home, &state.id)
15431            .unwrap_err()
15432            .to_string();
15433        assert!(
15434            running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
15435            "{running_err}"
15436        );
15437        assert!(running_err.contains(running_id), "{running_err}");
15438        assert!(running_err.contains("pid=42424"), "{running_err}");
15439        assert!(running_err.contains("status=running"), "{running_err}");
15440    }
15441
15442    #[test]
15443    fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
15444        let dir = tempfile::tempdir().unwrap();
15445        let home = dir.path();
15446        let queue = Queue::at(home.join("queue"));
15447        let mut state = run_state(RunStatus::Blocked);
15448        state.id = "20261125-090000-evid".to_owned();
15449        state.driver_exited = true;
15450        state.save_under(home).unwrap();
15451        let mut t = held_task_with(&state.id);
15452        queue.put(&mut t).unwrap();
15453
15454        // 1. Live task worker holding live.lock.
15455        let payload = serde_json::json!({
15456            "queue": home.join("queue"),
15457            "task": t.id,
15458            "opts": Opts::default(),
15459            "standalone": false,
15460        });
15461        let (job, lease) =
15462            crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
15463        let worker_err = crate::resume::validate(home, &state.id)
15464            .unwrap_err()
15465            .to_string();
15466        assert!(
15467            worker_err.starts_with("run already has a live driver: worker claim"),
15468            "{worker_err}"
15469        );
15470        assert!(worker_err.contains(&job.id), "{worker_err}");
15471        assert!(
15472            worker_err.contains(&format!("pid={}", std::process::id())),
15473            "{worker_err}"
15474        );
15475        assert!(worker_err.contains("status=running"), "{worker_err}");
15476        assert!(worker_err.contains("live.lock held"), "{worker_err}");
15477        drop(lease);
15478        std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
15479
15480        // 2. Unfenced Starting worker reservation.
15481        let starting_id = "fc769e65-0000-4000-8000-000000000010";
15482        let starting_dir = home.join("workers").join("jobs").join(starting_id);
15483        std::fs::create_dir_all(&starting_dir).unwrap();
15484        let starting_job = crate::worker::Job {
15485            id: starting_id.to_owned(),
15486            sequence: 2,
15487            kind: "task".to_owned(),
15488            key: format!("task:{}", t.id),
15489            payload: serde_json::json!({
15490                "queue": home.join("queue"),
15491                "task": t.id,
15492                "opts": Opts::default(),
15493                "standalone": false,
15494            }),
15495            generation: "a".repeat(64),
15496            version: None,
15497            status: crate::worker::Status::Starting,
15498            result: None,
15499            pid: None,
15500            created_at: 1,
15501            finished_at: None,
15502        };
15503        std::fs::write(
15504            starting_dir.join("job.json"),
15505            serde_json::to_vec(&starting_job).unwrap(),
15506        )
15507        .unwrap();
15508        let starting_err = crate::resume::validate(home, &state.id)
15509            .unwrap_err()
15510            .to_string();
15511        assert!(
15512            starting_err.starts_with("run already has a live driver: worker claim"),
15513            "{starting_err}"
15514        );
15515        assert!(starting_err.contains(starting_id), "{starting_err}");
15516        assert!(starting_err.contains("status=starting"), "{starting_err}");
15517        assert!(
15518            starting_err.contains("unfenced starting reservation"),
15519            "{starting_err}"
15520        );
15521        std::fs::remove_dir_all(&starting_dir).unwrap();
15522
15523        // 3. Unrelated corrupt worker triggers conservative protection with distinct wording.
15524        let corrupt_id = "bad00000-0000-4000-8000-000000000099";
15525        let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
15526        std::fs::create_dir_all(&corrupt_dir).unwrap();
15527        std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
15528        let store_err = crate::resume::validate(home, &state.id)
15529            .unwrap_err()
15530            .to_string();
15531        assert!(
15532            store_err.starts_with(
15533                "run already has a live driver: worker store observation failed (conservative protection):"
15534            ),
15535            "{store_err}"
15536        );
15537        assert!(store_err.contains(corrupt_id), "{store_err}");
15538        std::fs::remove_dir_all(&corrupt_dir).unwrap();
15539
15540        // 4. Held execution lease (driver.lock path).
15541        state.driver_exited = false;
15542        state.driver_claimed = Some(false);
15543        state.driver_pid = None;
15544        state.driver_started_at = None;
15545        state.save_under(home).unwrap();
15546        let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
15547        let lease_err = crate::resume::validate(home, &state.id)
15548            .unwrap_err()
15549            .to_string();
15550        let lock_path = home.join("runs").join(&state.id).join("driver.lock");
15551        assert!(
15552            lease_err.starts_with("run already has a live driver: execution lease held"),
15553            "{lease_err}"
15554        );
15555        assert!(
15556            lease_err.contains(&lock_path.display().to_string()),
15557            "{lease_err}"
15558        );
15559        drop(exec_lease);
15560
15561        // 5. Live process identity (pid + identity).
15562        let pid = std::process::id();
15563        let identity = crate::proc::process_started_at(pid).expect("current process identity");
15564        state.driver_claimed = None;
15565        state.driver_pid = Some(pid);
15566        state.driver_started_at = Some(identity.clone());
15567        state.save_under(home).unwrap();
15568        let pid_err = crate::resume::validate(home, &state.id)
15569            .unwrap_err()
15570            .to_string();
15571        assert!(
15572            pid_err.starts_with("run already has a live driver: live driver process"),
15573            "{pid_err}"
15574        );
15575        assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
15576        assert!(
15577            pid_err.contains(&format!("identity={identity}")),
15578            "{pid_err}"
15579        );
15580
15581        // decide_action uses the exact same refusal format for process identity too.
15582        let question = action_question(&state.id, resume_action(&state.id));
15583        let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
15584            RunState::load_under(id, home)
15585        });
15586        assert_eq!(decision, ActionDecision::Refuse(pid_err));
15587    }
15588}