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 state.land_sync_exhausted() {
2410        task.hold_machine(Some(format!("{detail} {}", state.land_sync_next_action())));
2411        task.last_error = Some(detail.to_owned());
2412    } else if !verdict.parked
2413        && task
2414            .pr_recovery
2415            .as_ref()
2416            .is_some_and(|s| s.disposition != Some(crate::pr_recovery::Disposition::Review))
2417        && matches!(
2418            verdict.status,
2419            RunStatus::Ready | RunStatus::Merged | RunStatus::AlreadyInBase
2420        )
2421    {
2422        if state.pr_recovery == task.pr_recovery && state.public_delivery_complete() {
2423            task.succeed(CompletionContext::from_run(
2424                CompletionActor::DaemonSettle,
2425                Some(detail.to_owned()),
2426                task,
2427                state,
2428            ));
2429        } else {
2430            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()));
2431        }
2432    } else if !verdict.parked
2433        && task.pr_recovery.is_some()
2434        && matches!(
2435            verdict.status,
2436            RunStatus::Blocked | RunStatus::Failed | RunStatus::Gating
2437        )
2438        && !verdict.quota_hit
2439    {
2440        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.")));
2441    } else if let Some(stop) = head_e2e_stop.clone() {
2442        // Conclusive current-head E2E red settles directly to one actionable
2443        // machine hold instead of cycling through runnable `Failed` passes.
2444        // Refund only when this pass provably reconsumed an earlier stop with
2445        // no new verification events, idempotently across reclaim/re-settle.
2446        if crate::head_e2e_stop::reconsumed_without_new_verification(state, &stop) {
2447            reconsumed_head_e2e = true;
2448            let pass = state.passes.last().map_or(0, |p| p.index);
2449            if !task
2450                .passes
2451                .iter()
2452                .any(|p| p.run == state.id && p.pass_index == pass)
2453            {
2454                task.attempts = task.attempts.saturating_sub(1);
2455            }
2456        }
2457        let reason = crate::head_e2e_stop::hold_reason(task, state, &stop, None);
2458        task.hold_head_e2e(stop, reason, detail.to_owned());
2459    } else {
2460        settle_in(task, verdict, detail, max_attempts, p, Some(state));
2461    }
2462    if !verdict.parked
2463        && !verdict.quota_hit
2464        && !reconsumed_head_e2e
2465        && matches!(
2466            verdict.status,
2467            RunStatus::Blocked | RunStatus::Failed | RunStatus::Stalled
2468        )
2469    {
2470        task.recovery_failed(state);
2471    }
2472    if state.prep_failure.is_some() {
2473        // Minting a run whose candidates could not be prepared is not work
2474        // on a newly approved attempt. Keep the unresolved outcome anchor.
2475        task.hold_notice_cause = unresolved;
2476        task.startup_notice_cause("startup-candidates");
2477    }
2478    // Written here, where the refund (or not) is decided, so the history is a
2479    // fact and not a later guess from the run's status.
2480    if let Some(pass) = state.passes.last() {
2481        let parked = match &pass.end {
2482            Some(crate::run::PassEnd::Parked { cause }) => Some(cause.clone()),
2483            _ => None,
2484        };
2485        task.record_pass_at(
2486            &state.id,
2487            pass.index,
2488            Some(pass.started_at),
2489            attempts_before,
2490            parked,
2491        );
2492    }
2493    if task.status == TaskStatus::Held {
2494        if state.base_sync_blocked() {
2495            task.base_sync_notice(state);
2496        } else if state.land_sync_exhausted() {
2497            task.land_sync_notice(state);
2498        } else if let Some(stop) = &head_e2e_stop {
2499            task.head_e2e_notice(stop);
2500        } else if state.prep_failure.is_none() {
2501            task.notice_cause(
2502                label(verdict.status),
2503                Some(&state.id),
2504                state.passes.last().map(|p| p.index),
2505            );
2506        }
2507        task.diagnostic = diagnostic(state);
2508        note_open_question(task, &state.id, p);
2509    }
2510}
2511
2512/// If `task` is held with a `magi ask` question still open on `run`, name the
2513/// question in [`Task::hold_reason`] rather than leaving the hold reading
2514/// only [`describe`]'s run summary.
2515///
2516/// This is the shape task 20260928-191407-05fd left underspecified: an
2517/// implementer settled a verified no-op and filed a question for the
2518/// operator, and the hold that followed said nothing about the question
2519/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
2520/// existing text ([`is_disk_hold`](crate::triage), the answered-question
2521/// marker) and must keep seeing it unchanged.
2522///
2523/// Best-effort: an unreadable question store must not stop a run from
2524/// settling, so this is a no-op rather than a propagated error when
2525/// [`crate::run::try_home`] has nothing to offer or the store is empty.
2526fn note_open_question(task: &mut Task, run: &str, p: &Phrases) {
2527    let Some(home) = crate::run::try_home() else {
2528        return;
2529    };
2530    let open = Questions::at(home.join("questions")).open_for(run);
2531    let Some(q) = open.first() else {
2532        return;
2533    };
2534    let mut decisions: Vec<_> = open.iter().map(|q| q.id.as_str()).collect();
2535    decisions.sort_unstable();
2536    task.notice_cause(
2537        &format!("questions:{}", decisions.join(",")),
2538        Some(run),
2539        None,
2540    );
2541    let base = task.hold_reason.clone().unwrap_or_default();
2542    task.hold_reason = Some(format!("{base}{}{}", p.waiting_for_answer, q.short()));
2543}
2544
2545/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
2546/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
2547/// by some other means entirely, like a manual `magi run` resume that
2548/// finishes the graph outside the queue's bookkeeping.
2549///
2550/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
2551/// `settle` is separate from `attempt`: a task recovered this way must land
2552/// exactly where a live daemon would have put it — the same policy table,
2553/// not a second one that quietly drifts from it — and that is only checkable
2554/// without spawning a real run.
2555fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize, language: &str) {
2556    if let Some(request) = task.sync_only.clone() {
2557        crate::base_sync_only::settle(task, &request, last_run.as_ref(), None);
2558        return;
2559    }
2560    match last_run {
2561        Some(state) => {
2562            let verdict = Verdict {
2563                status: state.status,
2564                left_pr: state.pr.is_some(),
2565                quota_hit: state.quota.iter().any(|loss| {
2566                    state
2567                        .passes
2568                        .last()
2569                        .is_none_or(|pass| loss.at >= pass.started_at)
2570                }),
2571                parked: state.parked,
2572                no_viable_candidates: state.viable().is_empty(),
2573            };
2574            let detail = format!(
2575                "{}{}",
2576                phrases(&state.config.graph.language).recovered_running,
2577                describe(&state)
2578            );
2579            settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
2580        }
2581        None => {
2582            // No run, so no config of its own: `language` is the task's
2583            // repository's setting, read by the caller.
2584            let why = phrases(language).no_run_to_recover;
2585            task.last_error = Some(why.to_owned());
2586            // The phone shows `hold_reason`, so a task held by the machine
2587            // says why there too and not only in `last_error`.
2588            task.notice_cause("missing-run", None, None);
2589            task.hold_machine(Some(why.to_owned()));
2590        }
2591    }
2592}
2593
2594/// Find every task left at `running` that no live process is actually
2595/// driving, and settle each one against whatever its last run became.
2596///
2597/// # Why a claim is proof, not a guess
2598///
2599/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
2600/// `running`, and the guard is held for the task's whole time in that status:
2601/// `attempt` does not return, and the loop does not move past the scope
2602/// holding the claim, until the run has settled. So a `running` task whose
2603/// lock is gone cannot have a live owner — this process or any other —
2604/// without needing a staleness threshold or a pid check the way
2605/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
2606/// task that never got as far as `running` at all. Taking the claim here is
2607/// the whole test: it either fails, because something really does hold it
2608/// and the task is left alone, or it succeeds, which is the proof — and it is
2609/// kept for the rest of the decision so nothing else can start a competing
2610/// run while this one is being written.
2611///
2612/// Called on every poll, not only at startup, for the reason
2613/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
2614/// keep noticing this, not only on the one morning it happened to restart.
2615fn reclaim_orphaned_running(
2616    queue: &Queue,
2617    max_attempts: usize,
2618    live_workers: &std::collections::BTreeSet<String>,
2619) -> Vec<String> {
2620    let mut reclaimed = Vec::new();
2621    for listed in queue.list() {
2622        if listed.status != TaskStatus::Running || live_workers.contains(&listed.id) {
2623            continue;
2624        }
2625        let Ok(_claim) = queue.claim(&listed.id) else {
2626            continue;
2627        };
2628        // Re-read under the claim: a release or an edit landed by a human
2629        // between the listing above and the claim just taken must not be
2630        // clobbered by a decision based on the stale copy.
2631        let Ok(mut task) = queue.get(&listed.id) else {
2632            continue;
2633        };
2634        if task.status != TaskStatus::Running {
2635            continue;
2636        }
2637        let last_run = task
2638            .execution_runs()
2639            .last()
2640            .and_then(|id| RunState::load(id).ok());
2641        // `execute` normally abandons a run's own open questions the moment
2642        // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
2643        // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
2644        // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
2645        // with the question still `open`, because the process died before
2646        // reaching that call. `reclaim` itself stays pure on purpose (see its
2647        // own doc), so the same cleanup runs here instead, against the run
2648        // this reclaim is already reading. `settle_run` costs nothing when
2649        // `execute` already got there first.
2650        if let Some(state) = &last_run
2651            && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
2652        {
2653            tracing::warn!("abandon questions for {}: {e:#}", state.id);
2654        }
2655        let language = if last_run.is_none() {
2656            language_of(&task, Path::new("."))
2657        } else {
2658            String::new()
2659        };
2660        reclaim(&mut task, last_run, max_attempts, &language);
2661        if task.status == TaskStatus::Done {
2662            supersede_prior_runs(&task, &crate::run::home());
2663        }
2664        record(queue, &mut task);
2665        reclaimed.push(task.id.clone());
2666    }
2667    reclaimed
2668}
2669
2670/// Find every run whose `run.json` is provably dead — every seat it still
2671/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
2672/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
2673/// not merely "no daemon claims it" — and fail it, clearing the leftover
2674/// active seats so the run stops reading as `implementing` (or whichever
2675/// node) forever.
2676///
2677/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
2678/// `running`, using whatever `run.json` already says — but nothing in that
2679/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
2680/// stays pure on purpose, see its own doc), so a `run.json` a killed process
2681/// never got back to sits exactly where it was left: `active` full of seats
2682/// nobody will ever answer for, `status` stuck on whatever node was in
2683/// flight. `magi show` already tells an operator this in prose (`no live
2684/// daemon claims this run right now`); this is what makes that fact durable
2685/// on disk, the same way a task's own `TaskStatus::Running` does not get to
2686/// stay stuck once nothing is driving it.
2687///
2688/// Runs on every poll, not only at startup, for the reason
2689/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
2690/// daemon up for days must keep noticing a run some other, now-dead, daemon
2691/// left behind just as readily as one it trips over on the way up.
2692///
2693/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
2694/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
2695/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
2696/// `runs` directory instead: `home` here is a parameter precisely so a test
2697/// can point it away from the operator's real history (see [`drive`]'s own
2698/// doc), and a scan that fell through to the global home anyway would walk
2699/// whichever directory some *other* process or test pinned into that
2700/// `OnceLock` first — mutating runs this call was never handed.
2701fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
2702    reclaim_abandoned_runs_with(
2703        home,
2704        now,
2705        crate::proc::pid_status,
2706        crate::proc::process_started_at,
2707    )
2708}
2709
2710/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
2711/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
2712/// for the identical reason: this sweep's real damage (wiping a run's active
2713/// seats and failing it) has to be provable against an injected answer in a
2714/// test, not just the real process table.
2715fn reclaim_abandoned_runs_with<F, G>(
2716    home: &Path,
2717    now: Timestamp,
2718    query: F,
2719    identity: G,
2720) -> Vec<String>
2721where
2722    F: Fn(u32) -> Option<bool>,
2723    G: Fn(u32) -> Option<String>,
2724{
2725    let mut abandoned = Vec::new();
2726    for entry in std::fs::read_dir(home.join("runs"))
2727        .into_iter()
2728        .flatten()
2729        .flatten()
2730    {
2731        let id = entry.file_name().to_string_lossy().into_owned();
2732        if !crate::run::is_run_id(&id) {
2733            continue;
2734        }
2735        // Serialize the proof and save with claims and takeover: a new
2736        // execution must not be overwritten after the liveness observation.
2737        let Ok(_owner) = crate::pr_head::owner_lock(home, &id) else {
2738            continue;
2739        };
2740        // Unreadable is `clean::fold_due`'s problem, not this one's — see
2741        // that module's docs for why a run this cannot parse is left alone
2742        // rather than guessed at. A different schema number is not that: this
2743        // touches only `status` and `active`, never a field whose meaning a
2744        // schema bump changed, so an old record's values serve this exactly
2745        // as well as a current one's (see `clean::read_state`'s own doc for
2746        // the same reasoning applied to folding).
2747        let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
2748            continue;
2749        };
2750        let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
2751            continue;
2752        };
2753        if state.driver_exited || state.status.done() || !state.active_all_overrun(now) {
2754            continue;
2755        }
2756        // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
2757        // it", which is also the normal, healthy shape of a manual `magi
2758        // run` / `magi review` sharing this same home — this scan walks
2759        // every run on disk, not only ones this daemon itself started. Such
2760        // a run's active seats can legitimately sit past their own timeout
2761        // for a little while (the CLI finishing up, its result still being
2762        // collected) without the process driving it having died. `liveness`
2763        // is what actually tells the two apart, by corroborating
2764        // `driver_pid` against the process it names — see its own doc. Only
2765        // its strongest, provable answer licenses wiping this run's active
2766        // seats and failing it out from under whatever is still running it.
2767        let daemon_claims = is_working_on(home, &id, now);
2768        if state.liveness_under_with(home, daemon_claims, &query, &identity)
2769            != crate::run::Liveness::Dead
2770        {
2771            continue;
2772        }
2773        state.abandon("daemon");
2774        if let Err(e) = state.save_under(home) {
2775            tracing::warn!("could not persist abandoned run {id}: {e:#}");
2776            continue;
2777        }
2778        // This run never passes through `Runner::execute` again, so its end
2779        // is announced here.
2780        if let Some(notice) = notices::run_ended(&state) {
2781            notices::raise_in(home, notice);
2782        }
2783        // The seat that asked is gone for good now, exactly like any other
2784        // door `graph::Runner::settle_questions` closes the moment `status`
2785        // lands somewhere non-resumable - see that method's own doc. Nothing
2786        // else reaches this one before the next `janitor()` startup pass
2787        // (`clean::abandon_settled_questions`), and a daemon that stays up
2788        // for days must not leave an open question badging the operator
2789        // until it happens to restart.
2790        if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
2791            tracing::warn!("abandon questions for {id}: {e:#}");
2792        }
2793        abandoned.push(id);
2794    }
2795    abandoned
2796}
2797
2798#[derive(Debug, Clone, Serialize, Deserialize)]
2799struct TaskWorker {
2800    opts: Opts,
2801    queue: PathBuf,
2802    task: String,
2803    #[serde(default)]
2804    lane: PermitKind,
2805    #[serde(default)]
2806    standalone: bool,
2807}
2808
2809#[doc(hidden)]
2810pub struct TaskWorkerLease {
2811    pub job: crate::worker::Job,
2812    dir: PathBuf,
2813    lease: Option<crate::worker::Lease>,
2814}
2815
2816impl TaskWorkerLease {
2817    pub fn release_lease(&mut self) {
2818        self.lease = None;
2819    }
2820}
2821
2822impl Drop for TaskWorkerLease {
2823    fn drop(&mut self) {
2824        self.release_lease();
2825        let _ = std::fs::remove_dir_all(&self.dir);
2826    }
2827}
2828
2829/// Reserve a task worker without launching a process, for integration tests.
2830#[doc(hidden)]
2831pub fn live_task_fixture(home: &Path, task: &str) -> Result<TaskWorkerLease> {
2832    let request = TaskWorker {
2833        opts: Opts::default(),
2834        queue: home.join("queue"),
2835        task: task.to_owned(),
2836        lane: PermitKind::default(),
2837        standalone: true,
2838    };
2839    let (job, lease) = crate::worker::running_fixture(
2840        home,
2841        &format!("task:{task}"),
2842        serde_json::to_value(request)?,
2843    )?;
2844    Ok(TaskWorkerLease {
2845        dir: home.join("workers").join("jobs").join(&job.id),
2846        job,
2847        lease: Some(lease),
2848    })
2849}
2850
2851fn task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2852    Ok(crate::worker::active(home)?
2853        .into_iter()
2854        .filter(|job| job.kind == "task")
2855        .collect())
2856}
2857
2858fn owned_task_jobs(home: &Path) -> Result<Vec<crate::worker::Job>> {
2859    task_jobs(home)?
2860        .into_iter()
2861        .filter_map(
2862            |job| match serde_json::from_value::<TaskWorker>(job.payload.clone()) {
2863                Ok(request) if !request.standalone => Some(Ok(job)),
2864                Ok(_) => None,
2865                Err(error) => Some(Err(error.into())),
2866            },
2867        )
2868        .collect()
2869}
2870
2871/// Whether an independent scheduler can be controlled without its web parent.
2872#[must_use]
2873pub fn managed(home: &Path) -> bool {
2874    match crate::worker::active(home) {
2875        Err(error) => {
2876            tracing::error!("cannot determine scheduler ownership: {error:#}");
2877            true
2878        }
2879        Ok(jobs) if jobs.iter().any(|j| j.kind == "scheduler") => true,
2880        Ok(_) => {
2881            read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2882                && crate::worker::try_lease(home, "scheduler").map_or(true, |lease| lease.is_none())
2883        }
2884    }
2885}
2886
2887/// Start a detached, singleton scheduler using this executable generation.
2888pub async fn spawn_detached(home: &Path, opts: &Opts) -> Result<crate::worker::Job> {
2889    anyhow::ensure!(
2890        crate::worker::control(home, "scheduler")?.is_none() || !managed(home),
2891        "the scheduler is stopping; wait for retirement before starting it again"
2892    );
2893    crate::worker::spawn(
2894        home,
2895        "scheduler",
2896        "scheduler",
2897        serde_json::to_value(opts.absolute()?)?,
2898    )
2899    .await
2900}
2901
2902fn park_request_path(home: &Path, job: &crate::worker::Job) -> PathBuf {
2903    home.join("worker-parks").join(format!("{}.json", job.id))
2904}
2905
2906fn request_task_park(
2907    home: &Path,
2908    job: &crate::worker::Job,
2909    cause: crate::run::ParkCause,
2910) -> Result<()> {
2911    let path = park_request_path(home, job);
2912    std::fs::create_dir_all(path.parent().context("worker park directory")?)?;
2913    std::fs::write(path, serde_json::to_vec(&cause)?)?;
2914    crate::worker::request(home, &job.key, crate::worker::Control::Park)
2915}
2916
2917/// Stop dispatch immediately; only an explicit park reaches existing workers.
2918pub fn request_control(home: &Path, control: crate::worker::Control) -> Result<()> {
2919    if control == crate::worker::Control::Park {
2920        for job in owned_task_jobs(home)? {
2921            request_task_park(home, &job, crate::run::ParkCause::Operator)?;
2922        }
2923    }
2924    crate::worker::request(home, "scheduler", control)
2925}
2926
2927/// Resolve what a restart would replace without signalling the scheduler.
2928pub(crate) fn scheduler_restart_options(home: &Path) -> Result<Option<Opts>> {
2929    if let Some(job) = crate::worker::active(home)?
2930        .into_iter()
2931        .find(|job| job.kind == "scheduler")
2932    {
2933        return serde_json::from_value(job.payload)
2934            .context("read detached scheduler options")
2935            .map(Some);
2936    }
2937    if read_status(home).is_some_and(|r| r.worker_protocol == Some(1))
2938        && crate::worker::try_lease(home, "scheduler")?.is_none()
2939    {
2940        let path = home.join("scheduler-options.json");
2941        let body = std::fs::read(&path).with_context(|| format!("read {}", path.display()))?;
2942        return serde_json::from_slice(&body)
2943            .context("decode detached scheduler options")
2944            .map(Some);
2945    }
2946    Ok(None)
2947}
2948
2949/// Replace the scheduler, leaving all active task and conversation jobs alone.
2950pub async fn restart_detached(home: &Path) -> Result<()> {
2951    let Some(opts) = scheduler_restart_options(home)? else {
2952        return Ok(());
2953    };
2954    request_control(home, crate::worker::Control::Stop)?;
2955    loop {
2956        let reserved = crate::worker::active(home)?
2957            .iter()
2958            .any(|job| job.kind == "scheduler");
2959        if !reserved && crate::worker::try_lease(home, "scheduler")?.is_some() {
2960            break;
2961        }
2962        tokio::time::sleep(Duration::from_millis(100)).await;
2963    }
2964    spawn_detached(home, &opts).await?;
2965    Ok(())
2966}
2967
2968/// Hidden worker dispatch entry. The worker infrastructure owns its job lease.
2969pub async fn run_scheduler_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2970    let opts: Opts = serde_json::from_value(payload)?;
2971    let _ = home;
2972    serve_until(opts, Stop::new()).await
2973}
2974
2975/// Execute and settle one task with the queue claim owned by this process.
2976pub async fn run_task_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
2977    let request: TaskWorker = serde_json::from_value(payload)?;
2978    let queue = Queue::at(request.queue);
2979    let key = format!("task:{}", request.task);
2980    let job = task_jobs(home)?
2981        .into_iter()
2982        .find(|job| job.key == key)
2983        .context("task worker reservation is missing")?;
2984    let park_path = park_request_path(home, &job);
2985    // The spawning CLI/scheduler still owns the claim until spawn acknowledges
2986    // our durable reservation. Never execute before that ownership hand-off.
2987    let _claim = loop {
2988        match queue.claim(&request.task) {
2989            Ok(claim) => break claim,
2990            // Only contention (the claim file exists) is worth waiting out; an
2991            // I/O failure must end this worker instead of pinning its lane.
2992            Err(e) if e.chain().any(|c| c.is::<std::io::Error>()) => {
2993                return Err(e.context("claim the task for its worker"));
2994            }
2995            Err(_) => {
2996                sweep_stale_claims(&queue, STALE_CLAIM);
2997                tokio::time::sleep(Duration::from_millis(50)).await;
2998            }
2999        }
3000    };
3001    let mut task = queue.get(&request.task)?;
3002    if !task.status.runnable()
3003        || (!request.standalone
3004            && request.lane
3005                != permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent))
3006    {
3007        return Ok(());
3008    }
3009    let stop = Stop::new();
3010    let watcher = {
3011        let home = home.to_path_buf();
3012        let stop = stop.clone();
3013        let park_path = park_path.clone();
3014        tokio::spawn(async move {
3015            loop {
3016                if crate::worker::control(&home, &key).ok().flatten().is_some() {
3017                    let cause = std::fs::read(&park_path)
3018                        .ok()
3019                        .and_then(|body| serde_json::from_slice(&body).ok())
3020                        .unwrap_or(crate::run::ParkCause::Operator);
3021                    stop.park(cause);
3022                    return;
3023                }
3024                tokio::time::sleep(Duration::from_millis(200)).await;
3025            }
3026        })
3027    };
3028    let quota = if request.standalone {
3029        run_claimed_until(&request.opts, &queue, &mut task, &stop).await
3030    } else {
3031        let status = Arc::new(Mutex::new(Status::new()));
3032        Box::pin(attempt(
3033            &request.opts,
3034            &queue,
3035            &status,
3036            &stop,
3037            crate::graph::Pause::new(),
3038            &mut task,
3039        ))
3040        .await
3041    };
3042    watcher.abort();
3043    let _ = std::fs::remove_file(park_path);
3044    persist_cooldown(home, &quota).await?;
3045    Ok(())
3046}
3047
3048/// Launch the standalone task worker with a claim-to-reservation handoff.
3049/// Returns only after the worker owns a durable execution reservation.
3050pub async fn spawn_claimed(
3051    home: &Path,
3052    opts: &Opts,
3053    queue: &Queue,
3054    task: &Task,
3055    claim: crate::queue::Claim,
3056) -> Result<crate::worker::Job> {
3057    let request = TaskWorker {
3058        opts: opts.absolute()?,
3059        queue: std::path::absolute(queue.root())?,
3060        task: task.id.clone(),
3061        lane: permit_kind(land_resume_state(task) == LandResume::Ready, task.urgent),
3062        standalone: true,
3063    };
3064    let job = crate::worker::spawn(
3065        home,
3066        "task",
3067        &format!("task:{}", task.id),
3068        serde_json::to_value(request)?,
3069    )
3070    .await?;
3071    drop(claim);
3072    Ok(job)
3073}
3074
3075/// Transfer a standalone caller's claim only after the detached worker is live,
3076/// then follow that worker to its final (non-automatically-retrying) outcome.
3077pub async fn run_detached_claimed(
3078    opts: &Opts,
3079    queue: &Queue,
3080    task: &mut Task,
3081    claim: crate::queue::Claim,
3082) -> Result<()> {
3083    let home = crate::run::home();
3084    let job = spawn_claimed(&home, opts, queue, task, claim).await?;
3085    loop {
3086        // Reconcile execution leases even without a scheduler. A dead worker
3087        // must become a reported failure, never an infinite persisted wait.
3088        crate::worker::active(&home)?;
3089        let current = crate::worker::get(&home, &job.id)?;
3090        if matches!(
3091            current.status,
3092            crate::worker::Status::Finished | crate::worker::Status::Failed
3093        ) {
3094            *task = queue.get(&task.id)?;
3095            anyhow::ensure!(
3096                current.status != crate::worker::Status::Failed,
3097                "task worker failed: {}",
3098                current.result.as_deref().unwrap_or("unknown failure")
3099            );
3100            return Ok(());
3101        }
3102        tokio::time::sleep(Duration::from_millis(200)).await;
3103    }
3104}
3105
3106async fn persist_cooldown(home: &Path, quota: &[QuotaLoss]) -> Result<()> {
3107    if let Some(until) = cooldown_until(quota, Timestamp::now()) {
3108        let _lease = loop {
3109            if let Some(lease) = crate::worker::try_lease(home, "task-quota-cooldown")? {
3110                break lease;
3111            }
3112            tokio::time::sleep(Duration::from_millis(10)).await;
3113        };
3114        if read_cooldown(home)?.is_none_or(|previous| previous < until) {
3115            let path = home.join("task-quota-cooldown.json");
3116            let temporary = path.with_extension("json.tmp");
3117            std::fs::write(&temporary, serde_json::to_vec(&until)?)?;
3118            std::fs::rename(temporary, path)?;
3119        }
3120    }
3121    Ok(())
3122}
3123
3124fn read_cooldown(home: &Path) -> Result<Option<Timestamp>> {
3125    match std::fs::read(home.join("task-quota-cooldown.json")) {
3126        Ok(body) => Ok(Some(serde_json::from_slice(&body)?)),
3127        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
3128        Err(error) => Err(error.into()),
3129    }
3130}
3131
3132/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
3133///
3134/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
3135/// sets, so there is one loop body rather than two that drift apart the first
3136/// time the retry policy changes on only one of them.
3137pub async fn serve(opts: Opts) -> Result<()> {
3138    tracing::info!(
3139        "automatic update and restart requires magi web; standalone serve does not restart"
3140    );
3141    serve_until(opts, Stop::new()).await
3142}
3143
3144/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
3145///
3146/// A stop retires dispatch promptly, including while a worker launch is being
3147/// acknowledged. Already reserved workers own their attempts independently and
3148/// finish with their started executable. Explicit park additionally forwards
3149/// durable park requests; neither scheduler retirement nor update does so.
3150///
3151/// While the queue is empty the stop is honoured within one wakeup rather than
3152/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
3153/// caller that taps stop does not sit through the remainder of a sleep.
3154pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
3155    let opts = opts.absolute()?;
3156    let home = crate::run::home();
3157    let _scheduler = crate::worker::try_lease(&home, "scheduler")?
3158        .context("another scheduler already owns this home")?;
3159    if let Some(reading) = read_status(&home)
3160        && legacy_scheduler_running(&reading, Timestamp::now(), std::process::id())
3161    {
3162        bail!("a legacy scheduler is still running; stop it before starting independent dispatch");
3163    }
3164    if !crate::worker::active(&home)?
3165        .iter()
3166        .any(|job| job.kind == "scheduler")
3167    {
3168        crate::worker::clear_control(&home, "scheduler")?;
3169    }
3170    std::fs::write(
3171        home.join("scheduler-options.json"),
3172        serde_json::to_vec(&opts)?,
3173    )?;
3174    let control = {
3175        let home = home.clone();
3176        let stop = stop.clone();
3177        tokio::spawn(async move {
3178            loop {
3179                match crate::worker::control(&home, "scheduler").ok().flatten() {
3180                    Some(crate::worker::Control::Park) => {
3181                        let _ = request_control(&home, crate::worker::Control::Park);
3182                        stop.park(crate::run::ParkCause::Operator);
3183                        break;
3184                    }
3185                    Some(crate::worker::Control::Stop) => {
3186                        stop.stop();
3187                        break;
3188                    }
3189                    None => {}
3190                }
3191                tokio::time::sleep(Duration::from_millis(100)).await;
3192            }
3193        })
3194    };
3195    let signal = {
3196        let stop = stop.clone();
3197        tokio::spawn(async move {
3198            if tokio::signal::ctrl_c().await.is_ok() {
3199                stop.stop();
3200                tracing::info!("scheduler shutdown requested; independent workers continue");
3201            }
3202        })
3203    };
3204
3205    let worktrees_root = opts
3206        .worktrees_root
3207        .clone()
3208        .unwrap_or_else(crate::run::default_worktree_root);
3209    let outcome = drive(
3210        &opts,
3211        &Queue::open(),
3212        &status_path(),
3213        &crate::run::home(),
3214        &worktrees_root,
3215        &stop,
3216    )
3217    .await;
3218
3219    signal.abort();
3220    control.abort();
3221    outcome
3222}
3223
3224/// The loop proper: setup, poll, teardown, with the queue and the status file
3225/// supplied rather than discovered.
3226///
3227/// All three of `home`, `worktrees_root` and the queue/status paths are
3228/// parameters rather than resolved here, for the same reason:
3229/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
3230/// so a unit test that pinned it would fight every other test in the binary,
3231/// and a loop that resolved its own worktree bay could only be exercised
3232/// against the operator's real `~/wt/<repo>` - publishing over a live
3233/// daemon's status file, claiming tasks out of a live backlog, and, since
3234/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
3235/// whatever the operator actually has on disk.
3236async fn drive(
3237    opts: &Opts,
3238    queue: &Queue,
3239    status_file: &Path,
3240    home: &Path,
3241    worktrees_root: &Path,
3242    stop: &Stop,
3243) -> Result<()> {
3244    // The status file is a *snapshot*, not a stream of events: a reader only
3245    // ever wants the latest values, and every tick rewrites the whole file
3246    // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
3247    // while an mpsc channel would force the loop to re-send unchanged fields on
3248    // every heartbeat — or the heartbeat to keep its own shadow copy of them —
3249    // for no gain. The lock is only ever held across a field assignment, never
3250    // across an await.
3251    let recovery_cfg = prepare(&opts.repo, opts).ok();
3252    let daemon_cfg = recovery_cfg
3253        .as_ref()
3254        .map(|c| c.daemon.clone())
3255        .unwrap_or_default();
3256    let reconciled = crate::driver::reconcile(home);
3257    if !reconciled.is_empty() {
3258        tracing::info!(runs = ?reconciled, "reconciled stopped run drivers at startup");
3259    }
3260    let mut initial_status = Status::new();
3261    let owned = owned_task_jobs(home)?;
3262    initial_status.current = current_work(home, Timestamp::now())
3263        .into_iter()
3264        .filter(|current| {
3265            owned
3266                .iter()
3267                .any(|job| job.key.strip_prefix("task:") == Some(current.task.as_str()))
3268        })
3269        .collect();
3270    initial_status.idle = initial_status.current.is_empty();
3271    initial_status.question_recovery = Some(crate::question_delivery::Recovery::new(
3272        recovery_cfg.as_ref(),
3273        daemon_cfg.max_deputies,
3274    ));
3275    let status = Arc::new(Mutex::new(initial_status));
3276    write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
3277    let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
3278
3279    // Read once at startup, not per task: how many runs this loop drives at
3280    // once is a property of the machine running it, not of whichever
3281    // repository a given task happens to name - see
3282    // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
3283    // fact in the same sense the agent roster is.
3284    let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
3285
3286    tracing::info!(
3287        "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
3288        queue.root().display(),
3289        opts.poll.as_secs(),
3290        opts.max_attempts,
3291        concurrency,
3292        if daemon_cfg.pause_for_interrupts {
3293            ", interrupts enabled"
3294        } else {
3295            ""
3296        }
3297    );
3298
3299    let outcome = tokio::select! {
3300        outcome = poll(opts, queue, &status, home, worktrees_root, stop, DispatchLimits {
3301            max_concurrent: concurrency,
3302            pause_for_interrupts: daemon_cfg.pause_for_interrupts,
3303            recovery_cfg,
3304        }) => outcome,
3305        () = async {
3306            while !stop.stopped() {
3307                tokio::time::sleep(Duration::from_millis(25)).await;
3308            }
3309        } => {
3310            if stop.parking() {
3311                request_control(home, crate::worker::Control::Park)?;
3312            }
3313            Ok(())
3314        }
3315    };
3316
3317    stop.busy.store(0, Ordering::SeqCst);
3318    beat.abort();
3319    clear_status_at(status_file);
3320    outcome
3321}
3322
3323/// The checkouts the release watcher covers and `[daemon] release_stall_minutes`,
3324/// re-read each lap. An unreadable config yields `0` minutes: the watcher idles.
3325pub(crate) fn release_watch_settings_from_config(
3326    home: &Path,
3327    repo: &Path,
3328    cfg: &Config,
3329) -> (Vec<PathBuf>, u64) {
3330    let mut paths: Vec<PathBuf> = crate::repos::scan(&cfg.repos.roots)
3331        .into_iter()
3332        .map(|r| r.path)
3333        .collect();
3334    // Repositories the daemon has worked in, wherever they live: a task may
3335    // name one outside `[repos] roots`, and its release PR must be watched too.
3336    let mut known: Vec<PathBuf> = Queue::at(home.join("queue"))
3337        .list()
3338        .into_iter()
3339        .map(|t| t.repo)
3340        .collect();
3341    let runs = home.join("runs");
3342    for id in crate::run::list_ids_in(&runs) {
3343        let repo = std::fs::read_to_string(runs.join(&id).join("run.json"))
3344            .ok()
3345            .and_then(|s| serde_json::from_str::<serde_json::Value>(&s).ok())
3346            .and_then(|v| v.get("repo")?.as_str().map(PathBuf::from));
3347        known.extend(repo);
3348    }
3349    for k in known {
3350        let k = k.canonicalize().unwrap_or(k);
3351        if k.join(".git").exists() && !paths.contains(&k) {
3352            paths.push(k);
3353        }
3354    }
3355    let own = repo.canonicalize().unwrap_or_else(|_| repo.to_path_buf());
3356    if !paths.contains(&own) {
3357        paths.push(own);
3358    }
3359    (paths, cfg.daemon.release_stall_minutes)
3360}
3361
3362/// Per-repo bound on one `git fetch`, so a dead remote cannot stall the pass.
3363const FETCH_TIMEOUT: Duration = Duration::from_secs(30);
3364
3365/// Refresh the status file on a fixed tick.
3366///
3367/// Separate from the loop because a run takes tens of minutes: a status file
3368/// written only between tasks would look stale for the whole of every run, and
3369/// a reader would report the daemon dead exactly while it was busiest.
3370async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
3371    loop {
3372        tokio::time::sleep(HEARTBEAT).await;
3373        let snapshot = {
3374            let mut guard = lock(&status);
3375            guard.updated_at = Timestamp::now();
3376            guard.clone()
3377        };
3378        if let Err(e) = write_status_to(&path, &snapshot) {
3379            // A failed heartbeat must not take the daemon down: the loop is the
3380            // product, the status file is only the window onto it.
3381            tracing::warn!("could not refresh the daemon status file: {e:#}");
3382        }
3383    }
3384}
3385
3386/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
3387/// if so, whether that wait is over.
3388#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3389enum LandResume {
3390    /// The task's last run is not parked on a land approval; schedule it
3391    /// like any other candidate.
3392    NotLanding,
3393    /// Parked in `land`, waiting on a question nobody has answered yet.
3394    /// Left alone: attempting it now would only re-observe the same pull
3395    /// request and park again, spending a `gh` call on a decision that has
3396    /// not changed since the last time this was checked.
3397    StillWaiting,
3398    /// Parked in `land`, and the question is settled - answered or
3399    /// abandoned. Resuming this is the one kind of candidate that must not
3400    /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
3401    Ready,
3402}
3403
3404/// Classify a runnable candidate by whether it is parked on a land-merge
3405/// approval. Read-only - no claim taken, nothing written - so it is cheap
3406/// enough to call on every candidate, every poll.
3407fn land_resume_state(task: &Task) -> LandResume {
3408    if task.sync_only.is_some() {
3409        return LandResume::NotLanding;
3410    }
3411    let Some(run_id) = task.execution_runs().last() else {
3412        return LandResume::NotLanding;
3413    };
3414    let Ok(state) = RunState::load(run_id) else {
3415        return LandResume::NotLanding;
3416    };
3417    if !state.parked {
3418        return LandResume::NotLanding;
3419    }
3420    if state.status == RunStatus::Landing
3421        && state.land_approval.as_ref().is_some_and(|binding| {
3422            ask::Questions::open()
3423                .get_for_effects(&binding.question)
3424                .is_ok_and(|q| {
3425                    q.run == state.id
3426                        && q.resolution()
3427                            .as_deref()
3428                            .is_some_and(crate::merge_decision::stops)
3429                })
3430        })
3431    {
3432        return LandResume::Ready;
3433    }
3434    if !implementers_match(task, &state) {
3435        return LandResume::NotLanding;
3436    }
3437    // Parked in `land` on the merge approval, or at `merge` on the owner's
3438    // word about a title/body the posting gate withheld. Told apart by the
3439    // run's own record, not by a status both can share.
3440    let node = if state.status == RunStatus::Landing {
3441        land::APPROVAL_NODE
3442    } else if state.github_text.as_ref().is_some_and(|g| !g.resolved) {
3443        crate::github_text::ASK_NODE
3444    } else {
3445        return LandResume::NotLanding;
3446    };
3447    let store = ask::Questions::open();
3448    let waiting = store
3449        .list_for_effects()
3450        .into_iter()
3451        .filter(|q| &q.run == run_id && q.node == node)
3452        .max_by(|a, b| a.id.cmp(&b.id));
3453    let Some(mut q) = waiting else {
3454        return LandResume::Ready;
3455    };
3456    if !q.status.open() {
3457        // Repair spends agent resources and must obey concurrency and quota
3458        // waits; only a merge/hold decision may use the decision-only lane.
3459        if q.resolution().as_deref() == Some(land::REPAIR) {
3460            return if state.liveness(false) == Liveness::Live {
3461                LandResume::StillWaiting
3462            } else {
3463                LandResume::NotLanding
3464            };
3465        }
3466        return LandResume::Ready;
3467    }
3468    // `ask::ask_and_wait`'s own deadline is what used to retire a question
3469    // nobody ever answered; land's approval bypasses that wait entirely (see
3470    // `land::approval_gate`), so the same deadline has to be enforced here
3471    // instead, or `graph.answer_timeout` silently stops meaning anything for
3472    // a land approval and a run can sit `StillWaiting` forever with nobody
3473    // told to look at it.
3474    let timeout = Duration::from_secs(state.config.graph.answer_timeout);
3475    let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
3476    if !store.held_reply(&q.id) && elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
3477        q.abandon(format!(
3478            "no answer within {}s of asking",
3479            timeout.as_secs().max(1)
3480        ));
3481        // If this can't be persisted, do not treat the wait as settled on a
3482        // guess: fall through and try again next poll.
3483        if store.put(&mut q).is_ok() {
3484            return LandResume::Ready;
3485        }
3486    }
3487    LandResume::StillWaiting
3488}
3489
3490/// How often the loop rechecks for new work while something it already
3491/// started is still running, rather than sleeping out the whole
3492/// [`Opts::poll`] interval.
3493///
3494/// Short on purpose: this is what lets a land-merge approval that comes back
3495/// while another task is mid-competition be noticed and resumed within a
3496/// fraction of a second, not within the next multi-second poll.
3497const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
3498
3499/// How often [`poll`] rechecks the shared build cache against its cap at a
3500/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
3501/// waiting for the queue to run dry.
3502///
3503/// A queue that never empties means the `janitor` call at the bottom of this
3504/// loop's fully-idle branch can go unreached for as long as the backlog
3505/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
3506/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
3507/// 81.8 GiB an idle-only check let it reach before this existed, and it is
3508/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
3509/// backlog of short tasks does not pay for that walk on every poll.
3510const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
3511
3512/// State of [`poll`]'s own interrupt-scheduling sequence - see
3513/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
3514/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
3515/// both kept free of `Task`'s non-identity fields on purpose: every decision
3516/// here turns only on task ids and which ones are in flight, so the "never
3517/// more than one run at once" and "exactly one resume" invariants can be
3518/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
3519/// queue - which is exactly the coverage this feature's first two attempts
3520/// were missing.
3521///
3522/// Persisted after every transition, so scheduler replacement preserves the
3523/// interrupt's exclusive turn and the interrupted task's priority resume.
3524#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3525enum Interrupt {
3526    /// No interrupt sequence in progress. Ordinary dispatch applies.
3527    Idle,
3528    /// `interrupt_task` is runnable and exactly one other run is in flight;
3529    /// `parked` names that one task's id. Dispatch is withheld from
3530    /// everyone, including `interrupt_task` itself, until it has left
3531    /// flight - only then is `interrupt_task` let through.
3532    ///
3533    /// `parked` is a `Vec` rather than a bare id for symmetry with
3534    /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
3535    /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
3536    /// when exactly one run is in flight, so it is guaranteed to hold
3537    /// exactly one entry in practice - see that branch's own doc for why
3538    /// more than one is deliberately never attempted.
3539    Parking {
3540        parked: Vec<String>,
3541        interrupt_task: String,
3542    },
3543    /// `interrupt_task` is dispatched and in flight alone. Dispatch is
3544    /// withheld from everyone until it leaves flight - merged, failed, held,
3545    /// it makes no difference - at which point the sequence moves to
3546    /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
3547    /// going straight to `Idle` would hand `parked` back to ordinary
3548    /// priority-order dispatch, where a higher-priority task filed in the
3549    /// meantime could start ahead of it.
3550    Running {
3551        parked: Vec<String>,
3552        interrupt_task: String,
3553    },
3554    /// `interrupt_task` left flight; `parked` still names the one run this
3555    /// sequence owes a resume. Dispatch is withheld from everyone except
3556    /// that task - see [`interrupt_gate`] - so the resume this feature
3557    /// promises is never raced by, or run alongside, an unrelated candidate.
3558    /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
3559    /// own doc on abandonment - the moment it is no longer runnable at all.
3560    Resuming { parked: Vec<String> },
3561}
3562
3563/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
3564/// and `runnable` are read-only snapshots of this tick's reality, and the
3565/// only side effect the caller still owes the world is asking whichever
3566/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
3567/// site.
3568///
3569/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
3570/// accepted rather than a narrower type because that is what [`poll`] already
3571/// has on hand from [`runnable`], and building a second, smaller list on
3572/// every tick just to satisfy this signature would cost more than it proves.
3573///
3574/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
3575/// back to a task they are waiting on no longer being [`runnable`] - held,
3576/// blocked, deleted, or finished by some other means entirely, all of which
3577/// an operator can do to a task sitting in the queue with no claim on it at
3578/// all, at any moment, interrupt sequence or not. Without this check the
3579/// sequence would wait forever for a dispatch that can never come, and
3580/// `interrupt_gate` would withhold every other task in the queue right along
3581/// with it - a single `magi task hold` on the wrong id turning into a
3582/// daemon that never dispatches anything again.
3583fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
3584    match state {
3585        Interrupt::Idle => {
3586            // Not just "something to interrupt": exactly one thing. More
3587            // than one run in flight only happens above the default
3588            // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
3589            // one resume, never run alongside anything else" only because
3590            // it is only ever seeded with exactly one id - see
3591            // `Interrupt::Resuming`'s own doc on why releasing more than one
3592            // parked id back to ordinary dispatch cannot be made safe
3593            // against that same setting's own extra concurrency slots.
3594            // Waiting here for the herd to settle to one is the
3595            // simplification this feature's own constraints ask for rather
3596            // than a second concurrency model to reconcile with the first.
3597            if in_flight.len() != 1 {
3598                return Interrupt::Idle;
3599            }
3600            match runnable.iter().find(|t| t.interrupt) {
3601                Some(t) => Interrupt::Parking {
3602                    parked: in_flight.to_vec(),
3603                    interrupt_task: t.id.clone(),
3604                },
3605                None => Interrupt::Idle,
3606            }
3607        }
3608        Interrupt::Parking {
3609            parked,
3610            interrupt_task,
3611        } => {
3612            if in_flight.iter().any(|id| parked.contains(id)) {
3613                // Still waiting for what was in flight to actually stop.
3614                Interrupt::Parking {
3615                    parked,
3616                    interrupt_task,
3617                }
3618            } else if in_flight.contains(&interrupt_task) {
3619                Interrupt::Running {
3620                    parked,
3621                    interrupt_task,
3622                }
3623            } else if runnable.iter().any(|t| t.id == interrupt_task) {
3624                // The parked run(s) are gone, but the interrupt task has not
3625                // been dispatched yet on this tick - `interrupt_gate` is
3626                // what lets it through next.
3627                Interrupt::Parking {
3628                    parked,
3629                    interrupt_task,
3630                }
3631            } else {
3632                // The interrupt task itself is no longer runnable - see this
3633                // function's own doc on abandonment. The parked run(s) still
3634                // get their guaranteed resume; there is simply no interrupt
3635                // to run ahead of them any longer.
3636                Interrupt::Resuming { parked }
3637            }
3638        }
3639        Interrupt::Running {
3640            parked,
3641            interrupt_task,
3642        } => {
3643            if in_flight.contains(&interrupt_task) {
3644                Interrupt::Running {
3645                    parked,
3646                    interrupt_task,
3647                }
3648            } else {
3649                // The interrupt task's own run reached a terminal status,
3650                // whichever one - this is the *only* trigger that moves the
3651                // sequence on, driven straight off the same in-flight
3652                // bookkeeping `poll` already reaps every tick, not a second,
3653                // independent poll of anything.
3654                Interrupt::Resuming { parked }
3655            }
3656        }
3657        Interrupt::Resuming { parked } => {
3658            if in_flight.iter().any(|id| parked.contains(id)) {
3659                // One of the parked runs has been dispatched - the resume
3660                // this sequence owed is fulfilled. Whatever else is left in
3661                // `parked` (ordinarily nothing, at the default concurrency
3662                // of one) rejoins ordinary priority-order dispatch, same as
3663                // any other runnable task.
3664                Interrupt::Idle
3665            } else if runnable.iter().any(|t| parked.contains(&t.id)) {
3666                Interrupt::Resuming { parked }
3667            } else {
3668                // Abandonment (see this function's own doc): nothing left in
3669                // `parked` is even runnable any longer.
3670                Interrupt::Idle
3671            }
3672        }
3673    }
3674}
3675
3676/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
3677/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
3678/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
3679/// indistinguishable from any other runnable task - exactly the "off does
3680/// nothing" this feature promises.
3681fn advance_interrupt_tick(
3682    enabled: bool,
3683    state: Interrupt,
3684    in_flight: &[String],
3685    runnable: &[Task],
3686) -> Interrupt {
3687    if !enabled {
3688        return Interrupt::Idle;
3689    }
3690    advance_interrupt(state, in_flight, runnable)
3691}
3692
3693/// Which of this tick's runnable candidates the interrupt sequence actually
3694/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
3695/// each half is assertable on its own: this is the half that keeps a
3696/// competition and an interrupt from ever running at the same moment.
3697fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
3698    match state {
3699        Interrupt::Idle => candidates,
3700        Interrupt::Parking {
3701            parked,
3702            interrupt_task,
3703        } => {
3704            if in_flight.iter().any(|id| parked.contains(id)) {
3705                Vec::new()
3706            } else {
3707                candidates
3708                    .into_iter()
3709                    .filter(|t| &t.id == interrupt_task)
3710                    .collect()
3711            }
3712        }
3713        Interrupt::Running { .. } => Vec::new(),
3714        // At most one: even if `parked` names more than one id (more than
3715        // one run was in flight when the sequence began, only possible
3716        // above the default `max_concurrent_runs = 1`), only the first match
3717        // is offered. Capping this to a single candidate - not merely to
3718        // `parked`'s own ids - is what makes "exactly one resume, never two
3719        // dispatched together" true regardless of how many ordinary slots
3720        // happen to be free this tick.
3721        Interrupt::Resuming { parked } => candidates
3722            .into_iter()
3723            .find(|t| parked.contains(&t.id))
3724            .into_iter()
3725            .collect(),
3726    }
3727}
3728
3729/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
3730/// bundled into one parameter so `poll`'s own signature stays readable -
3731/// see [`drive`]'s call site for where these are actually read.
3732struct DispatchLimits {
3733    /// How many *ordinary* candidates run at once. See
3734    /// [`crate::config::Daemon::max_concurrent_runs`].
3735    max_concurrent: usize,
3736    /// See [`crate::config::Daemon::pause_for_interrupts`].
3737    pause_for_interrupts: bool,
3738    recovery_cfg: Option<Config>,
3739}
3740
3741/// Which semaphore, if any, dispatching a candidate should draw its permit
3742/// from.
3743///
3744/// Pure and separate from [`poll`]'s loop body for the same reason
3745/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
3746/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
3747/// exactly the policy this feature adds, and a policy only exercisable by
3748/// running the whole loop is a policy nobody checks.
3749#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
3750enum PermitKind {
3751    /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
3752    /// Checked first - a task can be both a land resume and marked
3753    /// [`Task::urgent`], and the resume's own "must not queue behind
3754    /// anything" guarantee takes precedence.
3755    None,
3756    /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
3757    /// (never in addition to trying) the ordinary pool. This is what lets
3758    /// an urgent task dispatch while every ordinary slot is already checked
3759    /// out, and what stops a second urgent task from opening a third run: it
3760    /// waits on this same one-slot semaphore rather than falling through to
3761    /// the ordinary one.
3762    Urgent,
3763    /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
3764    /// above.
3765    #[default]
3766    Ordinary,
3767}
3768
3769/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
3770/// own boolean, already computed by the caller from [`land_resume_state`].
3771fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
3772    if priority {
3773        PermitKind::None
3774    } else if urgent {
3775        PermitKind::Urgent
3776    } else {
3777        PermitKind::Ordinary
3778    }
3779}
3780
3781fn available_slots(requests: &[TaskWorker], limit: usize) -> (usize, usize) {
3782    let (ordinary, urgent) = requests.iter().filter(|request| !request.standalone).fold(
3783        (0usize, 0usize),
3784        |(ordinary, urgent), request| match request.lane {
3785            PermitKind::Ordinary => (ordinary + 1, urgent),
3786            PermitKind::Urgent => (ordinary, urgent + 1),
3787            PermitKind::None => (ordinary, urgent),
3788        },
3789    );
3790    (
3791        limit.saturating_sub(ordinary),
3792        1usize.saturating_sub(urgent),
3793    )
3794}
3795
3796/// Why a runnable candidate was not dispatched. This does not alter policy.
3797#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
3798enum SkipReason {
3799    ClaimUnavailable,
3800    RereadFailed,
3801    NoLongerRunnable,
3802    WaitingOnLanding,
3803    CoolingDown,
3804    OrdinaryCapacity,
3805    UrgentCapacity,
3806    InterruptGate,
3807}
3808
3809impl SkipReason {
3810    fn key(self) -> &'static str {
3811        match self {
3812            Self::ClaimUnavailable => "claim_unavailable",
3813            Self::RereadFailed => "reread_failed",
3814            Self::NoLongerRunnable => "no_longer_runnable",
3815            Self::WaitingOnLanding => "waiting_on_landing",
3816            Self::CoolingDown => "cooling_down",
3817            Self::OrdinaryCapacity => "ordinary_capacity",
3818            Self::UrgentCapacity => "urgent_capacity",
3819            Self::InterruptGate => "interrupt_gate",
3820        }
3821    }
3822
3823    fn describe(self) -> &'static str {
3824        match self {
3825            Self::ClaimUnavailable => "could not claim it (held elsewhere or claim failed)",
3826            Self::RereadFailed => "could not re-read it",
3827            Self::NoLongerRunnable => "no longer runnable",
3828            Self::WaitingOnLanding => "waiting on landing",
3829            Self::CoolingDown => "quota cooldown",
3830            Self::OrdinaryCapacity => "no free ordinary slot",
3831            Self::UrgentCapacity => "urgent slot busy",
3832            Self::InterruptGate => "withheld by the interrupt sequence",
3833        }
3834    }
3835}
3836
3837/// A reason count from a completed dispatch scan.
3838#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3839pub struct DispatchReasonCount {
3840    /// Stable string key, so readers can preserve future reasons.
3841    pub reason: String,
3842    /// Candidates skipped for this reason.
3843    pub count: usize,
3844}
3845
3846/// Observations from a completed scan, not a fresh queue estimate.
3847#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3848pub struct DispatchWait {
3849    /// Runnable candidates before the interrupt gate.
3850    pub runnable: usize,
3851    /// Counts in descending order, with stable reason order for ties.
3852    pub reasons: Vec<DispatchReasonCount>,
3853}
3854
3855type DispatchSkips = std::collections::BTreeSet<(String, SkipReason)>;
3856
3857fn aggregate_dispatch_wait(runnable: usize, skips: &DispatchSkips) -> Option<DispatchWait> {
3858    if runnable == 0 {
3859        return None;
3860    }
3861    let mut counts = std::collections::BTreeMap::new();
3862    for (_, reason) in skips {
3863        *counts.entry(*reason).or_insert(0usize) += 1;
3864    }
3865    let mut counts: Vec<_> = counts.into_iter().collect();
3866    counts.sort_by(|(a, n), (b, m)| m.cmp(n).then(a.cmp(b)));
3867    Some(DispatchWait {
3868        runnable,
3869        reasons: counts
3870            .into_iter()
3871            .map(|(reason, count)| DispatchReasonCount {
3872                reason: reason.key().to_owned(),
3873                count,
3874            })
3875            .collect(),
3876    })
3877}
3878
3879fn interrupt_skips(before: &[String], after: &[Task]) -> DispatchSkips {
3880    before
3881        .iter()
3882        .filter(|id| !after.iter().any(|task| &task.id == *id))
3883        .map(|id| (id.clone(), SkipReason::InterruptGate))
3884        .collect()
3885}
3886
3887fn changed_dispatch_skips(previous: &mut DispatchSkips, current: DispatchSkips) -> bool {
3888    if *previous == current {
3889        return false;
3890    }
3891    *previous = current;
3892    true
3893}
3894
3895struct DispatchClaim {
3896    task: Task,
3897    claim: crate::queue::Claim,
3898    permit: Option<tokio::sync::OwnedSemaphorePermit>,
3899}
3900
3901/// Claim and re-read before choosing a lane: a queue listing may predate an
3902/// urgent toggle. All unsuccessful paths release the claim without an attempt.
3903fn claim_dispatch(
3904    queue: &Queue,
3905    candidate: &Task,
3906    cooling_down: bool,
3907    ordinary: &Arc<tokio::sync::Semaphore>,
3908    urgent: &Arc<tokio::sync::Semaphore>,
3909) -> std::result::Result<DispatchClaim, SkipReason> {
3910    let claim = queue
3911        .claim(&candidate.id)
3912        .map_err(|_| SkipReason::ClaimUnavailable)?;
3913    let task = match queue.get(&candidate.id) {
3914        Ok(t) if t.status.runnable() => t,
3915        Ok(_) => return Err(SkipReason::NoLongerRunnable),
3916        Err(e) => {
3917            tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
3918            return Err(SkipReason::RereadFailed);
3919        }
3920    };
3921    if let Some(hold) = crate::head_e2e_stop::dispatch_hold(queue, &task) {
3922        let mut held = task;
3923        hold.apply(&mut held);
3924        record(queue, &mut held);
3925        return Err(SkipReason::NoLongerRunnable);
3926    }
3927    let resume = land_resume_state(&task);
3928    if resume == LandResume::StillWaiting {
3929        return Err(SkipReason::WaitingOnLanding);
3930    }
3931    let priority = resume == LandResume::Ready;
3932    if !priority && cooling_down {
3933        return Err(SkipReason::CoolingDown);
3934    }
3935    // Never borrow an ordinary slot when the single urgent slot is busy.
3936    // Keep scanning other candidates when either pool has no free slot.
3937    let permit = match permit_kind(priority, task.urgent) {
3938        PermitKind::None => None,
3939        PermitKind::Urgent => Some(
3940            Arc::clone(urgent)
3941                .try_acquire_owned()
3942                .map_err(|_| SkipReason::UrgentCapacity)?,
3943        ),
3944        PermitKind::Ordinary => Some(
3945            Arc::clone(ordinary)
3946                .try_acquire_owned()
3947                .map_err(|_| SkipReason::OrdinaryCapacity)?,
3948        ),
3949    };
3950    // Persist the dispatch order under the claim, before config discovery or
3951    // coordination waits can reorder concurrent starts.
3952    let stamp = Timestamp::now();
3953    let mut task = task;
3954    task.dispatched_at = Some(stamp);
3955    if let Err(e) = queue.modify(&task.id, |t| {
3956        t.dispatched_at = Some(stamp);
3957        true
3958    }) {
3959        tracing::warn!("could not record dispatch order of {}: {e:#}", task.short());
3960    }
3961    Ok(DispatchClaim {
3962        task,
3963        claim,
3964        permit,
3965    })
3966}
3967
3968/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
3969/// teardown and cannot skip the teardown on an early return.
3970///
3971/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
3972/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
3973/// land approval that has since been answered is dispatched outside that
3974/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
3975/// the whole point of parking there is that it must not queue behind
3976/// whatever else the loop happens to be running, even at the default of one.
3977/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
3978/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
3979/// these exemptions is still subject to the interrupt gate below, urgent
3980/// included: a land-resume or urgent candidate is exactly as much "something
3981/// else running" as an ordinary one from the interrupt sequence's point of
3982/// view, and letting either slip through while a run is being parked, or
3983/// while the interrupt task itself has the floor, is precisely the second
3984/// run 75dd's own "at most one run, ever, at once" guarantee must never
3985/// allow - see [`Interrupt`]'s own doc.
3986#[derive(Serialize, Deserialize)]
3987struct ServiceWorker {
3988    opts: Opts,
3989    queue: PathBuf,
3990    worktrees_root: PathBuf,
3991    operation: String,
3992}
3993
3994fn load_conductor(home: &Path) -> Result<Conductor> {
3995    match std::fs::read(home.join("conductor-state.json")) {
3996        Ok(body) => serde_json::from_slice(&body).context("read conductor state"),
3997        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Conductor::new()),
3998        Err(error) => Err(error.into()),
3999    }
4000}
4001
4002fn conductor_work(queue: &Queue, home: &Path) -> (Vec<Task>, Vec<Task>, Vec<Task>) {
4003    let live: std::collections::BTreeSet<_> = current_work(home, Timestamp::now())
4004        .into_iter()
4005        .map(|c| c.task)
4006        .collect();
4007    let stalled = stalled_tasks(queue, home, Timestamp::now());
4008    let stalled_ids: std::collections::BTreeSet<_> = stalled.iter().map(|t| t.id.clone()).collect();
4009    let finished = finished_tasks(queue)
4010        .into_iter()
4011        .filter(|t| !live.contains(&t.id) && !stalled_ids.contains(&t.id))
4012        .filter(|t| !awaiting_resume_with(t, |id| RunState::load_under(id, home)))
4013        .collect();
4014    let queued = queued_tasks(queue)
4015        .into_iter()
4016        .filter(|t| !live.contains(&t.id))
4017        .collect();
4018    (queued, stalled, finished)
4019}
4020
4021// Separate latest dispatch and worker receipts expose version handoff and skips
4022// without erasing the last completed scan or treating observations as authority.
4023fn retention_service_receipt(
4024    home: &Path,
4025    operation: &str,
4026    phase: &str,
4027    outcome: &str,
4028    detail: &str,
4029    cfg: Option<&Config>,
4030) {
4031    if !matches!(operation, "housekeeping" | "disk-pressure") {
4032        return;
4033    }
4034    let receipt = serde_json::json!({"checked_at": Timestamp::now(),
4035        "version": env!("CARGO_PKG_VERSION"), "pid": std::process::id(),
4036        "operation": operation, "outcome": outcome, "detail": detail,
4037        "auto_fold": cfg.map(|c| c.disk.auto_fold),
4038        "reclaim_bytes": cfg.map(|c| c.disk.worktree_reclaim_bytes)});
4039    if let Err(error) = crate::fold_evidence::atomic_write(
4040        &home.join(format!("source-eviction-{operation}-{phase}.json")),
4041        &serde_json::to_vec(&receipt).expect("service receipt"),
4042    ) {
4043        tracing::warn!("retention service receipt failed: {error:#}");
4044    }
4045}
4046
4047async fn start_service(
4048    home: &Path,
4049    opts: &Opts,
4050    queue: &Queue,
4051    worktrees_root: &Path,
4052    operation: &str,
4053    cfg: Option<&Config>,
4054    busy: bool,
4055) -> Result<()> {
4056    // Fetch policy is live configuration, unlike question recovery capacity.
4057    // Reload before both cadence and eligibility, including disabled -> enabled.
4058    let fetch_cfg = if operation == "fetch" {
4059        match prepare(&opts.repo, opts) {
4060            Ok(cfg) => Some(cfg),
4061            Err(error) => {
4062                tracing::warn!("could not reload periodic fetch configuration: {error:#}");
4063                return Ok(());
4064            }
4065        }
4066    } else {
4067        None
4068    };
4069    let cfg = fetch_cfg.as_ref().or(cfg);
4070    let ticks = home.join("service-ticks");
4071    std::fs::create_dir_all(&ticks)?;
4072    let receipt = ticks.join(format!("daemon-{operation}"));
4073    let last = std::fs::read(&receipt)
4074        .ok()
4075        .and_then(|body| serde_json::from_slice::<Timestamp>(&body).ok());
4076    let interval = match operation {
4077        "disk-pressure" => 30,
4078        "chat-goals" => 60,
4079        "cache" => CACHE_CHECK_INTERVAL_SECS,
4080        "fetch" => cfg.map_or(60, |cfg| cfg.repos.fetch_interval.max(1)),
4081        _ => opts.poll.as_secs().max(1),
4082    };
4083    let now = Timestamp::now();
4084    if !cache_check_due(last, now, interval) {
4085        retention_service_receipt(
4086            home,
4087            operation,
4088            "dispatch",
4089            "skipped",
4090            "cadence not due",
4091            cfg,
4092        );
4093        return Ok(());
4094    }
4095    let key = format!("service:daemon-{operation}");
4096    if crate::worker::active(home)?
4097        .iter()
4098        .any(|job| job.key == key)
4099    {
4100        retention_service_receipt(
4101            home,
4102            operation,
4103            "dispatch",
4104            "skipped",
4105            "service worker already active",
4106            cfg,
4107        );
4108        return Ok(());
4109    }
4110    let eligible = match operation {
4111        "conductor" => {
4112            let (queued, stalled, finished) = conductor_work(queue, home);
4113            !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4114                && load_conductor(home)?.worth_a_look(queue, &stalled, &finished)
4115        }
4116        "maintenance" => {
4117            queue.list().iter().any(|task| {
4118                crate::triage::disk_wait_eligible(task)
4119                    && task
4120                        .disk_checked_at
4121                        .is_none_or(|at| now.as_second() - at.as_second() >= 60)
4122            }) || Questions::at(home.join("questions"))
4123                .list_for_effects()
4124                .iter()
4125                .any(|q| {
4126                    q.chosen_action().is_some_and(|action| action.maintenance())
4127                        && !home
4128                            .join("choice-actions")
4129                            .join(format!("{}.json", q.id))
4130                            .exists()
4131                })
4132        }
4133        "housekeeping" => !busy && runnable(queue).is_empty(),
4134        "cache" => {
4135            !busy
4136                && !runnable(queue).is_empty()
4137                && cfg.is_some_and(|cfg| cfg.disk.cache_limit_bytes > 0)
4138        }
4139        "disk-pressure" => busy,
4140        "fetch" => {
4141            cfg.is_some_and(|cfg| cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty())
4142        }
4143        "chat-goals" => crate::talk::Talks::at(home.join("talks"))
4144            .list()
4145            .iter()
4146            .any(|talk| {
4147                talk.status.open()
4148                    && talk.pending.is_empty()
4149                    && talk.pending_attachments.is_empty()
4150                    && talk.goals.iter().any(|goal| goal.active())
4151            }),
4152        _ => false,
4153    };
4154    if !eligible {
4155        retention_service_receipt(
4156            home,
4157            operation,
4158            "dispatch",
4159            "skipped",
4160            if operation == "housekeeping" {
4161                "active work or runnable task queue"
4162            } else {
4163                "no active work; idle housekeeping owns scan"
4164            },
4165            cfg,
4166        );
4167        return Ok(());
4168    }
4169    retention_service_receipt(
4170        home,
4171        operation,
4172        "dispatch",
4173        "launching",
4174        "eligible and cadence due",
4175        cfg,
4176    );
4177    let request = ServiceWorker {
4178        opts: opts.absolute()?,
4179        queue: std::path::absolute(queue.root())?,
4180        worktrees_root: std::path::absolute(worktrees_root)?,
4181        operation: operation.to_owned(),
4182    };
4183    if let Err(error) =
4184        crate::worker::spawn(home, "daemon-service", &key, serde_json::to_value(request)?).await
4185    {
4186        retention_service_receipt(
4187            home,
4188            operation,
4189            "dispatch",
4190            "error",
4191            &format!("worker launch: {error:#}"),
4192            cfg,
4193        );
4194        tracing::warn!(operation, "could not launch daemon service: {error:#}");
4195    }
4196    std::fs::write(receipt, serde_json::to_vec(&now)?)?;
4197    Ok(())
4198}
4199
4200/// Finite maintenance jobs survive scheduler replacement without duplicating
4201/// agent calls or cancelling an operation between its effect and receipt.
4202pub async fn run_service_worker(home: &Path, payload: serde_json::Value) -> Result<()> {
4203    let request: ServiceWorker = serde_json::from_value(payload)?;
4204    let opts = &request.opts;
4205    let queue = Queue::at(request.queue);
4206    let questions = Questions::at(home.join("questions"));
4207    match request.operation.as_str() {
4208        "chat-goals" => {
4209            let talks = crate::talk::Talks::at(home.join("talks"));
4210            crate::chat_goal_runtime::sweep(&talks, false).await;
4211        }
4212        "maintenance" => {
4213            apply_maintenance_choices(&queue, &questions, home).await;
4214            triage::monitor_disk_waits(
4215                &queue,
4216                &questions,
4217                opts.config.as_deref(),
4218                Timestamp::now(),
4219            );
4220        }
4221        "conductor" => {
4222            let path = home.join("conductor-state.json");
4223            let mut conductor = load_conductor(home)?;
4224            let (queued, stalled, finished) = conductor_work(&queue, home);
4225            if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
4226                && conductor.worth_a_look(&queue, &stalled, &finished)
4227            {
4228                let cfg = prepare(&opts.repo, opts)?;
4229                conductor
4230                    .maybe_run(
4231                        &cfg,
4232                        &opts.repo,
4233                        &queue,
4234                        &questions,
4235                        home,
4236                        &queued,
4237                        &stalled,
4238                        &finished,
4239                        opts.max_attempts,
4240                    )
4241                    .await;
4242                let temporary = path.with_extension("json.tmp");
4243                std::fs::write(&temporary, serde_json::to_vec(&conductor)?)?;
4244                std::fs::rename(temporary, path)?;
4245            }
4246        }
4247        "fetch" => {
4248            let cfg = prepare(&opts.repo, opts)?;
4249            if cfg.repos.fetch_interval > 0 && !cfg.repos.roots.is_empty() {
4250                let outcome = clean::fetch_origins(&cfg.repos.roots, FETCH_TIMEOUT, || false).await;
4251                tracing::debug!("fetch origins: {outcome:?}");
4252            }
4253        }
4254        "cache" => {
4255            if task_jobs(home)?.is_empty() {
4256                let mut checked = None;
4257                maybe_prune_cache_between_runs(
4258                    &opts.repo,
4259                    opts,
4260                    home,
4261                    &Stop::new(),
4262                    &mut checked,
4263                    Timestamp::now(),
4264                )
4265                .await;
4266            }
4267        }
4268        "disk-pressure" => {
4269            if let Ok(cfg) = prepare(&opts.repo, opts) {
4270                retention_service_receipt(
4271                    home,
4272                    "disk-pressure",
4273                    "worker",
4274                    "running",
4275                    "retention sweep",
4276                    Some(&cfg),
4277                );
4278                crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4279                if let Err(e) = clean::prune_cache_if_over_limit(&cfg, home) {
4280                    tracing::warn!("disk pressure cache cleanup failed: {e:#}");
4281                }
4282                if let Err(e) = crate::build_target::prune_registered(home, &cfg.disk) {
4283                    tracing::warn!("disk pressure isolated build cleanup failed: {e:#}");
4284                }
4285                for current in current_work(home, Timestamp::now()) {
4286                    if let Ok(state) = RunState::load_under(&current.run, home)
4287                        && let Some(reason) = disk_gate(&state.repo, &state.config)
4288                    {
4289                        for job in owned_task_jobs(home)?.into_iter().filter(|job| {
4290                            job.key.strip_prefix("task:") == Some(current.task.as_str())
4291                        }) {
4292                            request_task_park(
4293                                home,
4294                                &job,
4295                                crate::run::ParkCause::Interrupt {
4296                                    reason: reason.clone(),
4297                                },
4298                            )?;
4299                        }
4300                        notices::raise_in(
4301                            home,
4302                            Notice::warn(
4303                                "disk:pressure",
4304                                "Disk pressure persists after cleanup; active workers were asked to checkpoint and park. New starts and resumes wait for free space.",
4305                            ),
4306                        );
4307                    }
4308                }
4309            } else {
4310                retention_service_receipt(
4311                    home,
4312                    "disk-pressure",
4313                    "worker",
4314                    "error",
4315                    "configuration could not be loaded",
4316                    None,
4317                );
4318            }
4319        }
4320        "housekeeping" => {
4321            if task_jobs(home)?.is_empty() {
4322                match prepare(&opts.repo, opts) {
4323                    Ok(cfg) => {
4324                        retention_service_receipt(
4325                            home,
4326                            "housekeeping",
4327                            "worker",
4328                            "running",
4329                            "retention sweep",
4330                            Some(&cfg),
4331                        );
4332                        crate::retention::sweep(home, &cfg.disk, Timestamp::now()).await;
4333                    }
4334                    Err(error) => retention_service_receipt(
4335                        home,
4336                        "housekeeping",
4337                        "worker",
4338                        "error",
4339                        &format!("configuration: {error:#}"),
4340                        None,
4341                    ),
4342                }
4343                janitor(&opts.repo, opts, home, &request.worktrees_root).await;
4344                resweep_superseded_attempts(&queue, home);
4345                triage_held(&queue, home, opts).await;
4346            } else {
4347                retention_service_receipt(
4348                    home,
4349                    "housekeeping",
4350                    "worker",
4351                    "skipped",
4352                    "task worker became active",
4353                    None,
4354                );
4355            }
4356        }
4357        operation => bail!("unknown daemon service {operation}"),
4358    }
4359    Ok(())
4360}
4361
4362/// Only a different request under the same key is a dispatch handoff race.
4363/// Our own unacknowledged reservation is a startup failure, not competing work:
4364/// stop dispatch without fencing it, so an already detached child may still run.
4365fn task_worker_spawn_error(home: &Path, request: &TaskWorker, error: anyhow::Error) -> Result<()> {
4366    let key = format!("task:{}", request.task);
4367    let payload = serde_json::to_value(request)?;
4368    if crate::worker::active(home)?
4369        .iter()
4370        .any(|job| job.key == key && job.kind == "task" && job.payload != payload)
4371    {
4372        tracing::warn!(
4373            "task {} acquired a competing worker reservation: {error:#}",
4374            crate::run::short_of(&request.task)
4375        );
4376        return Ok(());
4377    }
4378    tracing::error!("task worker startup stopped dispatch: {error:#}");
4379    notices::raise_in(
4380        home,
4381        Notice::error(
4382            "loop:worker-startup",
4383            // Startup diagnostics may contain private child-process details;
4384            // keep them in the local error/log rather than the chat or notifier.
4385            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),
4386        ).link(Link::Task { id: request.task.clone() }),
4387    );
4388    Err(error).with_context(|| {
4389        format!(
4390            "cannot start task {} worker; dispatcher stopped; any unacknowledged reservation remains occupied",
4391            crate::run::short_of(&request.task)
4392        )
4393    })
4394}
4395
4396async fn poll(
4397    opts: &Opts,
4398    queue: &Queue,
4399    status: &Arc<Mutex<Status>>,
4400    home: &Path,
4401    worktrees_root: &Path,
4402    stop: &Stop,
4403    limits: DispatchLimits,
4404) -> Result<()> {
4405    let mut attempted = Vec::new();
4406    let mut settling_once_services = false;
4407    let interrupt_path = home.join("scheduler-interrupt.json");
4408    let mut interrupt = match std::fs::read(&interrupt_path) {
4409        Ok(body) => serde_json::from_slice(&body).context("read scheduler interrupt state")?,
4410        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Interrupt::Idle,
4411        Err(error) => return Err(error.into()),
4412    };
4413    let mut previous = std::collections::BTreeSet::<String>::new();
4414    let mut previous_skips = DispatchSkips::new();
4415    while !stop.stopped() {
4416        let jobs: Vec<_> = crate::worker::active(home)?
4417            .into_iter()
4418            .filter(|job| job.kind == "task")
4419            .collect();
4420        let requests: Vec<_> = jobs
4421            .iter()
4422            .map(|job| {
4423                serde_json::from_value::<TaskWorker>(job.payload.clone())
4424                    .with_context(|| format!("read live task worker {}", job.id))
4425            })
4426            .collect::<Result<_>>()?;
4427        let live: std::collections::BTreeSet<_> = requests.iter().map(|r| r.task.clone()).collect();
4428        let owned: std::collections::BTreeSet<_> = requests
4429            .iter()
4430            .filter(|r| !r.standalone)
4431            .map(|r| r.task.clone())
4432            .collect();
4433        let current: Vec<_> = requests
4434            .iter()
4435            .zip(&jobs)
4436            .filter(|(request, _)| !request.standalone)
4437            .map(|(request, job)| Current {
4438                worker: Some(job.id.clone()),
4439                task: request.task.clone(),
4440                run: queue
4441                    .get(&request.task)
4442                    .ok()
4443                    .and_then(|task| task.execution_runs().last().cloned())
4444                    .unwrap_or_default(),
4445            })
4446            .collect();
4447        {
4448            let mut snapshot = lock(status);
4449            snapshot.polls += 1;
4450            snapshot.completed += previous.difference(&owned).count();
4451            snapshot.current = current;
4452            snapshot.idle = owned.is_empty();
4453            snapshot.dispatch_wait = None;
4454        }
4455        previous = owned.clone();
4456        stop.busy.store(owned.len(), Ordering::SeqCst);
4457
4458        // Slots are reconstructed from durable reservations and OS-held worker
4459        // leases, not this scheduler's lifetime or mutable task urgency.
4460        let (ordinary, urgent) = available_slots(&requests, limits.max_concurrent);
4461        let sem = Arc::new(tokio::sync::Semaphore::new(ordinary));
4462        let urgent_sem = Arc::new(tokio::sync::Semaphore::new(urgent));
4463        let mut permits = Vec::new();
4464        sweep_stale_claims(queue, STALE_CLAIM);
4465        reclaim_orphaned_running(queue, opts.max_attempts, &live);
4466        reclaim_abandoned_runs(home, Timestamp::now());
4467        let questions = Questions::at(home.join("questions"));
4468
4469        // Deterministic: no model, run before the conductor sees anything so
4470        // its input reflects the queue's current, already-resolved state.
4471        crate::task_chat::sweep(
4472            queue,
4473            &crate::talk::Talks::at(home.join("talks")),
4474            &questions,
4475            home,
4476        );
4477        if let Err(error) = crate::task_inquiry::Outbox::at(home)
4478            .sweep(queue, &crate::talk::Talks::at(home.join("talks")))
4479        {
4480            tracing::warn!("task inquiry delivery remains pending: {error:#}");
4481        }
4482        repair_choice_offers(&questions);
4483        resolve_blockers(queue, &questions);
4484        apply_task_choice_actions(queue, &questions, home);
4485        triage::apply_answers(queue, &questions);
4486        reconcile_task_questions(queue, &questions);
4487        let talks = crate::talk::Talks::at(home.join("talks"));
4488        crate::chat_notify::sweep(queue, &talks, home);
4489        crate::notice_delivery::sweep(queue, &talks, home, &opts.repo);
4490        crate::chat_watch::sweep(home, &talks);
4491        if let Err(error) = crate::chat_control::reconcile_decisions(queue, home) {
4492            tracing::warn!("decision receipt reconciliation remains pending: {error:#}");
4493        }
4494        let mut turns = tokio::task::JoinSet::new();
4495        crate::chat_notify::start_turns(&talks, stop.parking(), &mut turns);
4496        // start_turns dispatches detached turns; no paid work lives in this set.
4497        while turns.join_next().await.is_some() {}
4498
4499        crate::consult::start_services(
4500            home,
4501            &opts.repo,
4502            limits.recovery_cfg.as_ref(),
4503            opts.config.as_deref(),
4504        )
4505        .await?;
4506        for operation in [
4507            "conductor",
4508            "maintenance",
4509            "housekeeping",
4510            "disk-pressure",
4511            "cache",
4512            "fetch",
4513            "chat-goals",
4514        ] {
4515            // Once an idle --once drain starts settling services, subsequent
4516            // scans only consume their effects. An expired cadence receipt
4517            // must not start another service and keep the drain alive.
4518            if settling_once_services {
4519                break;
4520            }
4521            if operation == "chat-goals" && stop.parking() {
4522                continue;
4523            }
4524            start_service(
4525                home,
4526                opts,
4527                queue,
4528                worktrees_root,
4529                operation,
4530                limits.recovery_cfg.as_ref(),
4531                !live.is_empty(),
4532            )
4533            .await?;
4534        }
4535        let latest = crate::worker::active(home)?;
4536        if latest.iter().any(|job| job.key == "service:daemon-cache")
4537            || latest
4538                .iter()
4539                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4540        {
4541            stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4542            continue;
4543        }
4544        let candidates: Vec<Task> = runnable(queue)
4545            .into_iter()
4546            .filter(|task| !live.contains(&task.id))
4547            .filter(|task| !opts.once || !attempted.contains(&task.id))
4548            .collect();
4549        let in_flight: Vec<_> = owned.iter().cloned().collect();
4550        let prior_interrupt = std::mem::discriminant(&interrupt);
4551        interrupt = advance_interrupt_tick(
4552            limits.pause_for_interrupts,
4553            interrupt,
4554            &in_flight,
4555            &candidates,
4556        );
4557        // Same-variant transitions preserve their identities. Only an actual
4558        // transition needs a durable write, atomically before sending controls.
4559        if prior_interrupt != std::mem::discriminant(&interrupt) {
4560            let temporary = interrupt_path.with_extension("json.tmp");
4561            std::fs::write(&temporary, serde_json::to_vec(&interrupt)?)?;
4562            std::fs::rename(temporary, &interrupt_path)?;
4563        }
4564        if let Interrupt::Parking {
4565            parked,
4566            interrupt_task,
4567        } = &interrupt
4568        {
4569            for job in jobs.iter().filter(|job| {
4570                parked
4571                    .iter()
4572                    .any(|id| job.key.strip_prefix("task:") == Some(id.as_str()))
4573            }) {
4574                if crate::worker::control(home, &job.key)?.is_none() {
4575                    request_task_park(
4576                        home,
4577                        job,
4578                        crate::run::ParkCause::Interrupt {
4579                            reason: format!(
4580                                "task {} asked to run first",
4581                                crate::run::short_of(interrupt_task)
4582                            ),
4583                        },
4584                    )?;
4585                }
4586            }
4587        }
4588        let candidate_ids: Vec<_> = candidates.iter().map(|task| task.id.clone()).collect();
4589        let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
4590        let mut skips = interrupt_skips(&candidate_ids, &candidates);
4591        let cooling = read_cooldown(home)?.is_some_and(|until| Timestamp::now() < until);
4592        let mut started = false;
4593        let mut resync = false;
4594        for candidate in candidates {
4595            if stop.stopped() {
4596                break;
4597            }
4598            let DispatchClaim {
4599                task,
4600                claim,
4601                permit,
4602            } = match claim_dispatch(queue, &candidate, cooling, &sem, &urgent_sem) {
4603                Ok(claim) => claim,
4604                Err(reason) => {
4605                    skips.insert((candidate.id, reason));
4606                    continue;
4607                }
4608            };
4609            if crate::worker::active(home)?
4610                .iter()
4611                .any(|job| job.kind == "task" && !jobs.iter().any(|known| known.id == job.id))
4612            {
4613                drop(claim);
4614                resync = true;
4615                break;
4616            }
4617            let lane = permit_kind(land_resume_state(&task) == LandResume::Ready, task.urgent);
4618            let request = TaskWorker {
4619                opts: opts.absolute()?,
4620                queue: std::path::absolute(queue.root())?,
4621                task: task.id.clone(),
4622                lane,
4623                standalone: false,
4624            };
4625            // Keep the claim until spawn acknowledges the worker's durable
4626            // reservation. The worker then claims and re-reads before attempt.
4627            if let Err(error) = crate::worker::spawn(
4628                home,
4629                "task",
4630                &format!("task:{}", task.id),
4631                serde_json::to_value(&request)?,
4632            )
4633            .await
4634            {
4635                task_worker_spawn_error(home, &request, error)?;
4636                drop(claim);
4637                resync = true;
4638                break;
4639            }
4640            drop(claim);
4641            permits.extend(permit);
4642            attempted.push(task.id);
4643            started = true;
4644        }
4645        if !resync && !stop.stopped() {
4646            if !started {
4647                lock(status).dispatch_wait = aggregate_dispatch_wait(candidate_ids.len(), &skips);
4648            }
4649            if changed_dispatch_skips(&mut previous_skips, skips) {
4650                if previous_skips.is_empty() {
4651                    tracing::info!("dispatch skips cleared");
4652                }
4653                for (task, reason) in &previous_skips {
4654                    tracing::info!(
4655                        task,
4656                        reason = reason.key(),
4657                        "task {} skipped: {}",
4658                        crate::run::short_of(task),
4659                        reason.describe()
4660                    );
4661                }
4662            }
4663        }
4664        if started || resync {
4665            continue;
4666        }
4667        if owned.is_empty() && opts.once {
4668            settling_once_services = true;
4669            // These finite services can own queue claims or publish answers.
4670            // A skipped claim is not an idle queue until they have finished;
4671            // scan again afterwards so their changes are actually scheduled.
4672            if crate::worker::active(home)?.iter().any(|job| {
4673                job.kind == "daemon-service"
4674                    && matches!(
4675                        job.key.as_str(),
4676                        "service:daemon-housekeeping"
4677                            | "service:daemon-conductor"
4678                            | "service:daemon-maintenance"
4679                    )
4680            }) {
4681                stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
4682                continue;
4683            }
4684            break;
4685        }
4686        stop.idle(if live.is_empty() {
4687            opts.poll
4688        } else {
4689            RECHECK_WHILE_BUSY.min(opts.poll)
4690        })
4691        .await;
4692    }
4693    // Dropping a scheduler only drops dispatch bookkeeping. The workers own
4694    // every queue claim and Runner driver lease through outcome settlement.
4695    stop.busy.store(0, Ordering::SeqCst);
4696    lock(status).dispatch_wait = None;
4697    Ok(())
4698}
4699
4700/// A maintenance pass may briefly own the same record while a worker starts.
4701/// Wait without blocking the executor or charging an agent attempt, then read
4702/// ownership again under the acquired lock. Other I/O failures still fail closed.
4703async fn resume_owner_lock(home: &Path, id: &str) -> Result<crate::pr_head::OwnerLock> {
4704    let busy = |error: &anyhow::Error| {
4705        error.downcast_ref::<std::io::Error>().is_some_and(|error| {
4706            error.kind() == std::io::ErrorKind::WouldBlock
4707                || cfg!(windows) && error.raw_os_error() == Some(33)
4708        })
4709    };
4710    match crate::pr_head::owner_lock(home, id) {
4711        Ok(lock) => return Ok(lock),
4712        Err(error) if busy(&error) => {}
4713        Err(error) => return Err(error),
4714    }
4715    let wait = RunState::load_under(id, home)?
4716        .config
4717        .graph
4718        .timeout_resource_wait;
4719    crate::pr_head::owner_lock_wait(home, id, Duration::from_secs(wait)).await
4720}
4721
4722/// Historical successors do not revoke a still-resumable public owner. Scan
4723/// under the same lock as publication/driver claims, and fail closed on unknown
4724/// history before spending another attempt.
4725async fn public_resume_owner(
4726    home: &Path,
4727    runs: &[String],
4728    repo: &Path,
4729) -> Result<Option<RunState>> {
4730    let mut owner = None;
4731    for id in runs.iter().collect::<std::collections::BTreeSet<_>>() {
4732        let _lock = resume_owner_lock(home, id).await?;
4733        let state = RunState::load_under(id, home)?;
4734        if state.released()
4735            || state.retired_to.is_some()
4736            || state.pr_taken_over_by.is_some()
4737            || !crate::handover::landing_checkpoint(&state)
4738        {
4739            continue;
4740        }
4741        anyhow::ensure!(
4742            crate::git::toplevel(&state.repo).await?.canonicalize()?
4743                == crate::git::toplevel(repo).await?.canonicalize()?,
4744            "public owner repository differs; inspect run lineage"
4745        );
4746        anyhow::ensure!(
4747            owner.is_none(),
4748            "multiple retained public owners; inspect run lineage"
4749        );
4750        if let Some(reason) = crate::handover::resume_refusal_under(&state, Some(home)) {
4751            anyhow::bail!(reason.diagnostic(&state));
4752        }
4753        let claimed = is_working_on_other(home, id, Timestamp::now())?;
4754        anyhow::ensure!(
4755            state.liveness_under(home, claimed) == crate::run::Liveness::Dead,
4756            "public owner's driver is live or unknown; wait before retrying"
4757        );
4758        owner = Some(state);
4759    }
4760    Ok(owner)
4761}
4762
4763/// Run one claimed task to a terminal status and record the outcome.
4764///
4765/// Every transition is flushed to the queue as it happens, so the state on disk
4766/// is what actually occurred rather than what this process still intends to
4767/// write.
4768async fn attempt(
4769    opts: &Opts,
4770    queue: &Queue,
4771    status: &Arc<Mutex<Status>>,
4772    stop: &Stop,
4773    interrupt_pause: crate::graph::Pause,
4774    task: &mut Task,
4775) -> Vec<QuotaLoss> {
4776    if let Some(request) = task.sync_only.clone() {
4777        Box::pin(attempt_sync_only(
4778            queue,
4779            status,
4780            stop,
4781            interrupt_pause,
4782            task,
4783            request,
4784        ))
4785        .await;
4786        return Vec::new();
4787    }
4788    let repo = repo_for(task, &opts.repo);
4789    tracing::info!(
4790        "task {} — {} (repo {})",
4791        task.short(),
4792        task.title,
4793        repo.display()
4794    );
4795
4796    let public_owner = match public_resume_owner(&crate::run::home(), &task.runs, &repo).await {
4797        Ok(owner) => owner,
4798        Err(e) => {
4799            task.hold_machine(Some(format!(
4800                "Cannot verify existing public owner: {e:#}; no attempt started."
4801            )));
4802            record(queue, task);
4803            return Vec::new();
4804        }
4805    };
4806    let resume_runs = public_owner
4807        .as_ref()
4808        .map(|s| vec![s.id.clone()])
4809        .unwrap_or_else(|| task.execution_runs().to_vec());
4810
4811    // A stop spends no agent resources and uses the saved landing owner.
4812    // Current roster edits, missing attachments or a failed config fetch must
4813    // never turn it into a new implementation, or prevent a PR from closing.
4814    if let Some(previous) = resume_runs.last().and_then(|id| RunState::load(id).ok())
4815        && previous
4816            .merge_decision
4817            .as_ref()
4818            .is_some_and(|decision| !decision.closed)
4819        && previous.status != RunStatus::Landing
4820        && !crate::merge_decision::resumable_hold(&previous)
4821    {
4822        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)));
4823        record(queue, task);
4824        return Vec::new();
4825    }
4826    let stop_owner = resume_runs
4827        .last()
4828        .and_then(|id| RunState::load(id).ok())
4829        .filter(|state| {
4830            crate::merge_decision::resumable_hold(state)
4831                || state.status == RunStatus::Landing
4832                    && state.land_approval.as_ref().is_some_and(|binding| {
4833                        Questions::open()
4834                            .get_for_effects(&binding.question)
4835                            .is_ok_and(|q| {
4836                                q.run == state.id
4837                                    && q.resolution()
4838                                        .as_deref()
4839                                        .is_some_and(crate::merge_decision::stops)
4840                            })
4841                    })
4842        });
4843    if let Some(owner) = stop_owner {
4844        let mut runner = match Runner::resume(&owner.id) {
4845            Ok(runner) => runner,
4846            Err(e) => {
4847                task.hold_manual(Some(format!("Cannot stop the existing landing owner: {e:#}. No replacement or merge was started.")));
4848                record(queue, task);
4849                return Vec::new();
4850            }
4851        };
4852        runner.on_pause(stop.pause());
4853        runner.watch_interrupt(interrupt_pause);
4854        let quota_before = runner.state.quota.clone();
4855        let before_start = task.clone();
4856        task.start(owner.id.clone());
4857        if let Err(error) = queue.put(task) {
4858            *task = before_start;
4859            let error = runner.fail_startup("task-start", error);
4860            if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
4861                task.record_startup_failure(failure.clone());
4862            }
4863            task.hold_manual(Some(format!(
4864                "Could not persist task start; no agents dispatched: {error:#}"
4865            )));
4866            record(queue, task);
4867            return Vec::new();
4868        }
4869        lock(status).current.push(Current {
4870            worker: None,
4871            task: task.id.clone(),
4872            run: owner.id,
4873        });
4874        runner.state.carry_dispatched_resumes(task);
4875        runner.state.next_pass_task_entry = true;
4876        let result = runner.execute().await;
4877        return finish_attempt(
4878            opts.max_attempts,
4879            queue,
4880            task,
4881            &runner.state,
4882            &quota_before,
4883            result,
4884        );
4885    }
4886
4887    if let Some(owner) = &public_owner
4888        && (task.fresh_start || !may_resume_run(owner, task))
4889    {
4890        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)));
4891        record(queue, task);
4892        return Vec::new();
4893    }
4894
4895    if let Some(state) = task
4896        .execution_runs()
4897        .last()
4898        .and_then(|id| RunState::load(id).ok())
4899        && let Some(reason) = crate::repair_budget::conflict_failure(task, &state)
4900    {
4901        task.hold_machine(Some(reason));
4902        record(queue, task);
4903        return Vec::new();
4904    }
4905
4906    if let Some(held) = crate::base_sync_recovery::held_run(queue, task)
4907        && !task.fresh_start
4908        && task.pr_recovery.is_none()
4909    {
4910        // A pinned infrastructure resume continues the saved reservation;
4911        // it does not authorize another base-sync interval.
4912        let sequencer_resume = crate::repair_budget::legacy::resumable_sequencer_stop(&held)
4913            && task.review_branch.is_none()
4914            && task.assignment_accepts(&held)
4915            && compatible_run_instruction(&held, task)
4916            && task
4917                .resume_override
4918                .as_ref()
4919                .is_some_and(|pin| pin.pinned_run.as_ref() == Some(&held.id));
4920        // Exhaustion authorization still takes the owner lock and execution
4921        // lease and rechecks liveness, retained HEAD and ownership.
4922        let authorized = if sequencer_resume || crate::repair_budget::conflict_pending(task, &held)
4923        {
4924            true
4925        } else if task.resumption.is_some() && compatible_run_instruction(&held, task) {
4926            let home = queue.root().parent().expect("queue has a home");
4927            match Runner::authorize_base_recovery_from_resumption(home, &held.id, &task.id).await {
4928                Ok(()) => true,
4929                Err(error) => {
4930                    tracing::debug!(run = %held.id, %error, "base recovery resumption refused");
4931                    false
4932                }
4933            }
4934        } else {
4935            false
4936        };
4937        if !authorized {
4938            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())));
4939            // Retain the existing stop identity when an old release reached the queue.
4940            task.base_sync_notice(&held);
4941            task.resume_override = None;
4942            record(queue, task);
4943            return Vec::new();
4944        }
4945    }
4946    if !task.fresh_start && task.pr_recovery.is_none() {
4947        let home = queue.root().parent().expect("queue has a home");
4948        if let crate::land_sync_recovery::DispatchDecision::Hold { reason, state } =
4949            crate::land_sync_recovery::dispatch_check(queue, home, task).await
4950        {
4951            task.hold_machine(Some(reason));
4952            task.land_sync_notice(state.as_ref());
4953            task.resume_override = None;
4954            record(queue, task);
4955            return Vec::new();
4956        }
4957    }
4958    let head_e2e_approval = match crate::head_e2e_stop::check_attempt(queue, task) {
4959        Some(crate::head_e2e_stop::AttemptGate::Hold(hold)) => {
4960            hold.apply(task);
4961            record(queue, task);
4962            return Vec::new();
4963        }
4964        Some(crate::head_e2e_stop::AttemptGate::ConsumeOwnerApproval {
4965            run,
4966            stop_id,
4967            generation,
4968            approval_at,
4969        }) => Some((run, stop_id, generation, approval_at)),
4970        None => None,
4971    };
4972    let unfinished = (!task.fresh_start)
4973        .then(|| unfinished_run(&resume_runs, task.short()))
4974        .flatten()
4975        .filter(|id| RunState::load(id).is_ok_and(|run| may_resume_run(&run, task)));
4976    let previous = resume_runs.last().and_then(|id| RunState::load(id).ok());
4977    if task.repair_grants.last().is_some_and(|receipt| {
4978        task.execution_runs().last() == Some(&receipt.request.run)
4979            && task.operator_decided_at == receipt.decision
4980            && previous
4981                .as_ref()
4982                .is_none_or(|run| run.id != receipt.request.run)
4983    }) {
4984        task.hold_unrequested_retry(Some(
4985            "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(),
4986        ));
4987        record(queue, task);
4988        return Vec::new();
4989    }
4990    if let Some(id) = &task.disk_resume_run
4991        && unfinished.as_ref() != Some(id)
4992    {
4993        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()));
4994        record(queue, task);
4995        return Vec::new();
4996    }
4997
4998    if !task.fresh_start
4999        && task.pr_recovery.is_none()
5000        && task.review_branch.is_none()
5001        && task.resume_override.is_none()
5002        && previous
5003            .as_ref()
5004            .is_some_and(|run| run.retired_to.is_some())
5005        && unfinished.is_none()
5006    {
5007        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()));
5008        record(queue, task);
5009        return Vec::new();
5010    }
5011
5012    let saved_recovery = previous.as_ref().filter(|run| {
5013        task.replacement.is_none()
5014            && task.pr_recovery.as_ref().is_some_and(|selected| {
5015                selected
5016                    .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5017                    .is_ok()
5018                    && selected_starter(selected, Some(run), unfinished.as_deref())
5019                        == Starter::Resume(run.id.clone())
5020            })
5021    });
5022
5023    // The repository's magi.toml comes from `<remote>/<base>`, fetched now. A
5024    // failure here is the network's or the operator's, not the task's: hold
5025    // without spending an attempt, never fall back to a possibly stale copy.
5026    let explicit = match &task.overrides {
5027        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
5028        Some(_) => opts.config.as_deref(),
5029        None => opts.config.as_deref(),
5030    };
5031    let (mut config, layers) = if let Some(run) = saved_recovery {
5032        // A matching resume owns its resolved configuration and evidence;
5033        // current layers and inherited overrides only configure new work.
5034        let mut saved = run.clone();
5035        if let Err(e) = saved.configure_recovery_resume() {
5036            task.hold_manual(Some(format!("[recovery] saved run {} cannot resume: {e:#}. Inspect its saved configuration and evidence before requesting a new selection.", run.id)));
5037            record(queue, task);
5038            return Vec::new();
5039        }
5040        (saved.config, Vec::new())
5041    } else {
5042        let (mut config, layers) = match Config::discover_fetched(&repo, explicit).await {
5043            Ok(loaded) => loaded,
5044            Err(e) => {
5045                let reason = format!("[config] {e:#}");
5046                record_config_failure(task, &e);
5047                task.last_error = Some(reason.clone());
5048                task.hold_machine(Some(reason));
5049                record(queue, task);
5050                return Vec::new();
5051            }
5052        };
5053        if let Err(e) = apply_options(&mut config, opts, task) {
5054            task.hold_manual(Some(format!(
5055                "[config] {e:#}; correct the merge override before releasing the task"
5056            )));
5057            record(queue, task);
5058            return Vec::new();
5059        }
5060        if let Some(selected) = &task.pr_recovery
5061            && let Err(e) = selected.configure(&mut config)
5062        {
5063            task.hold_manual(Some(format!("[recovery] {e:#}. No run started; select the PR again with an explicit disposition and corrected configuration.")));
5064            record(queue, task);
5065            return Vec::new();
5066        }
5067        (config, layers)
5068    };
5069    let config_evidence = crate::pr_recovery::ConfigEvidence {
5070        layers,
5071        overrides: task.overrides.clone(),
5072        daemon_merge: task
5073            .overrides
5074            .as_ref()
5075            .is_none_or(|o| o.inherit_daemon_options)
5076            .then(|| opts.merge.clone())
5077            .flatten(),
5078    };
5079    apply_task_implementers(&mut config, task);
5080    if let Some(replacement) = &task.replacement {
5081        let safe = RunState::load(&replacement.run).is_ok_and(|old| {
5082            old.liveness(false) == Liveness::Dead
5083                && old.merge_decision.as_ref().is_some_and(|d| {
5084                    d.closed
5085                        && d.question == replacement.question
5086                        && d.replacement_run.as_ref().is_none_or(|run| {
5087                            task.execution_runs().last() == Some(run)
5088                                && RunState::load(run).is_ok_and(|current| {
5089                                    current.replaces.as_ref().is_some_and(|pin| {
5090                                        pin.question == replacement.question
5091                                            && pin.agent == replacement.agent
5092                                    })
5093                                })
5094                        })
5095                })
5096        });
5097        if !safe {
5098            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()));
5099            record(queue, task);
5100            return Vec::new();
5101        }
5102        match config.agent(&replacement.agent) {
5103            Ok(agent) if crate::agent::installed(agent) => {}
5104            _ => {
5105                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)));
5106                record(queue, task);
5107                return Vec::new();
5108            }
5109        }
5110        config.graph.implementers = 1;
5111        config.graph.land_approval = true;
5112        config.merge.mode = MergeMode::Pr;
5113        config.graph.selected_implementer = Some(replacement.agent.clone());
5114    }
5115    let p = phrases(&config.graph.language);
5116    let start_failed = p.could_not_start;
5117    // Resolve once for both admission and settlement. The inputs are the
5118    // task's explicit sources (never prose), plus an explicit review source's
5119    // current head; review-only runs may rebase later, and neither fact can
5120    // refund a failed automatic generation.
5121    if let Ok(base) =
5122        crate::git::merge_base_branch(&repo, &config.merge.remote, config.merge.base.as_deref())
5123            .await
5124        && let Ok(head) =
5125            crate::git::rev_parse(&repo, &format!("{}/{}", config.merge.remote, base)).await
5126    {
5127        let mut inputs = crate::queue::recovery_inputs(&task.sources);
5128        if let Some(branch) = task.review_of.as_ref().or(task.review_branch.as_ref()) {
5129            let source = crate::git::rev_parse(&repo, branch)
5130                .await
5131                .unwrap_or_default();
5132            inputs.push_str(&format!(";review:{branch}:{source}"));
5133        }
5134        if let Some(reason) = task
5135            .recovery_exhausted(
5136                &head,
5137                &inputs,
5138                task.attempt_limit
5139                    .map_or(opts.max_attempts, std::num::NonZeroUsize::get),
5140            )
5141            .filter(|_| {
5142                !task.repair_grants.last().is_some_and(|receipt| {
5143                    RunState::load(&receipt.request.run)
5144                        .is_ok_and(|run| crate::repair_budget::pending(task, &run))
5145                })
5146            })
5147        {
5148            task.hold_recovery_budget(
5149                reason,
5150                crate::queue::RecoveryAdmission { base: head, inputs },
5151            );
5152            record(queue, task);
5153            return Vec::new();
5154        }
5155        task.recovery_admission = Some(crate::queue::RecoveryAdmission { base: head, inputs });
5156    }
5157
5158    // A resumable run of this task is carried on, never re-competed. The
5159    // candidates are built and paid for, and a fresh competition races a
5160    // second implementation against them.
5161    //
5162    // Two runs paid for that lesson. Run 01c2 was blocked and the loop
5163    // started 3cbf on the same task a moment later, duplicating two and a
5164    // half hours of agent work. Then b25f stalled on a judge that timed out
5165    // and one that answered with no JSON - `quota: 0`, so nothing the machine
5166    // was to blame for - and 4043 started **one second** later, buying three
5167    // fresh implementations to reach the same panel. `RunStatus::resumable`
5168    // rather than `!done()` is what catches the second case: a stall is
5169    // terminal, and its cheap recovery re-asks only the absent seats.
5170    //
5171    // A load failure is warned about rather than silently read as "not
5172    // resumable": the alternative is exactly what let a schema mismatch on
5173    // run `eba2` fall through to a full re-competition with nobody told why.
5174    // `crate::conduct` is what actually offers a better answer than
5175    // `Runner::start` here (see `Recovery::Review`), once this task's next
5176    // failure shows it up as `held`/`failed` with the run state unreadable.
5177    // Keep a retained review selection intact until disk admission succeeds.
5178    let consume_review = !previous
5179        .as_ref()
5180        .is_some_and(|state| crate::repair_budget::pending(task, state));
5181    let review_branch = consume_review
5182        .then(|| review_branch_for(task, previous.as_ref()))
5183        .flatten();
5184    let branch_exists = match review_branch {
5185        Some(branch) => crate::git::branch_exists(&repo, branch)
5186            .await
5187            .unwrap_or(false),
5188        None => false,
5189    };
5190    // An explicit `magi review <branch>` is reviewed whatever happens to the
5191    // branch unless an explicit implementer change requires fresh work. An
5192    // unfinished run of the same task still wins, so a retry resumes.
5193    let proposed = review_retry_starter(
5194        task,
5195        previous.as_ref(),
5196        review_branch,
5197        branch_exists,
5198        unfinished.as_deref(),
5199    );
5200    let retry_selected = task.replacement.is_some()
5201        && task.resumption.is_some()
5202        && !task.fresh_start
5203        && previous.as_ref().is_some_and(|run| {
5204            run.replaces.is_some()
5205                && ((run.status == RunStatus::Failed && run.viable().is_empty())
5206                    || (run.status == RunStatus::Blocked && run.tally.is_none()))
5207        });
5208    let stop_pin = task
5209        .resume_override
5210        .as_ref()
5211        .filter(|pin| {
5212            Questions::open()
5213                .get_for_effects(&pin.question_id)
5214                .is_ok_and(|q| {
5215                    q.node == land::APPROVAL_NODE
5216                        && q.resolution()
5217                            .as_deref()
5218                            .is_some_and(crate::merge_decision::stops)
5219                })
5220        })
5221        .and_then(|pin| pin.pinned_run.clone());
5222    let granted_run = task.repair_grants.last().and_then(|receipt| {
5223        let state = RunState::load(&receipt.request.run).ok()?;
5224        crate::repair_budget::pending(task, &state).then(|| receipt.request.run.clone())
5225    });
5226    let starter = if let Some(run) = granted_run {
5227        Starter::Resume(run)
5228    } else if let Some(owner) = &public_owner {
5229        Starter::Resume(owner.id.clone())
5230    } else if let Some(run) = stop_pin {
5231        // Stop actions resume their exact owner even after seat-count edits;
5232        // they must never fall through to implementation or a takeover.
5233        Starter::Resume(run)
5234    } else if retry_selected {
5235        Starter::Resume(previous.as_ref().unwrap().id.clone())
5236    } else if let Some(selected) = &task.pr_recovery {
5237        if selected
5238            .check_task_assignment(&task.id, &task.instruction, task.reassignments.len())
5239            .is_ok()
5240        {
5241            selected_starter(selected, previous.as_ref(), unfinished.as_deref())
5242        } else {
5243            Starter::Review(selected.branch.clone())
5244        }
5245    } else {
5246        starter_with_implementers(task, previous.as_ref(), proposed)
5247    };
5248    // A retained execution still writes to its saved output volume. A newer
5249    // repository policy only selects the volume for a fresh run.
5250    let disk_reason = match &starter {
5251        Starter::Resume(id) => previous.as_ref().filter(|run| &run.id == id).map_or_else(
5252            || {
5253                RunState::load(id)
5254                    .ok()
5255                    .and_then(|run| disk_gate(&run.repo, &run.config))
5256            },
5257            |run| disk_gate(&run.repo, &run.config),
5258        ),
5259        _ => disk_gate(&repo, &config),
5260    };
5261    if let Some(reason) = disk_reason {
5262        task.notice_cause("disk-space", None, None);
5263        task.last_error = Some(reason.clone());
5264        let disk_checked_at = task.disk_checked_at;
5265        task.hold_machine(Some(reason.clone()));
5266        if matches!(starter, Starter::Resume(_)) {
5267            task.mark_disk_capacity();
5268        } else {
5269            task.mark_startup_disk_capacity();
5270        }
5271        task.disk_checked_at = disk_checked_at;
5272        record(queue, task);
5273        tracing::warn!("holding {} for want of disk space: {reason}", task.short());
5274        notices::raise(
5275            Notice::warn(
5276                &format!("disk:{}", repo.display()),
5277                format!("Task {} is waiting for disk space. It will resume automatically when disk and output admission checks succeed.", task.id),
5278            )
5279            .link(Link::Task {
5280                id: task.id.clone(),
5281            }),
5282        );
5283        return Vec::new();
5284    }
5285    let review_branch = if consume_review {
5286        let valid = review_branch.is_some();
5287        task.review_instruction = None;
5288        task.review_branch.take().filter(|_| valid)
5289    } else {
5290        None
5291    };
5292    // An explicit resume pin must never degrade into a new competition or
5293    // takeover, including when its run stops being eligible after the answer.
5294    if let Some(pin) = &task.resume_override
5295        && let Some(run) = &pin.pinned_run
5296        && starter != Starter::Resume(run.clone())
5297    {
5298        let run = run.clone();
5299        task.notice_cause("resume-owner", Some(&run), None);
5300        task.hold_machine(Some(format!(
5301            "pinned run cannot resume; inspect `magi show {run}` and restore the existing run before `magi task release {}`; no replacement task was started",
5302            task.id
5303        )));
5304        record(queue, task);
5305        return Vec::new();
5306    }
5307    // Automatic disk recovery resumes its retained run or stops: a changed
5308    // seat count or review branch must not turn it into a new competition.
5309    // No attempt is spent here.
5310    if let Some(run) = &task.disk_resume_run
5311        && starter != Starter::Resume(run.clone())
5312    {
5313        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()));
5314        record(queue, task);
5315        return Vec::new();
5316    }
5317    if task.replacement.is_some()
5318        && previous.as_ref().is_some_and(|run| run.replaces.is_some())
5319        && starter != Starter::Resume(previous.as_ref().unwrap().id.clone())
5320    {
5321        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()));
5322        record(queue, task);
5323        return Vec::new();
5324    }
5325    if let Some((ref run, ..)) = head_e2e_approval
5326        && starter != Starter::Resume(run.clone())
5327    {
5328        task.hold_machine(Some(format!(
5329            "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."
5330        )));
5331        record(queue, task);
5332        return Vec::new();
5333    }
5334    if let Some(reason) = retained_attempt_hold(
5335        task,
5336        &starter,
5337        config.disk.retained_attempt_limit,
5338        RunState::load,
5339    ) {
5340        // The review choice was consumed above. Preserve it across this hold
5341        // so a later release cannot silently become a fresh implementation.
5342        if let Starter::Review(branch) = &starter {
5343            task.review_branch = Some(branch.clone());
5344        }
5345        task.hold_unrequested_retry(Some(reason));
5346        record(queue, task);
5347        return Vec::new();
5348    }
5349    // Absolute paths of the files the task was filed with, re-read from the
5350    // task now so a file attached while it was held reaches a resumed run
5351    // too. A stored name whose file has gone is an error before any agent is
5352    // paid for, never a silent omission the implementer cannot notice.
5353    let attachments = match task_attachments(queue, task) {
5354        Ok(a) => a,
5355        Err(e) => {
5356            task.attempts += 1;
5357            task.fail_startup_target(
5358                "startup-attachments",
5359                e.name.clone(),
5360                format!("{start_failed}{e:#}"),
5361                opts.max_attempts,
5362            );
5363            record(queue, task);
5364            return Vec::new();
5365        }
5366    };
5367    let startup_pause = stop.pause();
5368    let startup_interrupt = interrupt_pause.clone();
5369    let wait = crate::repo_lock::WaitPolicy::new(
5370        Duration::from_secs(config.graph.timeout_resource_wait),
5371        move || startup_pause.parked() || startup_interrupt.parked(),
5372    );
5373    // Startup includes review takeover and recovery. Do not embed its large
5374    // future in both the wait scope and the surrounding attempt stack frame.
5375    let started = wait.scope(Box::pin(async { match &starter {
5376        Starter::Review(_) if task.pr_recovery.is_some() => {
5377            let selected = task.pr_recovery.clone().expect("selected recovery");
5378            match selected.check_task_assignment(&task.id, &task.instruction, task.reassignments.len()) {
5379                Ok(()) => Runner::recover_pr(&repo, &task.id, selected, config)
5380                    .await
5381                    .map(|mut r| {
5382                        r.state.attachments = attachments.clone();
5383                        r
5384                    }),
5385                Err(e) => Err(e),
5386            }
5387        }
5388        Starter::Review(branch) => {
5389            tracing::info!(
5390                "task {} reopens `{branch}` as a review-only pass",
5391                task.short()
5392            );
5393            // Every earlier attempt is superseded by the one being minted
5394            // now, so a branch one of them still holds may be taken over.
5395            let takeover = crate::handover::Takeover {
5396                earlier: task.earlier_attempts().to_vec(),
5397                home: crate::run::home(),
5398                choice: take_divergence_answer(branch, &config.merge.remote, task),
5399                task_instruction: Some(instruction_for(task)),
5400            };
5401            Runner::review_taking_over(
5402                &repo,
5403                branch,
5404                config,
5405                Some(takeover),
5406                crate::run::Origin::queue(&task.id),
5407            )
5408            .await
5409        }
5410        Starter::Resume(id) => {
5411            tracing::info!("resuming run {id} rather than competing again");
5412            Runner::resume(id).and_then(|mut r| {
5413                if retry_selected {
5414                    // The explicit queue release retries this same pinned
5415                    // implementation, preserving the attempt and worktrees.
5416                    for candidate in &mut r.state.candidates {
5417                        candidate.failed = None;
5418                        candidate.empty = false;
5419                        candidate.commits = 0;
5420                    }
5421                    r.state.status = RunStatus::Implementing;
5422                    r.state.event("implement", "owner released the held selected implementer; retrying the same attempt without fallback");
5423                }
5424                if r.state.prep_complete == Some(false) && r.state.candidates.is_empty() {
5425                    r.state.sources = task.sources.clone();
5426                }
5427                if r.state.prep_failure.is_some() {
5428                    let approval = task
5429                        .resumption
5430                        .as_ref()
5431                        .context("preparation retry requires an explicit task release")?;
5432                    r.retry_preparation(approval.at)?;
5433                }
5434                if let Some(instruction) =
5435                    prepare_instruction(&starter, Some(&r.state.instruction), task)
5436                {
5437                    r.state.instruction = instruction;
5438                }
5439                r.state.attachments = attachments.clone();
5440                if task.replacement.is_some() {
5441                    r.state.config.merge.mode = MergeMode::Pr;
5442                    r.state.config.graph.land_approval = true;
5443                }
5444                // Replacements publish a new PR and ask again. Selected PR
5445                // recoveries keep their saved disposition; ordinary runs can
5446                // retain the task's merge override.
5447                if task.replacement.is_none() && task.pr_recovery.is_none() && let Some(mode) = task
5448                    .overrides
5449                    .as_ref()
5450                    .and_then(|o| o.merge.as_deref())
5451                    .and_then(|m| merge_mode(m).ok())
5452                {
5453                    r.state.config.merge.mode = mode;
5454                }
5455                Ok(r)
5456            })
5457        }
5458        Starter::Start => {
5459            if let Some(branch) = &review_branch {
5460                tracing::warn!(
5461                    "conductor chose review for task {} but branch `{branch}` no longer \
5462                     exists; requeuing as a fresh competition instead",
5463                    task.short()
5464                );
5465            }
5466            let instruction = prepare_instruction(&starter, None, task)
5467                .unwrap_or_else(|| task.instruction.clone());
5468            Runner::start_naming(
5469                &repo,
5470                instruction,
5471                &task.title,
5472                config,
5473                crate::run::Origin::queue(&task.id),
5474            )
5475            .await
5476            .map(|mut r| {
5477                r.state.attachments = attachments.clone();
5478                r.state.sources = task.sources.clone();
5479                r
5480            })
5481        }
5482    }})).await;
5483    if let Err(error) = &started
5484        && let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>()
5485    {
5486        task.record_startup_failure(failure.clone());
5487    }
5488    let mut runner = match started {
5489        Ok(r) => r,
5490        Err(e) if e.is::<crate::repo_lock::ResourceBlocked>() => {
5491            let detail = format!("{e:#}");
5492            task.last_error = Some(detail.clone());
5493            if e.is::<crate::build_target::AdmissionDiskWait>()
5494                && let Starter::Review(branch) = &starter
5495                && review_branch.is_some()
5496            {
5497                task.review_branch = Some(branch.clone());
5498                task.review_instruction = Some(task.instruction.clone());
5499            }
5500            if stop.parking() || interrupt_pause.parked() {
5501                let attempts = task.attempts;
5502                task.park(e.to_string());
5503                // Startup has not spent an attempt to refund.
5504                task.attempts = attempts;
5505            } else if e.is::<crate::build_target::AdmissionDiskWait>() {
5506                let disk_checked_at = task.disk_checked_at;
5507                task.hold_machine(Some(detail));
5508                task.mark_startup_disk_capacity();
5509                task.disk_checked_at = disk_checked_at;
5510            } else {
5511                task.hold_machine(Some(format!("{}{e}", crate::cache::RESOURCE_HOLD)));
5512            }
5513            record(queue, task);
5514            return Vec::new();
5515        }
5516        // A branch an earlier attempt still holds and magi will not release
5517        // by itself is the operator's call, not a failed attempt: hold the
5518        // task with the reason, spend nothing, and say so on the bell.
5519        Err(e) if task.pr_recovery.is_some() => {
5520            task.startup_notice_cause("startup-public-head");
5521            task.attempts += 1;
5522            task.last_error = Some(format!("{start_failed}{e:#}"));
5523            task.hold_unrequested_retry(Some(format!(
5524                "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."
5525            )));
5526            record(queue, task);
5527            return Vec::new();
5528        }
5529        Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
5530            let detail = match e.downcast_ref::<crate::handover::Refused>() {
5531                Some(r) => (p.handover_refused)(r),
5532                None => format!("{e:#}"),
5533            };
5534            task.startup_notice_cause("startup-handover");
5535            let reason = format!("{start_failed}{detail}");
5536            task.last_error = Some(reason.clone());
5537            // Consumed above by `take`; keep it so the released task retries
5538            // as a review of this same branch.
5539            let branch = match &starter {
5540                Starter::Review(branch) => Some(branch.clone()),
5541                _ => None,
5542            };
5543            // The hold's own `task:<id>` notice (raised by `Queue::put`) is the
5544            // one page; the guidance rides in the reason, fixed per state so a
5545            // re-put never changes the wording and relights it.
5546            task.hold_for_handover(branch, format!("{reason}{}", p.handover_hint));
5547            record(queue, task);
5548            tracing::warn!(
5549                "holding {} for a branch it cannot take over: {e:#}",
5550                task.short()
5551            );
5552            return Vec::new();
5553        }
5554        // A branch that differs between here and the remote in ways magi
5555        // cannot prove are the same change is a decision for the owner, not a
5556        // failed attempt: ask with both sides laid out, spend no attempt, and
5557        // let the answer requeue the task.
5558        Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
5559            let d = e
5560                .downcast_ref::<crate::reconcile::Diverged>()
5561                .expect("checked by the guard");
5562            let mut q = ask::Question::new(
5563                task.id.clone(),
5564                crate::reconcile::NODE.to_owned(),
5565                crate::reconcile::SEAT.to_owned(),
5566                d.summary(),
5567                d.detail(),
5568                d.choices(),
5569            );
5570            match Questions::open().put(&mut q) {
5571                Ok(()) => {
5572                    task.last_error = Some(format!("{e:#}"));
5573                    // Consumed above by `take`; the answer has to reach a review
5574                    // of this same branch, so keep pointing the task at it.
5575                    task.review_branch = Some(d.branch.clone());
5576                    task.review_instruction = Some(task.instruction.clone());
5577                    task.block(vec![q.id.clone()], Some(d.summary()));
5578                }
5579                Err(put) => {
5580                    tracing::warn!("could not file the divergence question: {put:#}");
5581                    task.attempts += 1;
5582                    task.fail_startup(
5583                        "startup-question-store",
5584                        format!("{start_failed}{e:#}"),
5585                        opts.max_attempts,
5586                    );
5587                }
5588            }
5589            record(queue, task);
5590            return Vec::new();
5591        }
5592        Err(e) => {
5593            // The answer was stale and nothing was applied: keep pointing at
5594            // the branch so the next attempt asks again against its new tips.
5595            // Nothing went wrong with the task, so no attempt is spent: a
5596            // budget one short of its limit must not hold it instead of
5597            // letting the question be asked again.
5598            if e.downcast_ref::<crate::reconcile::Stale>().is_some()
5599                && let Starter::Review(branch) = &starter
5600            {
5601                task.review_branch = Some(branch.clone());
5602                task.review_instruction = Some(task.instruction.clone());
5603                task.last_error = Some(format!("{start_failed}{e:#}"));
5604                task.status = crate::queue::TaskStatus::Failed;
5605                record(queue, task);
5606                return Vec::new();
5607            }
5608            task.attempts += 1;
5609            task.last_error = Some(format!("{start_failed}{e:#}"));
5610            task.startup_notice_cause("startup-source");
5611            task.hold_unrequested_retry(Some(format!(
5612                "Startup failed: {e:#}. Correct the startup source or configuration, then explicitly release the task; automatic recovery is stopped."
5613            )));
5614            record(queue, task);
5615            return Vec::new();
5616        }
5617    };
5618    if !matches!(starter, Starter::Resume(_))
5619        && let Some((mode, source)) = task.build_cache_override(&runner.state.config)
5620    {
5621        runner
5622            .state
5623            .event("build-cache", format!("{mode} selected by {source}"));
5624    }
5625    if task.pr_recovery.is_some() && !matches!(starter, Starter::Resume(_)) {
5626        runner.state.recovery_config = Some(config_evidence);
5627    }
5628    if let Some(replacement) = &task.replacement {
5629        if matches!(starter, Starter::Start) {
5630            runner.state.instruction.push_str(&format!(
5631                "\n\n# Replacement review context\n{}",
5632                replacement.context
5633            ));
5634        }
5635        runner.state.replaces = Some(replacement.clone());
5636        runner.state.config.graph.selected_implementer = Some(replacement.agent.clone());
5637        if let Ok(mut old) = RunState::load(&replacement.run)
5638            && let Some(d) = &mut old.merge_decision
5639        {
5640            d.replacement_run = Some(runner.state.id.clone());
5641            old.event(
5642                "replacement",
5643                format!(
5644                    "replacement run {} owns the next attempt; old PR remains closed",
5645                    runner.state.id
5646                ),
5647            );
5648            if let Err(e) = old.save() {
5649                let error = runner.fail_startup("replacement-history", e);
5650                if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5651                    task.record_startup_failure(failure.clone());
5652                }
5653                task.hold_manual(Some(format!(
5654                    "Could not link replacement history: {error:#}; no agents dispatched"
5655                )));
5656                record(queue, task);
5657                return Vec::new();
5658            }
5659        }
5660    }
5661    runner.state.task_instruction = Some(task.instruction.clone());
5662    // The follow-up depth is fixed now, while the task certainly exists:
5663    // deleting it later must not reset the cap (`crate::followup`).
5664    runner.state.followup_generation = Some(task.followup.as_ref().map_or(0, |f| f.generation));
5665    if runner.state.origin_chat.is_none() {
5666        runner.state.origin_chat = task.chat_talk().map(str::to_owned);
5667    }
5668    // A stop that means "park" reaches the graph through this handle.
5669    runner.on_pause(stop.pause());
5670    // `poll`'s interrupt scheduler reaches this one run - and no other -
5671    // through this handle. See `Pause`'s own doc for why these are never
5672    // the same one.
5673    runner.watch_interrupt(interrupt_pause);
5674
5675    // `start` has minted the run, so the task can now point at it. Persisting
5676    // `Running` before `execute` is what makes a crash mid-run legible.
5677    let run = runner.state.id.clone();
5678    let before_start = task.clone();
5679    task.start(run.clone());
5680    if let Err(error) = queue.put(task) {
5681        *task = before_start;
5682        let error = runner.fail_startup("task-start", error);
5683        if let Some(failure) = error.downcast_ref::<crate::run::StartupFailure>() {
5684            task.record_startup_failure(failure.clone());
5685        }
5686        task.hold_manual(Some(format!(
5687            "Could not persist task start; no agents dispatched: {error:#}"
5688        )));
5689        record(queue, task);
5690        return Vec::new();
5691    }
5692    if task.status != TaskStatus::Running {
5693        // Queue::put kept a newer hold or continuation instead of this start.
5694        return Vec::new();
5695    }
5696    lock(status).current.push(Current {
5697        worker: None,
5698        task: task.id.clone(),
5699        run,
5700    });
5701
5702    // `RunState::quota` is the run's whole history across every resume, so
5703    // only what this execution added may arm the cooldown or earn a refund.
5704    let quota_before = runner.state.quota.clone();
5705    runner.state.carry_dispatched_resumes(task);
5706    runner.state.entry_resumption_generation =
5707        Some(task.resumption.as_ref().map_or(0, |r| r.generation));
5708    if let Some((run, stop_id, generation, approval_at)) = head_e2e_approval
5709        && runner.state.id == run
5710    {
5711        crate::head_e2e_stop::record_consumed_approval(
5712            &mut runner.state,
5713            &task.id,
5714            &stop_id,
5715            generation,
5716            approval_at,
5717        );
5718    }
5719    runner.state.next_pass_task_entry = true;
5720    let result = runner.execute().await;
5721    finish_attempt(
5722        opts.max_attempts,
5723        queue,
5724        task,
5725        &runner.state,
5726        &quota_before,
5727        result,
5728    )
5729}
5730
5731async fn attempt_sync_only(
5732    queue: &Queue,
5733    status: &Arc<Mutex<Status>>,
5734    stop: &Stop,
5735    interrupt: crate::graph::Pause,
5736    task: &mut Task,
5737    request: crate::base_sync_only::Request,
5738) {
5739    let result = async {
5740        anyhow::ensure!(
5741            task.status == TaskStatus::Queued
5742                && task.execution_runs().last() == Some(&request.run)
5743                && task.resume_override.as_ref().is_some_and(
5744                    |pin| pin.at == request.at && pin.pinned_run.as_ref() == Some(&request.run)
5745                ),
5746            "sync-base-only request no longer owns the exact queued run"
5747        );
5748        let mut runner = Runner::resume(&request.run)?;
5749        anyhow::ensure!(
5750            public_resume_owner(&crate::run::home(), &task.runs, &runner.state.repo)
5751                .await?
5752                .is_none(),
5753            "the task still has a public execution owner"
5754        );
5755        anyhow::ensure!(
5756            !stop.parking() && !interrupt.parked(),
5757            "paused before base synchronization"
5758        );
5759        let original = task.clone();
5760        task.start(request.run.clone());
5761        task.attempts = original.attempts;
5762        if let Err(error) = queue.put(task) {
5763            *task = original;
5764            return Err(error);
5765        }
5766        if task.status != TaskStatus::Running || task.sync_only.as_ref() != Some(&request) {
5767            return Ok(());
5768        }
5769        lock(status).current.push(Current {
5770            worker: None,
5771            task: task.id.clone(),
5772            run: request.run.clone(),
5773        });
5774        runner.on_pause(stop.pause());
5775        runner.watch_interrupt(interrupt);
5776        runner.execute_sync_only(request.clone()).await
5777    }
5778    .await;
5779    if task.sync_only.as_ref() == Some(&request) {
5780        let saved = RunState::load(&request.run).ok();
5781        let detail = result.err().map(|error| {
5782            format!("Base synchronization only: {error:#}; verification was not allowed")
5783        });
5784        crate::base_sync_only::settle(task, &request, saved.as_ref(), detail);
5785        record(queue, task);
5786    }
5787}
5788
5789/// Settle `task` after its run executed: the verdict, the diagnosis, the
5790/// supersession of earlier attempts and the save. Shared by the loop and by
5791/// `magi run --resume`, so an attempt is counted one way wherever it ran.
5792/// Returns the quota losses this execution added to the run.
5793pub fn finish_attempt(
5794    max_attempts: usize,
5795    queue: &Queue,
5796    task: &mut Task,
5797    state: &RunState,
5798    quota_before: &[QuotaLoss],
5799    result: Result<()>,
5800) -> Vec<QuotaLoss> {
5801    let detail = match result {
5802        Ok(()) => describe(state),
5803        Err(e) => format!("{e:#}"),
5804    };
5805    let fresh = losses_this_attempt(quota_before, &state.quota);
5806    let verdict = Verdict {
5807        status: state.status,
5808        // A run that opened a pull request handed its work over, whatever the
5809        // gate then decided about merging it.
5810        left_pr: state.pr.is_some(),
5811        // Only a rate limit earns the task its attempt back - and only one
5812        // suffered now: a refund justified by a previous session's loss is
5813        // the same mistake as re-arming the cooldown from it. A stalled run
5814        // resumed without hitting quota again therefore spends its attempt,
5815        // like any other failure of the task's own.
5816        quota_hit: !fresh.is_empty(),
5817        // A run that parked was asked to stop; that is not a failure and must
5818        // not spend an attempt, or replacing the binary a few times would
5819        // exhaust a task's budget without an agent ever misbehaving.
5820        parked: state.parked,
5821        // A quota loss that left nothing viable is the same machine fact as a
5822        // `Stalled` quota loss; see `settle`'s doc table.
5823        no_viable_candidates: state.viable().is_empty(),
5824    };
5825    if let Some(replacement) = &state.replaces
5826        && let Some(pr) = &state.pr
5827        && let Ok(mut old) = RunState::load(&replacement.run)
5828        && let Some(d) = &mut old.merge_decision
5829    {
5830        d.replacement_pr = Some(pr.url.clone());
5831        let _ = old.save();
5832    }
5833    settle_and_diagnose(task, verdict, &detail, max_attempts, state);
5834    if state.status == RunStatus::Blocked && state.prep_failure.is_some() {
5835        task.hold_unrequested_retry(Some(format!(
5836            "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.",
5837            task.short()
5838        )));
5839    }
5840    if task.status == TaskStatus::Done {
5841        supersede_prior_runs(task, &crate::run::home());
5842    }
5843    record(queue, task);
5844    tracing::info!(
5845        "task {} is {} after run {} ({})",
5846        task.short(),
5847        task.status.as_str(),
5848        state.short(),
5849        label(state.status)
5850    );
5851    fresh
5852}
5853
5854/// A task a hand-started run leaves runnable (failed with attempts to spare,
5855/// or requeued) is **held**: nobody asked for a retry, and a loop starting
5856/// later must not spend agent calls on it. `magi task release` retries.
5857pub fn hold_if_runnable(queue: &Queue, task: &mut Task) {
5858    // Parked work (including legacy Failed records with a parked run) is a
5859    // checkpoint or owner handoff, not an unrequested retry.
5860    if matches!(task.status, TaskStatus::Queued | TaskStatus::Failed)
5861        && !awaiting_resume_with(task, RunState::load)
5862        // A run parked on the owner's word about a withheld PR title/body
5863        // resumes via `land_resume_state`, including review-only tasks that
5864        // `awaiting_resume_with` does not consider.
5865        && withheld_text_wait(task).is_none()
5866        && !(task.fresh_start && task.replacement.is_some())
5867    {
5868        let why = task.last_error.clone().map_or_else(
5869            || "the run did not finish".to_owned(),
5870            |e| format!("the run did not finish: {e}"),
5871        );
5872        task.hold_unrequested_retry(Some(format!(
5873            "{why}. It was started by hand, so it is not retried \
5874             automatically; `magi task release` retries it."
5875        )));
5876        record(queue, task);
5877    }
5878}
5879
5880/// Whether an attempt at a task whose newest run is `run` would resume that
5881/// run rather than start a fresh competition. `magi run --resume` hands a run
5882/// to a live loop only when this holds.
5883#[must_use]
5884pub fn loop_would_resume(run: &str) -> bool {
5885    unfinished_run(&[run.to_owned()], crate::run::short_of(run)).is_some()
5886}
5887
5888/// A loop in another process that is alive right now: a fresh heartbeat in
5889/// `<home>/daemon.json` published by a pid that is not `own_pid`. `Some(pid)`
5890/// carries the pid it published (`None` inside when it published none - a
5891/// fresh heartbeat is still evidence of a live loop).
5892///
5893/// The one judgement of "is somebody else serving this queue", shared by the
5894/// web UI's refusal to start a second loop and by `magi run` / `magi review`
5895/// deciding whether to hand a task to the loop. A claim file proves nothing
5896/// here: whether a claim succeeds says nothing about whether its owner lives.
5897#[must_use]
5898pub fn foreign_loop(
5899    reading: Option<&Reading>,
5900    now: Timestamp,
5901    own_pid: u32,
5902) -> Option<Option<u32>> {
5903    let reading = reading.filter(|r| r.running(now))?;
5904    match reading.pid {
5905        Some(pid) if pid == own_pid => None,
5906        pid => Some(pid),
5907    }
5908}
5909
5910fn legacy_scheduler_running(reading: &Reading, now: Timestamp, own_pid: u32) -> bool {
5911    reading.worker_protocol != Some(1)
5912        && (foreign_loop(Some(reading), now, own_pid).is_some()
5913            || reading
5914                .pid
5915                .is_some_and(|pid| pid != own_pid && crate::proc::pid_alive(pid)))
5916}
5917
5918/// Low-level claimed-task execution shared by the detached standalone worker
5919/// and focused lifecycle fixtures. The caller must retain the queue claim for
5920/// this entire call. CLI callers transfer ownership through
5921/// [`run_detached_claimed`] instead of executing inside their own runtime.
5922///
5923/// The one deliberate difference from the loop: a task the attempt leaves
5924/// runnable (failed with attempts to spare, or requeued) is **held** instead.
5925/// Nobody asked for a retry, and a daemon starting later must not spend agent
5926/// calls re-running a hand-started task behind the operator's back;
5927/// `magi task release` is the explicit retry.
5928pub async fn run_claimed(opts: &Opts, queue: &Queue, task: &mut Task) {
5929    run_claimed_until(opts, queue, task, &Stop::new()).await;
5930}
5931
5932async fn run_claimed_until(
5933    opts: &Opts,
5934    queue: &Queue,
5935    task: &mut Task,
5936    stop: &Stop,
5937) -> Vec<QuotaLoss> {
5938    let status = Arc::new(Mutex::new(Status::new()));
5939    // An attempt embeds startup and graph futures. Keep it off the standalone
5940    // caller's stack, on both the initial execution and withheld-text resume.
5941    let mut quota = Box::pin(attempt(
5942        opts,
5943        queue,
5944        &status,
5945        stop,
5946        crate::graph::Pause::new(),
5947        task,
5948    ))
5949    .await;
5950    // A run parked on the owner's word about a withheld PR title/body has no
5951    // daemon to finish it. Nobody else will enforce `answer_timeout`, so wait
5952    // here with the claim still held, and resume once the question is settled
5953    // (answered, or abandoned at its deadline -> the neutral text).
5954    // A rejected reply files one more question (the gate asks at most twice),
5955    // so after a resume the run may be waiting again: keep going, with a fresh
5956    // limit for the new question. `resumes` bounds it even if a resume parks
5957    // without asking anything new.
5958    let mut resumes = 0;
5959    while resumes < MAX_WITHHELD_RESUMES && !stop.parking() {
5960        let Some(timeout) = withheld_text_wait(task) else {
5961            break;
5962        };
5963        eprintln!(
5964            "waiting for the owner's answer on a withheld pull request text \
5965             (up to {timeout}s; Ctrl-C leaves the run parked for a later `magi serve`)"
5966        );
5967        // The deadline abandons the question itself; the extra margin only
5968        // covers an abandon that could not be saved.
5969        let limit = std::time::Instant::now() + Duration::from_secs(timeout + 60);
5970        let ready = loop {
5971            match land_resume_state(task) {
5972                LandResume::StillWaiting
5973                    if !stop.parking() && std::time::Instant::now() < limit =>
5974                {
5975                    tokio::time::sleep(WITHHELD_POLL).await;
5976                }
5977                LandResume::Ready => break true,
5978                _ => break false,
5979            }
5980        };
5981        if !ready || stop.parking() {
5982            break;
5983        }
5984        resumes += 1;
5985        quota.extend(
5986            Box::pin(attempt(
5987                opts,
5988                queue,
5989                &status,
5990                stop,
5991                crate::graph::Pause::new(),
5992                task,
5993            ))
5994            .await,
5995        );
5996    }
5997    hold_if_runnable(queue, task);
5998    quota
5999}
6000
6001/// Resumes an in-process run makes for withheld-text questions: the gate asks
6002/// at most twice, plus one for a resume that asks nothing new.
6003const MAX_WITHHELD_RESUMES: u32 = 3;
6004
6005/// How often an in-process run rechecks its withheld-text question.
6006const WITHHELD_POLL: Duration = Duration::from_secs(15);
6007
6008/// The `answer_timeout` (seconds) of the task's last run when that run is
6009/// parked on an unresolved withheld-text question; `None` otherwise.
6010fn withheld_text_wait(task: &Task) -> Option<u64> {
6011    let id = task.execution_runs().last()?;
6012    let s = RunState::load(id).ok()?;
6013    (s.parked && s.github_text.as_ref().is_some_and(|g| !g.resolved))
6014        .then_some(s.config.graph.answer_timeout)
6015}
6016
6017/// The quota losses `after` holds that `before` did not: what one execution
6018/// suffered, as opposed to the run's history.
6019///
6020/// Compared by value rather than by length or position because
6021/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
6022/// the vector can shrink and shift under a resume. A retried seat that hits
6023/// quota again is a `push` with a new `at`, so it shows up as new here.
6024/// Crash recovery uses the recorded pass start as its boundary when available;
6025/// legacy records without passes retain their original history-based policy.
6026fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
6027    after
6028        .iter()
6029        .filter(|q| !before.contains(q))
6030        .cloned()
6031        .collect()
6032}
6033
6034/// When the loop-wide quota cooldown should end, given this attempt's losses;
6035/// `None` when there were none. Reset-hint parsing and the cap live here.
6036fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
6037    let quota: Vec<_> = quota
6038        .iter()
6039        .filter(|q| q.cause == crate::agent::QuotaCause::UsageLimit)
6040        .collect();
6041    if quota.is_empty() {
6042        return None;
6043    }
6044    let with_hint = quota.iter().find(|q| q.reset.is_some());
6045    let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
6046    let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
6047    let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
6048    Some(
6049        now.checked_add(jiff::SignedDuration::from_secs(secs))
6050            .unwrap_or(Timestamp::MAX),
6051    )
6052}
6053
6054/// An explicit task count must agree with a run before any resume.
6055fn implementers_match(task: &Task, state: &RunState) -> bool {
6056    task.replacement.as_ref().map_or_else(
6057        || {
6058            task.implementers()
6059                .is_none_or(|n| n == state.config.graph.implementers)
6060        },
6061        |replacement| {
6062            state.config.graph.selected_implementer.as_deref() == Some(&replacement.agent)
6063                && state.config.graph.implementers == 1
6064        },
6065    )
6066}
6067
6068/// Never resume or take over candidate work built for a different seat count.
6069fn starter_with_implementers(
6070    task: &Task,
6071    previous: Option<&RunState>,
6072    proposed: Starter,
6073) -> Starter {
6074    if previous.is_some_and(|s| !implementers_match(task, s)) {
6075        task.review_of
6076            .as_ref()
6077            .map_or(Starter::Start, |branch| Starter::Review(branch.clone()))
6078    } else {
6079        proposed
6080    }
6081}
6082
6083/// Apply this task's explicit count to the new attempt, without changing defaults.
6084fn apply_task_implementers(config: &mut Config, task: &Task) {
6085    if let Some(n) = task.implementers() {
6086        config.graph.implementers = n;
6087    }
6088}
6089
6090/// [`prepare`] for one task: its own `--config` and command-line overrides
6091/// (`Task::overrides`, filed by `magi run` / `magi review`) take precedence
6092/// over the loop's, so handing a hand-started task to a daemon changes nothing
6093/// about what it does.
6094#[cfg(test)]
6095fn prepare_for(repo: &Path, opts: &Opts, task: &Task) -> Result<Config> {
6096    let explicit = match &task.overrides {
6097        Some(o) if !o.inherit_daemon_options => o.config.as_deref(),
6098        _ => opts.config.as_deref(),
6099    };
6100    let (mut config, _) = Config::discover(repo, explicit)?;
6101    apply_options(&mut config, opts, task)?;
6102    Ok(config)
6103}
6104
6105fn apply_options(config: &mut Config, opts: &Opts, task: &Task) -> Result<()> {
6106    if task
6107        .overrides
6108        .as_ref()
6109        .is_none_or(|o| o.inherit_daemon_options)
6110        && let Some(mode) = opts.merge.as_deref()
6111    {
6112        config.merge.mode = merge_mode(mode)?;
6113    }
6114    if let Some(o) = &task.overrides {
6115        o.apply(config);
6116    }
6117    if let Some((mode, _)) = task.build_cache_override(config) {
6118        config.verify.build_cache = mode;
6119    }
6120    Ok(())
6121}
6122
6123/// Load the config for a task's repository, with the merge override applied.
6124fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
6125    let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
6126    if let Some(mode) = &opts.merge {
6127        config.merge.mode = merge_mode(mode)?;
6128    }
6129    Ok(config)
6130}
6131
6132/// Prune the shared build cache at a between-runs boundary. The detached cache
6133/// service checks authoritative task jobs first; dispatch waits for that finite
6134/// service, so scheduler replacement cannot turn a compile into idle cleanup.
6135/// Its durable service cadence preserves [`CACHE_CHECK_INTERVAL_SECS`].
6136async fn maybe_prune_cache_between_runs(
6137    repo: &Path,
6138    opts: &Opts,
6139    home: &Path,
6140    stop: &Stop,
6141    last_checked: &mut Option<Timestamp>,
6142    now: Timestamp,
6143) {
6144    if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
6145        return;
6146    }
6147    *last_checked = Some(now);
6148    let cfg = match prepare(repo, opts) {
6149        Ok(cfg) => cfg,
6150        Err(e) => {
6151            tracing::warn!("cache check: no config: {e:#}");
6152            return;
6153        }
6154    };
6155    match clean::prune_cache_if_over_limit(&cfg, home) {
6156        Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
6157            "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
6158            pruned.files,
6159            pruned.freed
6160        ),
6161        Ok(_) => {}
6162        Err(e) => {
6163            tracing::warn!("housekeep: prune cache: {e:#}");
6164            notices::raise_in(
6165                home,
6166                Notice::warn(
6167                    "housekeep:cache",
6168                    format!(
6169                        "Pruning the shared build cache failed: {}. Disk usage may keep growing.",
6170                        e.to_string()
6171                            .lines()
6172                            .next()
6173                            .unwrap_or("unknown cleanup error")
6174                    ),
6175                ),
6176            );
6177        }
6178    }
6179}
6180
6181/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
6182/// now, given when it last did (if ever). Pure, so the cadence is asserted
6183/// directly rather than by waiting out real minutes in a test.
6184fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
6185    last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
6186}
6187
6188/// The disk janitor, with its housekeeping logged rather than fatal.
6189///
6190/// Called only at the loop's idle points, for the reason the caller documents:
6191/// a prune racing a live compile would delete files mid-build. The config is
6192/// re-read on every call because the repository that just ran may not be the
6193/// daemon's own default, and the cache directory is a repository fact.
6194///
6195/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
6196/// and [`crate::run::default_worktree_root`] read here, for the same reason
6197/// [`drive`] takes its queue and status file rather than resolving them: a
6198/// test driving the loop must not reach through to the operator's real home
6199/// or worktree bay just because the janitor runs on every idle tick.
6200/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
6201/// to get wrong silently - a test's `home` was already isolated, but nothing
6202/// exercised the parameter next to it, so a real worktree bay stayed wired in
6203/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
6204/// it for real, every test in this file that drives the loop at all started
6205/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
6206async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
6207    let cfg = match prepare(repo, opts) {
6208        Ok(cfg) => cfg,
6209        Err(e) => {
6210            tracing::warn!("housekeep: no config: {e:#}");
6211            return;
6212        }
6213    };
6214    // A run's own worktree lives under `config.graph.worktree_root` when the
6215    // repository sets one - the same precedence `RunState::worktree_root`
6216    // uses - and `worktrees_root` only stands in for the *default* an
6217    // unconfigured repository resolves to (see this function's own
6218    // parameter, or the test fixture wiring one to a fake path). Housekeeping
6219    // that always swept the default regardless of this override would never
6220    // see, and so never reclaim, a single worktree for a repository that
6221    // relocated them elsewhere.
6222    let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
6223    let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
6224    // Reported whenever there is anything to say, not only when `folded > 0`:
6225    // the incident this exists to prevent was 90 of 93 runs skipped and 0
6226    // folded, on every single pass, for months - a report gated on `folded`
6227    // would have stayed silent through every one of them.
6228    if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
6229        let mut extra = Vec::new();
6230        if out.unreadable > 0 {
6231            extra.push(format!("{} unreadable", out.unreadable));
6232        }
6233        if out.orphaned_worktrees > 0 {
6234            extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
6235        }
6236        let detail = if extra.is_empty() {
6237            String::new()
6238        } else {
6239            format!(" ({})", extra.join(", "))
6240        };
6241        tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
6242    }
6243    if out.external_merges_recorded > 0 {
6244        tracing::info!(
6245            "housekeep: recorded {} run(s) as merged externally",
6246            out.external_merges_recorded
6247        );
6248    }
6249    if out.stale_pr_states_repaired > 0 {
6250        tracing::info!(
6251            "housekeep: rewrote {} run record(s) whose pull request had already settled",
6252            out.stale_pr_states_repaired
6253        );
6254    }
6255    if out.cache_files > 0 {
6256        tracing::info!(
6257            "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
6258            out.cache_files,
6259            out.cache_freed
6260        );
6261    }
6262    if out.questions_abandoned > 0 {
6263        tracing::info!(
6264            "housekeep: abandoned {} question(s) left open by a finished run",
6265            out.questions_abandoned
6266        );
6267    }
6268}
6269
6270/// Run [`triage::run_once`] and log whatever it did, the same "only when
6271/// there is something to say" rule [`janitor`] follows for its own report.
6272///
6273/// Called at the same idle points as [`janitor`] - once per full poll
6274/// interval, never mid-attempt - for the same reason: it is not liveness
6275/// critical, and a task's own `hold_reason` string is the one thing this
6276/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
6277/// tick for no benefit.
6278async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
6279    let questions = Questions::at(home.join("questions"));
6280    let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
6281    if report.is_empty() {
6282        return;
6283    }
6284    if !report.quarantined.is_empty() {
6285        tracing::info!(
6286            "triage: held {} blocked task(s) whose blocked-on task or \
6287             question no longer exists: {}",
6288            report.quarantined.len(),
6289            report.quarantined.join(", ")
6290        );
6291    }
6292    if !report.resumed.is_empty() {
6293        tracing::info!(
6294            "triage: resumed {} held task(s) whose machine hold had resolved: {}",
6295            report.resumed.len(),
6296            report.resumed.join(", ")
6297        );
6298    }
6299    if !report.asked.is_empty() {
6300        tracing::info!(
6301            "triage: asked about {} held task(s): {}",
6302            report.asked.len(),
6303            report.asked.join(", ")
6304        );
6305    }
6306    if !report.answered.is_empty() {
6307        tracing::info!(
6308            "triage: applied {} operator answer(s): {}",
6309            report.answered.len(),
6310            report.answered.join(", ")
6311        );
6312    }
6313}
6314
6315/// The free-space gate: what stands between this task and a new run, if
6316/// anything. `Some(reason)` holds the task; `None` lets it start.
6317///
6318/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
6319/// the operator opted out. A measurement failure is a gate, not a pass: both
6320/// sides of "cannot tell" are served by not starting.
6321pub(crate) fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
6322    disk_gate_at(repo, config, crate::run::home)
6323}
6324
6325pub(crate) fn disk_gate_at(
6326    repo: &Path,
6327    config: &Config,
6328    home: impl FnOnce() -> PathBuf,
6329) -> Option<String> {
6330    let measure = if crate::build_target::isolated(config) {
6331        crate::disk::managed_free_bytes
6332    } else {
6333        crate::disk::free_bytes
6334    };
6335    disk_gate_with(repo, config, home, measure)
6336}
6337
6338/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
6339/// test can assert the exact wiring `attempt` runs - config's threshold in,
6340/// task-holding reason out - without asking the real machine's disk anything.
6341fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
6342    repo: &Path,
6343    config: &Config,
6344    home: impl FnOnce() -> PathBuf,
6345    free_bytes: F,
6346) -> Option<String> {
6347    let min = config.disk.min_free_bytes;
6348    if min == 0 {
6349        return None;
6350    }
6351    let output = match config.verify.build_cache {
6352        BuildCache::Shared => config.cache_dir(),
6353        BuildCache::Isolated => Some(home()),
6354    };
6355    let default_worktree_root;
6356    let worktree_root = match config.graph.worktree_root.as_deref() {
6357        Some(root) => root,
6358        None => {
6359            default_worktree_root = crate::run::default_worktree_root();
6360            &default_worktree_root
6361        }
6362    };
6363    for path in [Some(repo), output.as_deref(), Some(worktree_root)]
6364        .into_iter()
6365        .flatten()
6366    {
6367        let probe = if path == repo {
6368            path
6369        } else {
6370            path.ancestors().find(|p| p.exists()).unwrap_or(path)
6371        };
6372        let reason = match free_bytes(probe) {
6373            Ok(free) => crate::disk::gate_in(free, min, &config.graph.language),
6374            Err(e) => Some(crate::disk::unmeasured_in(
6375                probe,
6376                &e,
6377                &config.graph.language,
6378            )),
6379        };
6380        if reason.is_some() {
6381            return reason;
6382        }
6383    }
6384    None
6385}
6386
6387/// How long to wait before offering another task when a run lost a seat to a
6388/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
6389/// could read, or carried nothing at all. Long enough that a quota outage
6390/// cannot burn through a whole backlog in the few seconds each doomed attempt
6391/// takes to fail; short enough that a quota which clears early is not left
6392/// idle for the fallback's sake.
6393const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
6394
6395/// Longest a parsed reset hint may push the wait out to. The hint comes from
6396/// the CLI's own words, not a contract, so a parsing slip that lands a day
6397/// away must not leave the loop asleep for a day.
6398const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
6399
6400/// How long [`poll`] should wait before offering the next task, after a run
6401/// lost at least one seat to a rate limit.
6402///
6403/// Pure and separate from the loop so the policy can be exercised without a
6404/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
6405/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
6406/// nothing to parse, or the parsed time has already passed; `cap` bounds how
6407/// far a parsed hint is trusted to push the wait out.
6408fn quota_wait(
6409    reset_at: Option<Timestamp>,
6410    now: Timestamp,
6411    fallback: Duration,
6412    cap: Duration,
6413) -> Duration {
6414    match reset_at {
6415        Some(at) if at > now => {
6416            let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
6417            Duration::from_secs(secs).min(cap)
6418        }
6419        _ => fallback,
6420    }
6421}
6422
6423/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
6424///
6425/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
6426/// explains why parsing it exactly "would be a bug factory" — so this only
6427/// recognises the shapes actually observed in the wild, and returns `None`
6428/// for anything else rather than guess at a format nobody has seen.
6429///
6430/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
6431/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
6432/// said it, not from whenever this loop happens to read it: anchoring on `now`
6433/// would push the reset later on every read and would read an already-elapsed
6434/// reset as still in the future. (A long hint is still clamped by
6435/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
6436fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
6437    parse_reset_hint_zoned(text, now)
6438        .or_else(|| parse_reset_hint_dated(text))
6439        .or_else(|| parse_reset_hint_relative(text, recorded))
6440}
6441
6442/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
6443/// optional but at least one required, in that order. A bare number or any
6444/// unknown unit is refused.
6445fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
6446    let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
6447    let mut rest = rest.trim();
6448    if rest.is_empty() {
6449        return None;
6450    }
6451    let mut total: i64 = 0;
6452    let mut matched = false;
6453    for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
6454        if let Some((digits, tail)) = rest.split_once(unit)
6455            && !digits.is_empty()
6456            && digits.bytes().all(|b| b.is_ascii_digit())
6457        {
6458            total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
6459            rest = tail;
6460            matched = true;
6461        }
6462    }
6463    if !rest.is_empty() || !matched {
6464        return None;
6465    }
6466    recorded
6467        .checked_add(jiff::SignedDuration::from_secs(total))
6468        .ok()
6469}
6470
6471/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
6472/// case-insensitive) into a 24-hour hour and minute. Shared by every
6473/// reset-hint shape below.
6474fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
6475    let clock = clock.trim().to_lowercase();
6476    let (digits, pm) = clock
6477        .strip_suffix("am")
6478        .map(|d| (d, false))
6479        .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
6480    let (h, m) = digits.trim().split_once(':')?;
6481    let mut hour: i8 = h.trim().parse().ok()?;
6482    let minute: i8 = m.trim().parse().ok()?;
6483    if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
6484        return None;
6485    }
6486    if pm && hour != 12 {
6487        hour += 12;
6488    } else if !pm && hour == 12 {
6489        hour = 0;
6490    }
6491    Some((hour, minute))
6492}
6493
6494/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
6495/// and a zone, never a date. A clock reading already past today is read as
6496/// tomorrow's: a CLI naming a same-day reset that has already gone by means
6497/// the window rolled over while nothing was watching.
6498fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
6499    let open = text.find('(')?;
6500    let close = text.rfind(')')?;
6501    if close <= open {
6502        return None;
6503    }
6504    let zone = text[open + 1..close].trim();
6505    let (hour, minute) = parse_12h_clock(&text[..open])?;
6506    let tz = jiff::tz::TimeZone::get(zone).ok()?;
6507    let candidate = now
6508        .to_zoned(tz)
6509        .with()
6510        .hour(hour)
6511        .minute(minute)
6512        .second(0)
6513        .millisecond(0)
6514        .microsecond(0)
6515        .nanosecond(0)
6516        .build()
6517        .ok()?;
6518    let mut at = candidate.timestamp();
6519    if at <= now {
6520        at += jiff::SignedDuration::from_hours(24);
6521    }
6522    Some(at)
6523}
6524
6525/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
6526/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
6527/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
6528/// "already past today" correction to make: the year already disambiguates
6529/// it. Scanned as a five-word window so it can be pulled out of the middle
6530/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
6531/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
6532/// any other timestamp with no zone attached.
6533fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
6534    let words: Vec<&str> = text.split_whitespace().collect();
6535    if words.len() < 5 {
6536        return None;
6537    }
6538    (0..=words.len() - 5)
6539        .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
6540}
6541
6542/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
6543/// parenthesis right after the window is refused rather than ignored — it
6544/// reads as an explicit zone annotation on a shape that otherwise carries
6545/// none, and guessing UTC anyway would be exactly the silent misread this
6546/// module's parsing otherwise avoids.
6547fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
6548    if trailing.is_some_and(|next| next.starts_with('(')) {
6549        return None;
6550    }
6551    let month = month_number(window[0])?;
6552    let day_token = window[1].strip_suffix(',')?.to_lowercase();
6553    let day_digits = ["st", "nd", "rd", "th"]
6554        .iter()
6555        .find_map(|suffix| day_token.strip_suffix(*suffix))?;
6556    let day: i8 = day_digits.parse().ok()?;
6557    let year_token = window[2];
6558    if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
6559        return None;
6560    }
6561    let year: i16 = year_token.parse().ok()?;
6562    // The am/pm word carries the sentence's own trailing punctuation, e.g.
6563    // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
6564    // reusing the same 12-hour clock reader the bracketed shape uses.
6565    let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
6566    let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
6567    let date = jiff::civil::Date::new(year, month, day).ok()?;
6568    let candidate = date
6569        .at(hour, minute, 0, 0)
6570        .to_zoned(jiff::tz::TimeZone::UTC)
6571        .ok()?;
6572    Some(candidate.timestamp())
6573}
6574
6575/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
6576/// case-insensitively, into a 1-based month number.
6577fn month_number(name: &str) -> Option<i8> {
6578    const NAMES: [&str; 12] = [
6579        "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
6580    ];
6581    let lower = name.to_lowercase();
6582    NAMES
6583        .iter()
6584        .position(|n| *n == lower.as_str())
6585        .map(|i| i as i8 + 1)
6586}
6587
6588/// Test probe for the shared resume policy's review-budget exclusion.
6589#[cfg(test)]
6590fn exhausted_review_budget(state: &RunState) -> bool {
6591    // A run whose task-head publication failed has nothing left to review:
6592    // resuming it only retries the publication, so it is never "exhausted".
6593    !crate::handover::can_resume(state)
6594        && state.status == RunStatus::Blocked
6595        && !state.released()
6596        && state.retired_to.is_none()
6597}
6598
6599/// This task's *most recent* run, if resuming it would actually make
6600/// progress. `short` is only for the warning's own message.
6601///
6602/// Only ever `runs.last()` — never a search back through older history.
6603/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
6604/// mint, oldest first, and every entry before the last one was already
6605/// superseded at the moment it was minted: the daemon only ever starts a new
6606/// run when the previous one was not worth resuming (unresumable, exhausted,
6607/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
6608/// opens a fresh review-only run alongside an older, already-failed
6609/// competition. Searching further back would let an old run that merely
6610/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
6611/// behind, say — get resumed instead of the fresh competition
6612/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
6613/// nothing asked to revisit.
6614///
6615/// Two runs paid for the "prefer resuming over restarting" half of this
6616/// lesson, which is why this still checks `runs.last()` rather than always
6617/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
6618/// task a moment later, duplicating two and a half hours of agent work. Then
6619/// b25f stalled on a judge that timed out and one that answered with no JSON
6620/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
6621/// **one second** later, buying three fresh implementations to reach the
6622/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
6623/// the second case: a stall is terminal, and its cheap recovery re-asks only
6624/// the absent seats. [`crate::handover::can_resume`] supplies the other half: a run
6625/// that is technically `resumable()` but provably cannot progress must not
6626/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
6627/// no-op instead of the fresh competition it promises.
6628///
6629/// A load failure is warned about rather than silently read as "not
6630/// resumable": the alternative is exactly what let a schema mismatch on run
6631/// `eba2` fall through to a full re-competition with nobody told why.
6632/// `crate::conduct` is what actually offers a better answer than
6633/// `Runner::start` here (see `Recovery::Review`), once this task's next
6634/// failure shows it up as `held`/`failed` with the run state unreadable.
6635fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
6636    unfinished_run_with(runs, short, RunState::load)
6637}
6638
6639/// [`unfinished_run`] with an injected state reader. Tests provide their
6640/// fixtures directly rather than touching the process-global run home.
6641pub(crate) fn unfinished_run_with<F>(runs: &[String], short: &str, mut load: F) -> Option<String>
6642where
6643    F: FnMut(&str) -> Result<RunState>,
6644{
6645    let mut id = runs.last()?.clone();
6646    let mut visited = std::collections::BTreeSet::new();
6647    let mut repo = None;
6648    loop {
6649        if !runs.contains(&id) || !visited.insert(id.clone()) {
6650            tracing::warn!("invalid or cyclic recovery authority for task {short}");
6651            return None;
6652        }
6653        let state = match load(&id) {
6654            Ok(state) if state.id == id => state,
6655            Ok(_) => return None,
6656            Err(e) => {
6657                tracing::warn!("could not read run {id} for task {short}: {e:#}");
6658                return None;
6659            }
6660        };
6661        if repo.as_ref().is_some_and(|repo| *repo != state.repo) {
6662            return None;
6663        }
6664        repo = Some(state.repo.clone());
6665        if let Some(authority) = state.retired_to {
6666            id = authority;
6667            continue;
6668        }
6669        return (crate::handover::can_resume(&state)
6670            && state.liveness(false) != crate::run::Liveness::Live)
6671            .then_some(id);
6672    }
6673}
6674
6675/// Is `task` a parked (or, from an older build, failed) task whose last run was parked at a node boundary, so
6676/// that [`attempt`] will resume it on its own?
6677///
6678/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
6679/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
6680/// injected reader like its sibling. An unreadable run is not awaiting
6681/// anything: it keeps going to the conductor as before.
6682fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
6683where
6684    F: FnOnce(&str) -> Result<RunState>,
6685{
6686    // `Failed` stays: a record an older build wrote for a parked run.
6687    if !matches!(task.status, TaskStatus::Parked | TaskStatus::Failed)
6688        || task.fresh_start
6689        || task.review_branch.is_some()
6690    {
6691        return false;
6692    }
6693    let Some(id) = task.execution_runs().last() else {
6694        return false;
6695    };
6696    load(id).is_ok_and(|s| s.parked && crate::handover::can_resume(&s))
6697}
6698
6699/// Which of the three ways [`attempt`] can mint or continue a run this task
6700/// should use.
6701#[derive(Debug, Clone, PartialEq, Eq)]
6702enum Starter {
6703    /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
6704    /// and that still exists.
6705    Review(String),
6706    /// `crate::graph::Runner::resume` on an unfinished run of this task.
6707    Resume(String),
6708    /// `crate::graph::Runner::start`: a fresh competition.
6709    Start,
6710}
6711
6712/// A second bound independent of inputs and the resettable failure counter.
6713/// Count execution and failed-startup recovery records once per run. Startup
6714/// failures can retain unrecorded preparation assets without an execution pass.
6715/// Unknown history is not evidence that a new set of worktrees is affordable.
6716fn retained_attempt_hold(
6717    task: &Task,
6718    starter: &Starter,
6719    limit: usize,
6720    mut load: impl FnMut(&str) -> Result<RunState>,
6721) -> Option<String> {
6722    if limit == 0 || matches!(starter, Starter::Resume(_)) {
6723        return None;
6724    }
6725    let mut retained = 0;
6726    for id in task
6727        .runs
6728        .iter()
6729        .chain(task.startup_failures.iter().map(|failure| &failure.run))
6730        .collect::<std::collections::BTreeSet<_>>()
6731    {
6732        let state = match load(id) {
6733            Ok(state) if state.id == *id => state,
6734            _ => {
6735                return Some(format!(
6736                    "[recovery-backlog] Cannot verify historical run {id}. Restore its record and inspect the recovery lineage before starting another attempt. Existing history was retained."
6737                ));
6738            }
6739        };
6740        if state.retired_to.is_some() || state.released() {
6741            continue;
6742        }
6743        // Neither a completed status nor an empty candidate array proves that
6744        // all recovery sources (including unrecorded preparation) were retired.
6745        retained += 1;
6746    }
6747    (retained >= limit).then(|| format!(
6748        "[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."
6749    ))
6750}
6751
6752/// A selected public implementation overrides every historical candidate and pin.
6753fn selected_starter(
6754    selected: &crate::pr_recovery::Selection,
6755    previous: Option<&RunState>,
6756    unfinished: Option<&str>,
6757) -> Starter {
6758    if let Some(id) = unfinished
6759        && previous.is_some_and(|r| {
6760            r.id == id && r.pr_recovery.as_ref() == Some(selected) && r.reviewed_commits.is_some()
6761        })
6762    {
6763        Starter::Resume(id.to_owned())
6764    } else {
6765        Starter::Review(selected.branch.clone())
6766    }
6767}
6768
6769/// The owner's answer to this branch's divergence question, consumed from the
6770/// task so a later, different divergence asks again. The runner applies it
6771/// (see `Runner::review_taking_over`), after the earlier worktree is released.
6772fn take_divergence_answer(
6773    branch: &str,
6774    remote: &str,
6775    task: &mut Task,
6776) -> Option<crate::reconcile::Choice> {
6777    let summary = crate::reconcile::summary_for(branch, remote);
6778    let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
6779        (a.question == summary)
6780            .then(|| crate::reconcile::Choice::from_answer(&a.answer))
6781            .flatten()
6782            .map(|c| (i, c))
6783    })?;
6784    task.answers.remove(idx);
6785    Some(choice)
6786}
6787
6788/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
6789/// this attempt should use. Pure, and separate from [`attempt`], so the
6790/// routing itself is assertable without spawning a real graph or a git
6791/// process: `attempt`'s own `crate::git::branch_exists` call has already
6792/// happened by the time this is called.
6793///
6794/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
6795/// whose branch is gone falls all the way through to [`Starter::Start`], not
6796/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
6797/// old (likely `Blocked`) run in the first place, and a branch that vanished
6798/// out from under that choice is not evidence resuming it would fare better.
6799fn choose_starter(
6800    review_branch: Option<&str>,
6801    branch_exists: bool,
6802    unfinished: Option<&str>,
6803) -> Starter {
6804    match review_branch {
6805        Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
6806        Some(_) => Starter::Start,
6807        None => match unfinished {
6808            Some(id) => Starter::Resume(id.to_owned()),
6809            None => Starter::Start,
6810        },
6811    }
6812}
6813
6814/// Reuse a compatible latest review owner instead of taking its checked-out
6815/// branch into a new run. Different branches and changed criteria still use
6816/// the ordinary review/takeover policy.
6817fn review_retry_starter(
6818    task: &Task,
6819    previous: Option<&RunState>,
6820    branch: Option<&str>,
6821    exists: bool,
6822    unfinished: Option<&str>,
6823) -> Starter {
6824    if let Some(run) = previous
6825        && unfinished == Some(run.id.as_str())
6826        && run.reviewed_commits.is_some()
6827        && branch.is_some_and(|branch| {
6828            exists && run.candidates.len() == 1 && run.candidates[0].branch == branch
6829        })
6830        && may_resume_run(run, task)
6831    {
6832        return Starter::Resume(run.id.clone());
6833    }
6834    match (branch, unfinished, &task.review_of) {
6835        (None, None, Some(branch)) => Starter::Review(branch.clone()),
6836        _ => choose_starter(branch, exists, unfinished),
6837    }
6838}
6839
6840/// A retained review is valid only while its authored criteria still match.
6841fn review_branch_for<'a>(task: &'a Task, previous: Option<&RunState>) -> Option<&'a str> {
6842    task.review_branch
6843        .as_deref()
6844        .filter(|&branch| match &task.review_instruction {
6845            Some(authored) => *authored == task.instruction,
6846            // Legacy retained branches must agree with their prior run; only an
6847            // explicitly pinned review can proceed without recoverable provenance.
6848            None => previous.map_or_else(
6849                || task.review_of.as_deref() == Some(branch),
6850                |run| compatible_run_instruction(run, task),
6851            ),
6852        })
6853}
6854
6855/// A current explicit pin can select an otherwise incompatible run. Edits
6856/// and subsequent approvals invalidate pins selected for earlier criteria.
6857fn may_resume_run(run: &RunState, task: &Task) -> bool {
6858    if !task.assignment_accepts(run) {
6859        return false;
6860    }
6861    task.resume_override
6862        .as_ref()
6863        .is_some_and(|r| r.pinned_run.as_ref() == Some(&run.id))
6864        || compatible_run_instruction(run, task)
6865}
6866
6867/// Review scaffolding is execution context, not evidence of an operator edit.
6868pub(crate) fn compatible_run_instruction(run: &RunState, task: &Task) -> bool {
6869    if let Some(authored) = &run.task_instruction {
6870        return compatible_instruction(authored, task);
6871    }
6872    if compatible_instruction(&run.instruction, task) {
6873        return true;
6874    }
6875    // Recognize only the existing generated review shapes on legacy runs.
6876    // Ordinary authored text with a similar heading is left intact.
6877    if run.reviewed_commits.is_some() {
6878        if let Some((authored, _)) = run.instruction.split_once("\n\n# Work already on branch `") {
6879            return strip_answers_block(authored, task).trim() == task.instruction.trim();
6880        }
6881        if let Some(branch) = &task.review_of {
6882            let canonical = format!(
6883                "Review the branch `{branch}` (review-only: no implementation, no judging)."
6884            );
6885            let generated = format!(
6886                "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"
6887            );
6888            return task.instruction == canonical && run.instruction.starts_with(&generated);
6889        }
6890    }
6891    false
6892}
6893
6894/// Compare authored instructions, excluding answer blocks appended by the daemon.
6895pub(crate) fn compatible_instruction(old: &str, task: &Task) -> bool {
6896    strip_answers_block(old, task) == task.instruction
6897}
6898
6899/// Which repository a task runs in. A task that names none — the normal case
6900/// for one filed from a phone — runs in the daemon's own default.
6901fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
6902    if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
6903        return fallback.to_path_buf();
6904    }
6905    task.repo.clone()
6906}
6907
6908/// The header [`append_answers`] appends operator answers under. Shared with
6909/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
6910/// rather than grown a new block on every resume.
6911const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
6912
6913/// Render the first `count` answers in the block appended to an instruction.
6914fn answers_block(task: &Task, count: usize) -> String {
6915    let mut s = ANSWERS_HEADER.to_owned();
6916    for a in &task.answers[..count] {
6917        s.push_str(&format!("- {}: {}\n", a.question, a.answer));
6918    }
6919    s
6920}
6921
6922/// Render the approval independently of transient task state, so historical
6923/// suffixes remain recognizable after another explicit release.
6924fn resumption_block(r: &crate::queue::Resumption) -> String {
6925    format!(
6926        "\n\n# Explicit operator resumption\n\nGeneration {} at {} approved this instruction:\n{}\n\
6927         Earlier answers (first {}) are audit history; their waiting premises are superseded by this approval.\n",
6928        r.generation, r.at, r.instruction, r.answers_through,
6929    )
6930}
6931
6932/// Append audit answers and the latest explicit approval to the instruction.
6933fn append_answers(base: &str, task: &Task) -> String {
6934    let mut s = base.to_owned();
6935    if !task.answers.is_empty() {
6936        s.push_str(&answers_block(task, task.answers.len()));
6937    }
6938    if let Some(r) = &task.resumption {
6939        s.push_str(&resumption_block(r));
6940    }
6941    s
6942}
6943
6944/// Drop the prior answer block only when it is exactly the suffix this task
6945/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
6946/// the task author is ordinary instruction text, not a block to remove.
6947fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
6948    let mut instruction = instruction;
6949    for approval in task
6950        .resumption
6951        .iter()
6952        .chain(task.resumption_history.iter().rev())
6953    {
6954        if let Some(base) = instruction.strip_suffix(&resumption_block(approval)) {
6955            instruction = base;
6956            break;
6957        }
6958    }
6959    for count in (1..=task.answers.len()).rev() {
6960        let block = answers_block(task, count);
6961        if let Some(base) = instruction.strip_suffix(&block) {
6962            return base;
6963        }
6964    }
6965    instruction
6966}
6967
6968/// The instruction handed to `Runner::start`: the task's own text, plus any
6969/// operator answers `crate::conduct` collected for it (see
6970/// [`Task::answers`]), so a decision the operator actually made reaches the
6971/// implementers rather than only clearing the block that was waiting on it.
6972///
6973/// Appended rather than merged into [`Task::instruction`] itself, so the
6974/// task's own record stays exactly what its author wrote.
6975fn instruction_for(task: &Task) -> String {
6976    append_answers(&task.instruction, task)
6977}
6978
6979/// The instruction a resumed run should carry on with: whatever it already
6980/// had, refreshed with the task's *current* operator answers.
6981///
6982/// A resumable run's own `RunState::instruction` predates any answer
6983/// `crate::conduct` collects after the run parks, so resuming it unchanged —
6984/// the behaviour before this function existed — silently drops the very
6985/// decision the operator made to unblock it. Re-stripping any block this
6986/// function appended on an earlier resume before re-appending the current
6987/// list (rather than blindly appending again) is what keeps a task resumed
6988/// three times over three answered questions from carrying the same answer
6989/// three times.
6990fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
6991    append_answers(strip_answers_block(old_instruction, task), task)
6992}
6993
6994/// Preserve the producer's verified boundary and target, independent of prose.
6995fn record_config_failure(task: &mut Task, error: &anyhow::Error) {
6996    let failure = error.downcast_ref::<crate::config::ConfigFailure>();
6997    task.notice_cause(failure.map_or("config-load", |f| f.stage), None, None);
6998    if let Some(cause) = task.hold_notice_cause.as_mut() {
6999        cause.target = failure.map(|f| f.target.clone());
7000    }
7001}
7002
7003#[derive(Debug, thiserror::Error)]
7004#[error("attachment `{name}` is recorded on the task but {path} is missing")]
7005struct MissingAttachment {
7006    name: String,
7007    path: PathBuf,
7008}
7009
7010/// The task's attachments as absolute paths, each checked to still exist.
7011fn task_attachments(
7012    queue: &Queue,
7013    task: &Task,
7014) -> std::result::Result<Vec<PathBuf>, MissingAttachment> {
7015    let paths = queue.attachment_paths(task);
7016    for (name, path) in task.attachments.iter().zip(&paths) {
7017        if !path.is_file() {
7018            return Err(MissingAttachment {
7019                name: name.clone(),
7020                path: path.clone(),
7021            });
7022        }
7023    }
7024    Ok(paths)
7025}
7026
7027/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
7028/// answers before handing it to `Runner` — the actual boundary between
7029/// [`choose_starter`]'s routing and the graph, factored out so it is
7030/// assertable without a real repository, git branch, or agent CLI.
7031///
7032/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
7033/// instruction from the reviewed branch's own commit log because there is no
7034/// task statement to speak of for hand-written work, and splicing operator
7035/// answers into that text would contradict the very message it sends
7036/// reviewers ("there is no task statement").
7037fn prepare_instruction(
7038    starter: &Starter,
7039    old_instruction: Option<&str>,
7040    task: &Task,
7041) -> Option<String> {
7042    match starter {
7043        Starter::Start => Some(instruction_for(task)),
7044        Starter::Resume(_) => Some(resumed_instruction(
7045            old_instruction.expect("a resumed run always has a prior instruction"),
7046            task,
7047        )),
7048        Starter::Review(_) => None,
7049    }
7050}
7051
7052/// Persist a transition. A queue write failure is logged rather than fatal: the
7053/// run already happened, and taking the daemon down would only add a lost
7054/// backlog to a full disk.
7055fn record(queue: &Queue, task: &mut Task) {
7056    if let Err(e) = queue.put(task) {
7057        tracing::error!("could not record task {}: {e:#}", task.short());
7058        let notice = Notice::error(
7059            "loop:record",
7060            format!(
7061                "Task {} state could not be saved: {}. Check the disk.",
7062                task.id,
7063                e.to_string().lines().next().unwrap_or("unknown save error")
7064            ),
7065        )
7066        .link(Link::Task {
7067            id: task.id.clone(),
7068        });
7069        // The queue lives at `<home>/queue`, so its parent is the home.
7070        match queue.root().parent().filter(|p| !p.as_os_str().is_empty()) {
7071            Some(home) => notices::raise_in(home, notice),
7072            None => notices::raise(notice),
7073        }
7074    }
7075}
7076
7077/// Every runnable task, in the order the loop should try them.
7078///
7079/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
7080/// tail exists so that a claim somebody else holds costs the loop the next
7081/// candidate rather than a whole poll interval of idleness.
7082fn runnable(queue: &Queue) -> Vec<Task> {
7083    let mut tasks: Vec<Task> = queue
7084        .list()
7085        .into_iter()
7086        .filter(|t| t.status.runnable())
7087        .collect();
7088    tasks.sort_unstable_by(crate::queue::dispatch_order);
7089    tasks
7090}
7091
7092/// Why a run ended where it did, in one line, for [`Task::last_error`].
7093///
7094/// A stalled run names the seats the quota took out: "out of quota" is not
7095/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
7096/// agent to replace or which plan to top up.
7097///
7098/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
7099/// purpose: unlike `label`'s other callers (an internal log line, an
7100/// already-a-bug fallback message), this string becomes `Task::last_error`
7101/// verbatim, which the phone renders in the same alarm-styled box an
7102/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
7103/// `.err` styling. A bare `verified_noop` there would read exactly like the
7104/// failure this whole feature exists to tell apart from one.
7105fn describe(state: &RunState) -> String {
7106    let p = phrases(&state.config.graph.language);
7107    let mut detail = if state.status == RunStatus::Stalled {
7108        let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
7109        seats.sort_unstable();
7110        seats.dedup();
7111        if seats.is_empty() {
7112            p.quorum_lost.to_owned()
7113        } else {
7114            format!("{}{}{}", p.quorum_lost, p.quota_took_out, seats.join(", "))
7115        }
7116    } else {
7117        format!("{}{}", p.run_ended, state.status.display_label())
7118    };
7119    if let Some(cause) = state.verification_blocking_cause() {
7120        detail.push_str(&format!(" ({cause})"));
7121    } else if let Some(last) = state.events.last() {
7122        // The review loop's "never answered" stop is the one event worth
7123        // translating; it is recognised from structured state, not by
7124        // matching the English event text (which stays as recorded).
7125        let unanswered = state
7126            .reviews
7127            .last()
7128            .filter(|r| {
7129                state.status == RunStatus::Blocked
7130                    && last.node == "review"
7131                    && r.incomplete()
7132                    && r.blocking == 0
7133                    && r.round == state.config.graph.review_rounds
7134                    && r.e2e.iter().all(crate::run::CommandOutcome::ok)
7135            })
7136            .map(|r| (r.expected - r.answered, r.round));
7137        match unanswered {
7138            Some((missing, rounds)) if crate::lang::is_japanese(&state.config.graph.language) => {
7139                detail.push_str(&format!(
7140                    " ({}: {})",
7141                    last.node,
7142                    (p.reviewers_never_answered)(missing, rounds)
7143                ));
7144            }
7145            _ => detail.push_str(&format!(" ({}: {})", last.node, last.message)),
7146        }
7147    }
7148    detail.push_str(&format!(" [run {}]", state.id));
7149    detail
7150}
7151
7152/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
7153///
7154/// The task file lives in the backlog indefinitely; a diagnostic is an
7155/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
7156/// stay small regardless of how much a gate command or a candidate printed.
7157const DIAGNOSTIC_MAX: usize = 4_000;
7158
7159/// Tail kept from a single failing command's output inside a diagnostic.
7160/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
7161/// pointer for a human deciding whether to go read the full artifact by hand,
7162/// not a replacement for reading it.
7163const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
7164
7165/// Assemble a bounded diagnostic excerpt from a held task's own run, so
7166/// `magi task show` says more than the one-line reason in [`describe`].
7167///
7168/// The one-liner answers "where did the run stop"; this answers "what would a
7169/// human have found opening `artifacts/` by hand" — the point of the whole
7170/// feature is the case that one-liner actively misleads on: a run held as "no
7171/// candidate produced a change" can mean the implementer actually finished
7172/// the task (opened a PR, merged it, tagged a release) and only left a clean
7173/// local worktree behind, which reads as "nothing happened" unless someone
7174/// goes and reads what the agent actually said. `None` when the run carries
7175/// none of the three shapes this recognises — an ordinary run held for
7176/// something not diagnosable from `RunState` alone still explains itself
7177/// through `Task::last_error`.
7178pub(crate) fn diagnostic_for(state: &RunState) -> Option<String> {
7179    diagnostic(state)
7180}
7181
7182fn diagnostic(state: &RunState) -> Option<String> {
7183    let mut parts: Vec<String> = Vec::new();
7184
7185    if let Some(e2e) = &state.head_e2e
7186        && !e2e.passed
7187    {
7188        for o in e2e
7189            .outcomes
7190            .iter()
7191            .filter(|o| !o.ok() && !o.resource_blocked)
7192        {
7193            parts.push(format!(
7194                "head_e2e `{}` failed on {} ({}):\n{}",
7195                o.command,
7196                e2e.head.chars().take(7).collect::<String>(),
7197                notices::exit_status(o.code),
7198                crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7199            ));
7200        }
7201    }
7202
7203    // Gate failure: which check(s), and the tail of what each printed.
7204    for o in state.gate.iter().filter(|o| !o.ok()) {
7205        parts.push(format!(
7206            "gate `{}` failed ({}):\n{}",
7207            o.command,
7208            notices::exit_status(o.code),
7209            crate::run::summarize_verify(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
7210        ));
7211    }
7212
7213    // The land loop gave up because the fixer declined while checks were
7214    // still red: the message already names them (see `land::run`).
7215    if let Some(last) = state
7216        .events
7217        .iter()
7218        .rev()
7219        .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
7220    {
7221        parts.push(last.message.clone());
7222    }
7223
7224    // No viable candidate: every implementer's own final word, sanitized the
7225    // same way a judge would have read it, so a run that actually finished
7226    // the job does not read as an unexplained failure. A verified no-op is
7227    // called out ahead of its own summary and apart from an ordinary
7228    // failure's `why` — this is the one candidate shape whose diagnostic a
7229    // human is expected to actually judge, not just skim.
7230    if state.viable().is_empty() {
7231        for c in &state.candidates {
7232            if c.has_valid_verified_noop()
7233                && let Some(evidence) = c.verified_noop_display()
7234            {
7235                parts.push(format!(
7236                    "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
7237                    c.label
7238                ));
7239            } else if !c.summary.trim().is_empty() {
7240                if let Some(why) = &c.failed {
7241                    parts.push(format!(
7242                        "candidate {} ({why}): {}",
7243                        c.label,
7244                        c.summary.trim()
7245                    ));
7246                } else {
7247                    parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
7248                }
7249            } else if let Some(why) = &c.failed {
7250                parts.push(format!("candidate {}: {why}", c.label));
7251            }
7252        }
7253    }
7254
7255    if parts.is_empty() {
7256        return None;
7257    }
7258    // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
7259    // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
7260    // back slightly over. Leave it enough room to always land under the
7261    // limit.
7262    Some(crate::run::tail(
7263        &parts.join("\n\n"),
7264        DIAGNOSTIC_MAX.saturating_sub(100),
7265    ))
7266}
7267
7268/// Stable lower-case name for a run status, for an internal log line and the
7269/// "graph stopped without reaching a terminal status" bug message in
7270/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
7271/// doc for why that one reads [`RunStatus::display_label`] instead. One
7272/// definition of a status's name, on the type that owns it: this table used
7273/// to live here as a second copy, and a status renamed in one place would
7274/// have gone on reading correctly in the other.
7275fn label(status: RunStatus) -> &'static str {
7276    status.as_str()
7277}
7278
7279/// Parse a merge mode override.
7280pub(crate) fn merge_mode(mode: &str) -> Result<MergeMode> {
7281    match mode {
7282        "none" => Ok(MergeMode::None),
7283        "local" => Ok(MergeMode::Local),
7284        "pr" => Ok(MergeMode::Pr),
7285        other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
7286    }
7287}
7288
7289/// Take the status lock, recovering from a poisoned one.
7290///
7291/// A panic elsewhere must not silently stop the heartbeat: the status is plain
7292/// data, and the worst a poisoned lock can hold is a stale timestamp.
7293fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
7294    mutex
7295        .lock()
7296        .unwrap_or_else(std::sync::PoisonError::into_inner)
7297}
7298
7299#[cfg(test)]
7300mod tests {
7301    use super::*;
7302    use crate::queue::{Source, TaskStatus};
7303    use crate::run::{Candidate, CommandOutcome};
7304    use pretty_assertions::assert_eq;
7305
7306    fn task() -> Task {
7307        Task::new(
7308            "add retries".to_owned(),
7309            "add retries".to_owned(),
7310            PathBuf::from("/repo"),
7311            Source::Human,
7312        )
7313    }
7314
7315    #[test]
7316    fn dispatch_wait_aggregates_unique_skips_in_stable_count_order() {
7317        let skips = DispatchSkips::from([
7318            ("a".into(), SkipReason::CoolingDown),
7319            ("b".into(), SkipReason::WaitingOnLanding),
7320            ("c".into(), SkipReason::WaitingOnLanding),
7321            ("d".into(), SkipReason::OrdinaryCapacity),
7322        ]);
7323        let wait = aggregate_dispatch_wait(4, &skips).unwrap();
7324        assert_eq!(wait.runnable, 4);
7325        assert_eq!(
7326            wait.reasons
7327                .iter()
7328                .map(|r| (r.reason.as_str(), r.count))
7329                .collect::<Vec<_>>(),
7330            [
7331                ("waiting_on_landing", 2),
7332                ("cooling_down", 1),
7333                ("ordinary_capacity", 1)
7334            ]
7335        );
7336        assert_eq!(aggregate_dispatch_wait(0, &DispatchSkips::new()), None);
7337        assert!(
7338            aggregate_dispatch_wait(2, &DispatchSkips::new())
7339                .unwrap()
7340                .reasons
7341                .is_empty()
7342        );
7343    }
7344
7345    #[test]
7346    fn dispatch_wait_tracks_interrupt_withholding_and_set_changes() {
7347        let before = vec!["a".into(), "b".into(), "c".into()];
7348        let allowed = vec![task_with_id("b")];
7349        let skips = interrupt_skips(&before, &allowed);
7350        assert_eq!(
7351            skips,
7352            DispatchSkips::from([
7353                ("a".into(), SkipReason::InterruptGate),
7354                ("c".into(), SkipReason::InterruptGate),
7355            ])
7356        );
7357        let mut previous = DispatchSkips::new();
7358        assert!(!changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7359        assert!(changed_dispatch_skips(&mut previous, skips.clone()));
7360        assert!(!changed_dispatch_skips(&mut previous, skips));
7361        assert!(changed_dispatch_skips(
7362            &mut previous,
7363            DispatchSkips::from([("a".into(), SkipReason::CoolingDown),])
7364        ));
7365        assert!(changed_dispatch_skips(&mut previous, DispatchSkips::new()));
7366    }
7367
7368    #[test]
7369    fn dispatch_wait_status_reads_legacy_and_future_reason_keys() {
7370        let mut value = serde_json::to_value(Status::new()).unwrap();
7371        value.as_object_mut().unwrap().remove("dispatch_wait");
7372        assert!(
7373            serde_json::from_value::<Status>(value.clone())
7374                .unwrap()
7375                .dispatch_wait
7376                .is_none()
7377        );
7378        assert!(
7379            serde_json::from_value::<Reading>(value.clone())
7380                .unwrap()
7381                .dispatch_wait
7382                .is_none()
7383        );
7384        value["dispatch_wait"] = serde_json::json!({
7385            "runnable": 3, "reasons": [{"reason": "future_reason", "count": 3}]
7386        });
7387        let reading = serde_json::from_value::<Reading>(value).unwrap();
7388        assert_eq!(
7389            reading.dispatch_wait.unwrap().reasons[0].reason,
7390            "future_reason"
7391        );
7392    }
7393
7394    fn starting_task_reservation(home: &Path, request: &TaskWorker) -> crate::worker::Job {
7395        let job = crate::worker::Job {
7396            id: "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa".into(),
7397            sequence: 1,
7398            kind: "task".into(),
7399            key: format!("task:{}", request.task),
7400            payload: serde_json::to_value(request).unwrap(),
7401            generation: "a".repeat(64),
7402            version: None,
7403            status: crate::worker::Status::Starting,
7404            result: None,
7405            pid: None,
7406            created_at: u64::try_from(Timestamp::now().as_second()).unwrap(),
7407            finished_at: None,
7408        };
7409        let dir = home.join("workers/jobs").join(&job.id);
7410        std::fs::create_dir_all(&dir).unwrap();
7411        std::fs::write(dir.join("job.json"), serde_json::to_vec(&job).unwrap()).unwrap();
7412        job
7413    }
7414
7415    #[test]
7416    fn an_unacknowledged_own_reservation_stops_dispatch_without_cancelling_the_child() {
7417        let home = tempfile::tempdir().unwrap();
7418        let request = TaskWorker {
7419            opts: Opts::default(),
7420            queue: home.path().join("queue"),
7421            task: "startup".into(),
7422            lane: PermitKind::Ordinary,
7423            standalone: false,
7424        };
7425        let job = starting_task_reservation(home.path(), &request);
7426        let error = task_worker_spawn_error(
7427            home.path(),
7428            &request,
7429            anyhow::anyhow!("worker startup is unacknowledged: private-error-detail"),
7430        )
7431        .expect_err("our own reservation must not turn a failed spawn into a resync");
7432        let active = crate::worker::active(home.path()).unwrap();
7433        assert_eq!(active.len(), 1);
7434        assert_eq!(active[0].id, job.id);
7435        assert_eq!(active[0].status, crate::worker::Status::Starting);
7436        assert!(
7437            crate::worker::control(home.path(), &job.key)
7438                .unwrap()
7439                .is_none()
7440        );
7441        let notices = notices::Notices::at(home.path().join("notifications")).list();
7442        assert_eq!(notices.len(), 1);
7443        assert_eq!(notices[0].key, "loop:worker-startup");
7444        assert!(!notices[0].message.contains("private-error-detail"));
7445        assert!(notices[0].message.contains(&request.task));
7446        assert!(
7447            notices[0]
7448                .message
7449                .contains("could not be started or acknowledged")
7450        );
7451        assert!(notices[0].message.contains("worker.log"));
7452        assert_eq!(
7453            notices[0].link,
7454            Some(Link::Task {
7455                id: request.task.clone()
7456            })
7457        );
7458        assert!(format!("{error:#}").contains("private-error-detail"));
7459    }
7460
7461    #[test]
7462    fn a_standalone_handoff_reservation_resyncs_dispatch_without_replacing_it() {
7463        let home = tempfile::tempdir().unwrap();
7464        let mut request = TaskWorker {
7465            opts: Opts::default(),
7466            queue: home.path().join("queue"),
7467            task: "handoff".into(),
7468            lane: PermitKind::Ordinary,
7469            standalone: true,
7470        };
7471        let job = starting_task_reservation(home.path(), &request);
7472        request.standalone = false;
7473        task_worker_spawn_error(
7474            home.path(),
7475            &request,
7476            anyhow::anyhow!("operation key is already reserved for a different request"),
7477        )
7478        .expect("a different standalone request is the handoff race, not our startup failure");
7479        let active = crate::worker::active(home.path()).unwrap();
7480        assert_eq!(active.len(), 1);
7481        assert_eq!(active[0].id, job.id);
7482        assert_eq!(active[0].payload, job.payload);
7483        assert!(
7484            notices::Notices::at(home.path().join("notifications"))
7485                .list()
7486                .is_empty()
7487        );
7488    }
7489
7490    #[test]
7491    fn starting_worker_projects_the_previous_run_without_owning_its_execution() {
7492        let home = tempfile::tempdir().unwrap();
7493        let queue = Queue::at(home.path().join("queue"));
7494        let mut task = task();
7495        task.runs = vec!["previous".into()];
7496        queue.put(&mut task).unwrap();
7497        let request = TaskWorker {
7498            opts: Opts::default(),
7499            queue: home.path().join("queue"),
7500            task: task.id.clone(),
7501            lane: PermitKind::Ordinary,
7502            standalone: false,
7503        };
7504        let job = starting_task_reservation(home.path(), &request);
7505        let claims = current_work(home.path(), Timestamp::now());
7506        assert_eq!(claims.len(), 1);
7507        assert_eq!(claims[0].worker.as_deref(), Some(job.id.as_str()));
7508        assert_eq!(claims[0].run, "previous");
7509        assert!(other_claims_run(&claims, "previous", None));
7510        // Only after confirming the executing caller may admission ignore
7511        // this exact projection. Cleanup continues to observe it as live.
7512        assert!(!other_claims_run(&claims, "previous", Some(&job.id)));
7513        assert!(is_working_on(home.path(), "previous", Timestamp::now()));
7514    }
7515
7516    #[test]
7517    fn admission_excludes_only_the_callers_exact_reservation() {
7518        let own = Current {
7519            worker: Some("own".into()),
7520            task: "same-task".into(),
7521            run: "previous".into(),
7522        };
7523        assert!(!other_claims_run(
7524            std::slice::from_ref(&own),
7525            "previous",
7526            Some("own")
7527        ));
7528        assert!(other_claims_run(
7529            std::slice::from_ref(&own),
7530            "previous",
7531            None
7532        ));
7533        for worker in [None, Some("other".into())] {
7534            let other = Current {
7535                worker,
7536                ..own.clone()
7537            };
7538            assert!(other_claims_run(
7539                &[own.clone(), other],
7540                "previous",
7541                Some("own")
7542            ));
7543        }
7544        let legacy: Current =
7545            serde_json::from_str(r#"{"task":"same-task","run":"previous"}"#).unwrap();
7546        assert!(other_claims_run(&[legacy], "previous", Some("own")));
7547    }
7548
7549    #[test]
7550    fn os_leased_task_worker_survives_wall_clock_advance() {
7551        let home = tempfile::tempdir().unwrap();
7552        let queue = Queue::at(home.path().join("queue"));
7553        let mut task = task();
7554        let run = "20260903-100000-abcd";
7555        task.start(run.into());
7556        queue.put(&mut task).unwrap();
7557        let mut worker = live_task_fixture(home.path(), &task.id).unwrap();
7558        let future = Timestamp::now() + jiff::SignedDuration::from_secs(3600);
7559        assert!(
7560            current_work(home.path(), future)
7561                .iter()
7562                .any(
7563                    |claim| claim.worker.as_deref() == Some(worker.job.id.as_str())
7564                        && claim.run == run
7565                )
7566        );
7567        worker.release_lease();
7568        assert!(worker.dir.join("job.json").is_file());
7569        assert!(!is_working_on(home.path(), run, future));
7570        let dir = worker.dir.clone();
7571        drop(worker);
7572        assert!(!dir.exists());
7573    }
7574
7575    #[test]
7576    fn review_retry_resumes_only_the_matching_authorized_latest_owner() {
7577        let mut task = task();
7578        let mut run = run_state(RunStatus::Reviewing);
7579        run.task_instruction = Some(task.instruction.clone());
7580        run.reviewed_commits = Some(vec!["committed-fix".into()]);
7581        let branch = "magi/test/B";
7582        run.candidates.push(crate::run::Candidate {
7583            branch: branch.into(),
7584            ..candidate('B', "preserved work", false, None)
7585        });
7586        task.runs = vec![run.id.clone()];
7587        let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(run.clone()));
7588        assert_eq!(
7589            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7590            Starter::Resume(run.id.clone())
7591        );
7592        assert!(matches!(
7593            review_retry_starter(
7594                &task,
7595                Some(&run),
7596                Some("different"),
7597                true,
7598                unfinished.as_deref()
7599            ),
7600            Starter::Review(_)
7601        ));
7602        assert_eq!(
7603            review_retry_starter(
7604                &task,
7605                Some(&run),
7606                Some(branch),
7607                false,
7608                unfinished.as_deref()
7609            ),
7610            Starter::Start
7611        );
7612        task.instruction.push_str(" changed criteria");
7613        assert!(matches!(
7614            review_retry_starter(&task, Some(&run), Some(branch), true, unfinished.as_deref()),
7615            Starter::Review(_)
7616        ));
7617        assert!(matches!(
7618            review_retry_starter(&task, Some(&run), Some(branch), true, None),
7619            Starter::Review(_)
7620        ));
7621    }
7622
7623    #[test]
7624    fn a_live_worker_reservation_prevents_reclaim_before_its_task_claim() {
7625        let dir = tempfile::tempdir().unwrap();
7626        let queue = Queue::at(dir.path().join("queue"));
7627        let mut task = task();
7628        task.status = TaskStatus::Running;
7629        task.attempts = 1;
7630        queue.put(&mut task).unwrap();
7631        let live = std::collections::BTreeSet::from([task.id.clone()]);
7632        assert!(reclaim_orphaned_running(&queue, 2, &live).is_empty());
7633        drop(queue.claim(&task.id).unwrap());
7634        let saved = queue.get(&task.id).unwrap();
7635        assert_eq!(saved.status, TaskStatus::Running);
7636        assert_eq!(saved.attempts, 1);
7637        assert!(saved.last_error.is_none());
7638    }
7639
7640    #[test]
7641    fn standalone_workers_do_not_consume_scheduler_lanes() {
7642        let request = |task: &str, lane, standalone| TaskWorker {
7643            opts: Opts::default(),
7644            queue: PathBuf::from("/queue"),
7645            task: task.to_owned(),
7646            lane,
7647            standalone,
7648        };
7649        let mut jobs = vec![
7650            request("ordinary", PermitKind::Ordinary, false),
7651            request("standalone-urgent", PermitKind::Urgent, true),
7652            request("standalone-ordinary", PermitKind::Ordinary, true),
7653            request("decision", PermitKind::None, false),
7654        ];
7655        assert_eq!(available_slots(&jobs, 2), (1, 1));
7656        jobs.push(request("urgent", PermitKind::Urgent, false));
7657        assert_eq!(available_slots(&jobs, 2), (1, 0));
7658        assert_eq!(available_slots(&jobs, 0), (0, 0));
7659    }
7660
7661    #[test]
7662    fn a_live_legacy_scheduler_blocks_migration_even_with_a_stale_heartbeat() {
7663        let now = Timestamp::now();
7664        let mut reading = Reading {
7665            pid: Some(std::process::id()),
7666            updated_at: Some(now - jiff::SignedDuration::from_secs(STALE_SECS + 1)),
7667            ..Reading::default()
7668        };
7669        assert!(!reading.running(now));
7670        assert!(legacy_scheduler_running(&reading, now, 0));
7671        reading.worker_protocol = Some(1);
7672        assert!(!legacy_scheduler_running(&reading, now, 0));
7673    }
7674
7675    #[test]
7676    fn selected_public_head_overrides_historical_resume_and_pin() {
7677        let mut t = task();
7678        let mut old = run_state(RunStatus::Blocked);
7679        let selection = crate::pr_recovery::Selection {
7680            url: "url".into(),
7681            branch: format!("magi/task-{}", t.id),
7682            head: "a".repeat(40),
7683            source_head: None,
7684            source_run: None,
7685            source_proof: None,
7686            disposition: Some(crate::pr_recovery::Disposition::Review),
7687            instruction: t.instruction.clone(),
7688            approved_at: Timestamp::now(),
7689        };
7690        t.resume_override = Some(crate::queue::OperatorResume {
7691            pinned_run: Some(old.id.clone()),
7692            question_id: "choice".into(),
7693            at: Timestamp::now(),
7694            conductor_rehold: None,
7695            forced: false,
7696        });
7697        assert_eq!(
7698            selected_starter(&selection, Some(&old), Some(&old.id)),
7699            Starter::Review(selection.branch.clone())
7700        );
7701        old.pr_recovery = Some(selection.clone());
7702        assert_eq!(
7703            selected_starter(&selection, Some(&old), Some(&old.id)),
7704            Starter::Review(selection.branch.clone())
7705        );
7706        old.reviewed_commits = Some(vec!["implementation".into()]);
7707        assert_eq!(
7708            selected_starter(&selection, Some(&old), Some(&old.id)),
7709            Starter::Resume(old.id.clone())
7710        );
7711        let mut changed = selection.clone();
7712        changed.head = "b".repeat(40);
7713        assert_eq!(
7714            selected_starter(&changed, Some(&old), Some(&old.id)),
7715            Starter::Review(changed.branch)
7716        );
7717    }
7718
7719    #[test]
7720    fn candidate_transplant_failure_is_one_actionable_hold() {
7721        let dir = tempfile::tempdir().unwrap();
7722        let q = Queue::at(dir.path().join("queue"));
7723        let mut t = task();
7724        let mut state = run_state(RunStatus::Blocked);
7725        state.event("prep", "cannot apply referenced commit: conflict");
7726        state.prep_failure = Some("conflict".into());
7727        t.start(state.id.clone());
7728        finish_attempt(3, &q, &mut t, &state, &[], Err(anyhow::anyhow!("conflict")));
7729        assert_eq!(t.attempts, 1);
7730        assert_eq!(t.status, TaskStatus::Held);
7731        assert!(t.operator_held());
7732        assert!(!t.status.runnable());
7733        assert!(t.hold_reason.as_deref().unwrap().contains("recover-pr"));
7734        let first = t.chat_notice_key().unwrap();
7735        t.chat_notices.push(first.clone());
7736        t.release_operator("test", None);
7737        state.id = "another-unprepared-run".into();
7738        t.start(state.id.clone());
7739        finish_attempt(
7740            3,
7741            &q,
7742            &mut t,
7743            &state,
7744            &[],
7745            Err(anyhow::anyhow!("still conflicts")),
7746        );
7747        assert_eq!(
7748            t.chat_notice_key().as_ref(),
7749            Some(&first),
7750            "no work happened"
7751        );
7752        t.release_operator("test", None);
7753        state.prep_failure = None;
7754        state.status = RunStatus::Failed;
7755        state.begin_pass();
7756        t.start(state.id.clone());
7757        finish_attempt(
7758            1,
7759            &q,
7760            &mut t,
7761            &state,
7762            &[],
7763            Err(anyhow::anyhow!("new gate failure")),
7764        );
7765        let failure = t.chat_notice_key().unwrap();
7766        assert_ne!(failure, first, "approved recovery reached a real failure");
7767        t.release_operator("test", None);
7768        state.begin_pass();
7769        t.start(state.id.clone());
7770        finish_attempt(
7771            1,
7772            &q,
7773            &mut t,
7774            &state,
7775            &[],
7776            Err(anyhow::anyhow!("new failure on resume")),
7777        );
7778        assert_ne!(
7779            t.chat_notice_key().as_ref(),
7780            Some(&failure),
7781            "a new settled pass"
7782        );
7783    }
7784
7785    #[test]
7786    fn revised_resumption_invalidates_old_pins_and_preserves_unchanged_pins() {
7787        for source in ["cli", "web"] {
7788            let mut t = task();
7789            let mut run = run_state(RunStatus::Blocked);
7790            run.instruction = "Run A original criteria".into();
7791            run.task_instruction = Some(run.instruction.clone());
7792            t.start(run.id.clone());
7793            t.release_operator("choice", Some("resume-question"));
7794            t.resume_override = Some(crate::queue::OperatorResume {
7795                question_id: "resume-question".into(),
7796                at: Timestamp::now(),
7797                conductor_rehold: None,
7798                forced: true,
7799                pinned_run: Some(run.id.clone()),
7800            });
7801            t.hold_machine(Some("not enough free space to start a run".into()));
7802            let mut unchanged = t.clone();
7803            unchanged
7804                .edit("title changed".into(), unchanged.instruction.clone())
7805                .unwrap();
7806            unchanged.release_operator(source, None);
7807            assert_eq!(
7808                unchanged
7809                    .resume_override
7810                    .as_ref()
7811                    .unwrap()
7812                    .pinned_run
7813                    .as_deref(),
7814                Some(run.id.as_str())
7815            );
7816            assert!(!compatible_run_instruction(&run, &unchanged));
7817            assert!(may_resume_run(&run, &unchanged));
7818
7819            t.edit(
7820                "approved recovery".into(),
7821                "Reuse measured PR head B; fix Clippy; review".into(),
7822            )
7823            .unwrap();
7824            assert!(t.resume_override.is_none());
7825            t.release_operator(source, None);
7826            let reloaded: Task = serde_json::from_str(&serde_json::to_string(&t).unwrap()).unwrap();
7827            assert!(reloaded.resume_override.is_none());
7828            assert!(!may_resume_run(&run, &reloaded));
7829            let unfinished =
7830                unfinished_run_with(&reloaded.runs, reloaded.short(), |_| Ok(run.clone()))
7831                    .filter(|_| may_resume_run(&run, &reloaded));
7832            assert_eq!(
7833                choose_starter(None, false, unfinished.as_deref()),
7834                Starter::Start
7835            );
7836            assert!(instruction_for(&reloaded).starts_with("Reuse measured PR head B"));
7837            assert_eq!(
7838                reloaded.resumption_history[0].question_id.as_deref(),
7839                Some("resume-question")
7840            );
7841
7842            // A revision already persisted with the old approval/pin is also
7843            // invalidated when the new operator release is recorded.
7844            unchanged.instruction = "Reuse measured PR head B".into();
7845            unchanged.hold_machine(Some("disk hold".into()));
7846            unchanged.release_operator(source, None);
7847            assert!(unchanged.resume_override.is_none());
7848            assert!(!may_resume_run(&run, &unchanged));
7849        }
7850    }
7851
7852    #[test]
7853    fn resumption_preserves_generated_review_runs_and_rejects_revised_targets() {
7854        let mut t = task();
7855        let mut run = run_state(RunStatus::Blocked);
7856        t.review_of = Some("approved-head".into());
7857        t.instruction =
7858            "Review the branch `approved-head` (review-only: no implementation, no judging)."
7859                .into();
7860        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();
7861        run.reviewed_commits = Some(vec!["Commit log".into()]);
7862        t.start(run.id.clone());
7863        t.hold_machine(Some("interrupted review".into()));
7864        t.release_operator("cli", None);
7865        assert!(
7866            compatible_run_instruction(&run, &t),
7867            "legacy explicit review remains resumable"
7868        );
7869        let unfinished = unfinished_run_with(&t.runs, t.short(), |_| Ok(run.clone()))
7870            .filter(|_| compatible_run_instruction(&run, &t));
7871        assert_eq!(
7872            choose_starter(None, false, unfinished.as_deref()),
7873            Starter::Resume(run.id.clone())
7874        );
7875        run.task_instruction = Some(t.instruction.clone());
7876        assert!(compatible_run_instruction(&run, &t));
7877        let reloaded: RunState =
7878            serde_json::from_str(&serde_json::to_string(&run).unwrap()).unwrap();
7879        assert!(compatible_run_instruction(&reloaded, &t));
7880        t.edit(
7881            "new approved head".into(),
7882            "Reuse measured PR head B".into(),
7883        )
7884        .unwrap();
7885        assert!(!compatible_run_instruction(&run, &t));
7886
7887        // Legacy recovery reviews retain the task criteria ahead of the log.
7888        t.review_of = None;
7889        t.instruction = "Fix Clippy on approved head".into();
7890        run.task_instruction = None;
7891        run.instruction = format!(
7892            "{}\n\n# Work already on branch `approved-head` (commit subjects)\n\nCommit log",
7893            t.instruction
7894        );
7895        assert!(compatible_run_instruction(&run, &t));
7896        t.instruction.push('\n');
7897        assert!(
7898            compatible_run_instruction(&run, &t),
7899            "legacy generated review trimmed the original criteria"
7900        );
7901        t.hold_for_handover(Some("approved-head".into()), "refused".into());
7902        assert_eq!(review_branch_for(&t, Some(&run)), Some("approved-head"));
7903        t.edit("new plan".into(), "Reuse measured PR head B".into())
7904            .unwrap();
7905        assert!(review_branch_for(&t, Some(&run)).is_none());
7906        assert!(!compatible_run_instruction(&run, &t));
7907        t.review_branch = Some("approved-head".into());
7908        t.review_instruction = None;
7909        assert!(
7910            review_branch_for(&t, Some(&run)).is_none(),
7911            "legacy retained candidate cannot replace a revised approved head"
7912        );
7913    }
7914
7915    #[test]
7916    fn resumption_actions_survive_automatic_holds_of_hand_started_runs() {
7917        let home = crate::run::test_home();
7918        crate::run::pin_test_home();
7919        let dir = tempfile::tempdir().unwrap();
7920        let queue = Queue::at(dir.path().join("queue"));
7921        for resume in [true, false] {
7922            let state = run_state(RunStatus::Blocked);
7923            let mut t = task();
7924            t.start(state.id.clone());
7925            let action = if resume {
7926                ask::ChoiceAction::Resume {
7927                    run: state.id.clone(),
7928                }
7929            } else {
7930                ask::ChoiceAction::Requeue
7931            };
7932            let mut q = action_question(&state.id, action);
7933            q.status = ask::QuestionStatus::Open;
7934            q.answer = None;
7935            q.answered_at = None;
7936            t.fail("run stopped with a question", 3);
7937            hold_if_runnable(&queue, &mut t);
7938            assert!(t.operator_decided_at.is_none());
7939            assert!(t.operator_held());
7940            q.answer(ask::Answer::Choice(q.choices[0].clone())).unwrap();
7941            let expected = if resume {
7942                ActionDecision::Resume(state.id.clone())
7943            } else {
7944                ActionDecision::Requeue
7945            };
7946            assert_eq!(
7947                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7948                expected
7949            );
7950            t.hold_manual(Some("later explicit hold".into()));
7951            assert_eq!(
7952                decide_action(&home, &t, &q, phrases("en"), |_| Ok(state.clone())),
7953                ActionDecision::Stale
7954            );
7955        }
7956    }
7957
7958    #[test]
7959    fn explicit_resumption_keeps_revised_instruction_and_audit_answers() {
7960        let mut t = task();
7961        t.answers.push(crate::queue::AnsweredQuestion {
7962            question: "Inspect the remote?".into(),
7963            answer: "Inspect then wait".into(),
7964        });
7965        let old = instruction_for(&t);
7966        assert!(compatible_instruction(&old, &t));
7967        t.instruction = "Reuse approved PR head and review".into();
7968        t.release_operator("cli", None);
7969        assert!(!compatible_instruction(&old, &t));
7970        let approved = instruction_for(&t);
7971        assert!(approved.contains("waiting premises are superseded"));
7972        assert!(compatible_instruction(&approved, &t));
7973        assert_eq!(resumed_instruction(&approved, &t), approved);
7974        t.release_operator("web", None);
7975        assert!(compatible_instruction(&approved, &t));
7976        assert_eq!(t.resumption_history.len(), 1);
7977        t.start("run".into());
7978        assert!(instruction_for(&t).contains("Explicit operator resumption"));
7979    }
7980
7981    /// A run that stopped on an infrastructure wait asked no agent anything:
7982    /// the task is held by the machine under a `[resource]` reason (resumable,
7983    /// re-checked by triage), and the attempt it started is given back.
7984    #[test]
7985    fn unrelated_ci_refunds_once_per_pass_and_holds_for_the_owner() {
7986        let mut state = RunState::new(
7987            PathBuf::from("/repo"),
7988            "main".into(),
7989            "base".into(),
7990            "task".into(),
7991            Config::default(),
7992        );
7993        state.status = RunStatus::Landing;
7994        state.parked = true;
7995        state.pr_pushed_head = Some("head".into());
7996        state.land_unrelated = Some(
7997            serde_json::from_value(serde_json::json!({
7998                "head": "head", "question": "ci-question",
7999                "evidence": {"head": "head", "base": "base", "changed": [], "checks": []}
8000            }))
8001            .unwrap(),
8002        );
8003        let mut t = task();
8004        t.start(state.id.clone());
8005        let verdict = Verdict {
8006            status: RunStatus::Landing,
8007            left_pr: true,
8008            quota_hit: false,
8009            parked: true,
8010            no_viable_candidates: false,
8011        };
8012        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8013        assert_eq!(t.attempts, 0);
8014        assert_eq!(t.status, TaskStatus::Held);
8015        assert!(!t.operator_held());
8016        assert!(
8017            t.hold_reason
8018                .as_deref()
8019                .unwrap()
8020                .starts_with("[ci-unrelated]")
8021        );
8022        // A second settlement must not refund an earlier task attempt.
8023        t.attempts = 1;
8024        settle_and_diagnose(&mut t, verdict, "CI hold", 2, &state);
8025        assert_eq!(t.attempts, 1);
8026        assert_eq!(t.passes.len(), 1);
8027        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
8028        state.pr_pushed_head = Some("new-head".into());
8029        state.parked = false;
8030        state.status = RunStatus::Blocked;
8031        let stale = Verdict {
8032            status: RunStatus::Blocked,
8033            parked: false,
8034            ..verdict
8035        };
8036        settle_and_diagnose(&mut t, stale, "stale CI hold", 2, &state);
8037        assert_eq!(t.attempts, 1);
8038        // A new execution pass can refund its own newly charged attempt.
8039        state.begin_pass();
8040        state.begin_pass();
8041        state.status = RunStatus::Landing;
8042        state.parked = true;
8043        state.pr_pushed_head = Some("head".into());
8044        settle_and_diagnose(&mut t, verdict, "CI hold on resume", 2, &state);
8045        assert_eq!(t.attempts, 0);
8046        assert_eq!(t.passes.len(), 2);
8047    }
8048
8049    #[test]
8050    fn orphan_recovery_does_not_refund_a_previous_pass_loss() {
8051        let mut state = run_state(RunStatus::Failed);
8052        state
8053            .quota
8054            .push(loss("advisor-1", "2026-10-22T14:38:00Z", None));
8055        state.begin_pass();
8056        let mut t = task();
8057        t.start(state.id.clone());
8058        reclaim(&mut t, Some(state), 2, "en");
8059        assert_eq!(t.attempts, 1);
8060    }
8061
8062    #[test]
8063    fn an_all_seats_unauthenticated_node_refunds_and_holds_without_retry() {
8064        let mut state = run_state(RunStatus::Blocked);
8065        let losses: Vec<_> = ["alpha", "beta"]
8066            .into_iter()
8067            .enumerate()
8068            .map(|(i, agent)| {
8069                QuotaLoss::from_report(
8070                    format!("advisor-{i}"),
8071                    "advise",
8072                    Some(&crate::agent::Quota {
8073                        cause: crate::agent::QuotaCause::Authentication,
8074                        agent: agent.to_owned(),
8075                        reset: None,
8076                    }),
8077                )
8078            })
8079            .collect();
8080        crate::graph::block_machine_outage(&mut state, "advise", &losses);
8081        state.quota = losses;
8082        let mut t = task();
8083        t.start(state.id.clone());
8084        let verdict = Verdict {
8085            status: state.status,
8086            left_pr: false,
8087            quota_hit: true,
8088            parked: false,
8089            no_viable_candidates: true,
8090        };
8091        settle_and_diagnose(&mut t, verdict, "authentication unavailable", 2, &state);
8092        assert_eq!(t.attempts, 0);
8093        assert_eq!(t.status, TaskStatus::Held);
8094        assert!(!t.operator_held());
8095        let reason = t.hold_reason.as_deref().unwrap();
8096        assert!(reason.starts_with("[authentication]"));
8097        assert!(
8098            reason.contains("alpha")
8099                && reason.contains("beta")
8100                && reason.contains("re-authenticate")
8101        );
8102        assert!(cooldown_until(&state.quota, Timestamp::now()).is_none());
8103        // Orphan recovery uses the same settlement and cannot spend an attempt.
8104        let mut orphan = task();
8105        orphan.start(state.id.clone());
8106        reclaim(&mut orphan, Some(state), 2, "en");
8107        assert_eq!(orphan.attempts, 0);
8108        assert_eq!(orphan.status, TaskStatus::Held);
8109    }
8110
8111    #[test]
8112    fn a_resource_blocked_run_holds_its_task_and_spends_no_attempt() {
8113        let mut state = RunState::new(
8114            PathBuf::from("/repo"),
8115            "main".to_owned(),
8116            "abc1234".to_owned(),
8117            "task".to_owned(),
8118            Config::default(),
8119        );
8120        state.status = RunStatus::Blocked;
8121        state.resource_block = Some(crate::run::ResourceBlock {
8122            cause: crate::run::ResourceBlockCause::Other,
8123            node: "graft".to_owned(),
8124            kind: "shared build cache".to_owned(),
8125            detail: "timed out".to_owned(),
8126            at: jiff::Timestamp::now(),
8127        });
8128        let mut t = task();
8129        t.start("20260902-000000-aaaa".to_owned());
8130        assert_eq!(t.attempts, 1);
8131        let verdict = Verdict {
8132            status: RunStatus::Blocked,
8133            left_pr: false,
8134            quota_hit: false,
8135            parked: false,
8136            no_viable_candidates: false,
8137        };
8138        settle_and_diagnose(&mut t, verdict, "blocked", 2, &state);
8139        assert_eq!(t.status, TaskStatus::Held);
8140        assert_eq!(t.attempts, 0, "the attempt is refunded");
8141        assert!(t.hold_reason.as_deref().unwrap().starts_with("[resource] "));
8142        assert!(
8143            !t.operator_held(),
8144            "a machine hold, released without a human"
8145        );
8146
8147        let mut selected = task();
8148        selected.start("20260902-000000-cccc".into());
8149        selected.replacement = Some(crate::merge_decision::Replacement {
8150            question: "fixture".into(),
8151            run: "earlier".into(),
8152            pr: "https://example.invalid/pr/1".into(),
8153            agent: "selected".into(),
8154            context: "fixture".into(),
8155        });
8156        state.resource_block.as_mut().unwrap().kind = "repository coordination".into();
8157        settle_and_diagnose(&mut selected, verdict, "blocked", 2, &state);
8158        assert_eq!(selected.attempts, 0);
8159        assert!(
8160            !selected.operator_held(),
8161            "a selected agent also retains a machine resource hold"
8162        );
8163        assert!(
8164            selected
8165                .hold_reason
8166                .as_deref()
8167                .unwrap()
8168                .starts_with("[resource] ")
8169        );
8170
8171        // A park request outranks it: still the operator's doing.
8172        let mut p = task();
8173        p.start("20260902-000000-bbbb".to_owned());
8174        settle_and_diagnose(
8175            &mut p,
8176            Verdict {
8177                parked: true,
8178                ..verdict
8179            },
8180            "parked",
8181            2,
8182            &state,
8183        );
8184        assert_eq!(p.status, TaskStatus::Parked);
8185        assert_eq!(
8186            p.attempts, 0,
8187            "parking refunds once rather than also settling the resource hold"
8188        );
8189    }
8190
8191    #[test]
8192    fn record_failure_notice_links_the_task() {
8193        let dir = tempfile::tempdir().unwrap();
8194        // A regular file where the queue directory should be makes every
8195        // `put` fail, on every platform and whoever runs the test.
8196        std::fs::write(dir.path().join("queue"), b"not a directory").unwrap();
8197        let queue = Queue::at(dir.path().join("queue"));
8198        let mut t = interrupt_task("rec-fail-1");
8199        record(&queue, &mut t);
8200
8201        let found = crate::notices::Notices::at(dir.path().join("notifications")).list();
8202        assert_eq!(found.len(), 1);
8203        assert_eq!(found[0].key, "loop:record");
8204        assert_eq!(
8205            found[0].link,
8206            Some(Link::Task {
8207                id: "rec-fail-1".to_owned()
8208            })
8209        );
8210    }
8211
8212    /// A runnable task marked to interrupt, with an id fixed for assertions
8213    /// rather than the random one [`Task::new`] mints.
8214    fn interrupt_task(id: &str) -> Task {
8215        let mut t = task();
8216        t.id = id.to_owned();
8217        t.interrupt = true;
8218        t
8219    }
8220
8221    /// An ordinary runnable task with an id fixed for assertions.
8222    fn task_with_id(id: &str) -> Task {
8223        let mut t = task();
8224        t.id = id.to_owned();
8225        t
8226    }
8227
8228    /// A runnable task marked `--urgent`, with an id fixed for assertions.
8229    fn urgent_task(id: &str) -> Task {
8230        let mut t = task();
8231        t.id = id.to_owned();
8232        t.urgent = true;
8233        t
8234    }
8235
8236    #[test]
8237    fn upgrade_resume_dispatch_keeps_claim_and_lane_limits() {
8238        let dir = tempfile::tempdir().unwrap();
8239        let queue = Queue::at(dir.path().join("queue"));
8240        let mut parked = task_with_id("parked");
8241        parked.start("run".into());
8242        parked.park("upgrade");
8243        parked.record_pass_at(
8244            "run",
8245            0,
8246            Some(Timestamp::now()),
8247            1,
8248            Some(crate::run::ParkCause::Upgrade {
8249                from: "old".into(),
8250                to: None,
8251            }),
8252        );
8253        let mut fresh = task_with_id("fresh");
8254        fresh.priority = 100;
8255        let mut urgent_task = urgent_task("urgent");
8256        for t in [&mut parked, &mut fresh, &mut urgent_task] {
8257            queue.put(t).unwrap();
8258        }
8259        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8260        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8261        let candidates = runnable(&queue);
8262        assert_eq!(candidates[0].id, parked.id);
8263        let first = claim_dispatch(&queue, &candidates[0], false, &ordinary, &urgent).unwrap();
8264        assert!(claim_dispatch(&queue, &fresh, false, &ordinary, &urgent).is_err());
8265        assert!(claim_dispatch(&queue, &urgent_task, false, &ordinary, &urgent).is_ok());
8266        drop(first);
8267        let claimed_elsewhere = queue.claim(&parked.id).unwrap();
8268        let next = runnable(&queue)
8269            .into_iter()
8270            .find_map(|t| claim_dispatch(&queue, &t, false, &ordinary, &urgent).ok())
8271            .unwrap();
8272        assert_eq!(next.task.id, fresh.id);
8273        assert_eq!(queue.get(&parked.id).unwrap().attempts, 0);
8274        drop(claimed_elsewhere);
8275        drop(next);
8276        assert!(matches!(
8277            claim_dispatch(&queue, &parked, true, &ordinary, &urgent),
8278            Err(SkipReason::CoolingDown)
8279        ));
8280    }
8281
8282    #[test]
8283    fn urgent_dispatch_has_one_extra_slot_and_never_uses_a_stale_flag() {
8284        let dir = tempfile::tempdir().unwrap();
8285        let queue = Queue::at(dir.path().join("queue"));
8286        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8287        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8288        let occupied = Arc::clone(&ordinary).try_acquire_owned().unwrap();
8289        let mut first = task();
8290        queue.put(&mut first).unwrap();
8291        let stale_plain = queue.get(&first.id).unwrap();
8292        first.set_urgent(true).unwrap();
8293        queue.put(&mut first).unwrap();
8294        let dispatched = claim_dispatch(&queue, &stale_plain, false, &ordinary, &urgent).unwrap();
8295        let mut second = urgent_task("second");
8296        queue.put(&mut second).unwrap();
8297        assert!(matches!(
8298            claim_dispatch(&queue, &second, false, &ordinary, &urgent),
8299            Err(SkipReason::UrgentCapacity)
8300        ));
8301        drop(queue.claim(&second.id).unwrap());
8302        assert_eq!(queue.get(&second.id).unwrap().attempts, 0);
8303        drop(dispatched);
8304        let stale_urgent = queue.get(&first.id).unwrap();
8305        first.set_urgent(false).unwrap();
8306        queue.put(&mut first).unwrap();
8307        assert!(matches!(
8308            claim_dispatch(&queue, &stale_urgent, false, &ordinary, &urgent),
8309            Err(SkipReason::OrdinaryCapacity)
8310        ));
8311        assert_eq!(urgent.available_permits(), 1);
8312        drop(queue.claim(&first.id).unwrap());
8313        drop(occupied);
8314    }
8315
8316    #[test]
8317    fn urgent_dispatch_uses_saved_lane_and_releases_unsuccessful_claims() {
8318        let dir = tempfile::tempdir().unwrap();
8319        let queue = Queue::at(dir.path().join("queue"));
8320        let ordinary = Arc::new(tokio::sync::Semaphore::new(1));
8321        let urgent = Arc::new(tokio::sync::Semaphore::new(1));
8322        let mut t = task();
8323        queue.put(&mut t).unwrap();
8324        for enabled in [true, false] {
8325            let stale = queue.get(&t.id).unwrap();
8326            t.set_urgent(enabled).unwrap();
8327            queue.put(&mut t).unwrap();
8328            assert_ne!(stale.urgent, enabled);
8329            let DispatchClaim {
8330                task: fresh,
8331                claim,
8332                permit,
8333            } = claim_dispatch(&queue, &stale, false, &ordinary, &urgent).unwrap();
8334            assert_eq!(fresh.urgent, enabled);
8335            assert_eq!(ordinary.available_permits(), usize::from(enabled));
8336            assert_eq!(urgent.available_permits(), usize::from(!enabled));
8337            assert!(queue.claim(&t.id).is_err());
8338            assert_eq!(fresh.attempts, stale.attempts);
8339            drop((claim, permit));
8340            assert_eq!(ordinary.available_permits(), 1);
8341            assert_eq!(urgent.available_permits(), 1);
8342        }
8343        t.set_urgent(true).unwrap();
8344        queue.put(&mut t).unwrap();
8345        let occupied = Arc::clone(&urgent).try_acquire_owned().unwrap();
8346        assert!(matches!(
8347            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8348            Err(SkipReason::UrgentCapacity)
8349        ));
8350        assert_eq!(ordinary.available_permits(), 1, "no ordinary fallback");
8351        drop(queue.claim(&t.id).unwrap());
8352        assert_eq!(queue.get(&t.id).unwrap().attempts, t.attempts);
8353        drop(occupied);
8354        assert!(matches!(
8355            claim_dispatch(&queue, &t, true, &ordinary, &urgent),
8356            Err(SkipReason::CoolingDown)
8357        ));
8358        drop(queue.claim(&t.id).unwrap());
8359        let held = queue.claim(&t.id).unwrap();
8360        assert!(matches!(
8361            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8362            Err(SkipReason::ClaimUnavailable)
8363        ));
8364        drop(held);
8365        t.status = TaskStatus::Held;
8366        queue.put(&mut t).unwrap();
8367        assert!(matches!(
8368            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8369            Err(SkipReason::NoLongerRunnable)
8370        ));
8371        drop(queue.claim(&t.id).unwrap());
8372        std::fs::remove_file(queue.path_of(&t.id)).unwrap();
8373        assert!(matches!(
8374            claim_dispatch(&queue, &t, false, &ordinary, &urgent),
8375            Err(SkipReason::RereadFailed)
8376        ));
8377        drop(queue.claim(&t.id).unwrap());
8378        assert_eq!(urgent.available_permits(), 1);
8379    }
8380
8381    /// The land-resume exemption wins outright, whether or not the candidate
8382    /// also happens to be marked [`Task::urgent`]: a resume's own "must not
8383    /// queue behind anything" guarantee cannot be weaker just because the
8384    /// same task was also filed with `--urgent`.
8385    #[test]
8386    fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
8387        assert_eq!(permit_kind(true, false), PermitKind::None);
8388        assert_eq!(permit_kind(true, true), PermitKind::None);
8389    }
8390
8391    /// The one property this whole feature exists for: `--urgent` draws from
8392    /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
8393    /// ordinary candidate draws from the ordinary pool exactly as before,
8394    /// untouched by the urgent slot's existence.
8395    #[test]
8396    fn permit_kind_separates_urgent_from_ordinary() {
8397        assert_eq!(permit_kind(false, true), PermitKind::Urgent);
8398        assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
8399    }
8400
8401    /// The exact wiring `attempt` runs before minting anything: a config's
8402    /// `min_free_bytes` in, a task-holding reason naming both numbers out.
8403    /// Free space is injected rather than asked of the real disk - the point
8404    /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
8405    /// is deterministic on every machine this test runs on, never dependent
8406    /// on how full the CI runner's own disk happens to be.
8407    #[test]
8408    fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
8409        let cfg = Config::default();
8410        let repo = Path::new("/any/repo/path");
8411
8412        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(1024))
8413            .expect("must hold below the threshold");
8414        assert!(reason.contains("1024"), "{reason}");
8415        assert!(
8416            reason.contains(&cfg.disk.min_free_bytes.to_string()),
8417            "{reason}"
8418        );
8419
8420        assert_eq!(
8421            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(cfg.disk.min_free_bytes)),
8422            None,
8423            "exactly at the floor is open"
8424        );
8425        assert_eq!(
8426            disk_gate_with(
8427                repo,
8428                &cfg,
8429                PathBuf::new,
8430                |_| Ok(cfg.disk.min_free_bytes + 1)
8431            ),
8432            None,
8433            "comfortably above the floor is open"
8434        );
8435    }
8436
8437    #[test]
8438    fn disk_gate_with_checks_cache_and_worktree_volumes_and_measurement_errors() {
8439        let dir = tempfile::tempdir().unwrap();
8440        let repo = dir.path().join("repo");
8441        let cache = dir.path().join("cache");
8442        let worktrees = dir.path().join("worktrees");
8443        for path in [&repo, &cache, &worktrees] {
8444            std::fs::create_dir(path).unwrap();
8445        }
8446        let mut cfg = Config::default();
8447        cfg.graph.worktree_root = Some(worktrees.clone());
8448        cfg.verify.gate = vec![format!(
8449            "CARGO_TARGET_DIR='{}' cargo build",
8450            cache.display()
8451        )];
8452        for blocked in [&cache, &worktrees] {
8453            for unmeasured in [false, true] {
8454                assert!(
8455                    disk_gate_with(&repo, &cfg, PathBuf::new, |path| {
8456                        if path == blocked {
8457                            if unmeasured {
8458                                Err(anyhow::anyhow!("measurement failed"))
8459                            } else {
8460                                Ok(0)
8461                            }
8462                        } else {
8463                            Ok(u64::MAX)
8464                        }
8465                    })
8466                    .is_some(),
8467                    "a blocked secondary output volume must close admission"
8468                );
8469            }
8470        }
8471        assert!(disk_gate_with(&repo, &cfg, PathBuf::new, |_| Ok(u64::MAX)).is_none());
8472    }
8473
8474    #[test]
8475    fn isolated_admission_measures_the_run_home_instead_of_the_shared_cache() {
8476        let dir = tempfile::tempdir().unwrap();
8477        let repo = dir.path().join("repo");
8478        let cache = dir.path().join("cache");
8479        let home_parent = dir.path().join("run-volume");
8480        let home = home_parent.join("new-home");
8481        for path in [&repo, &cache, &home_parent] {
8482            std::fs::create_dir(path).unwrap();
8483        }
8484        let mut cfg = Config::default();
8485        cfg.graph.worktree_root = Some(repo.clone());
8486        cfg.verify.gate = vec![format!(
8487            "CARGO_TARGET_DIR='{}' cargo build",
8488            cache.display()
8489        )];
8490        cfg.verify.build_cache = BuildCache::Isolated;
8491        let denied = |blocked: &Path| {
8492            disk_gate_with(
8493                &repo,
8494                &cfg,
8495                || home.clone(),
8496                |path| Ok(if path == blocked { 0 } else { u64::MAX }),
8497            )
8498            .is_some()
8499        };
8500        assert!(!denied(&cache));
8501        assert!(denied(&home_parent));
8502    }
8503
8504    #[test]
8505    fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
8506        let mut cfg = Config::default();
8507        cfg.disk.min_free_bytes = 0;
8508        let repo = Path::new("/any/repo/path");
8509        assert_eq!(
8510            disk_gate_with(repo, &cfg, PathBuf::new, |_| Ok(0)),
8511            None,
8512            "a zero floor never measures at all"
8513        );
8514    }
8515
8516    #[test]
8517    fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
8518        let cfg = Config::default();
8519        let repo = Path::new("/any/repo/path");
8520        let reason = disk_gate_with(repo, &cfg, PathBuf::new, |_| {
8521            Err(anyhow::anyhow!("no df on this box"))
8522        })
8523        .expect("a measurement failure must close the gate, not open it");
8524        assert!(reason.contains("could not measure"), "{reason}");
8525    }
8526
8527    #[test]
8528    fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
8529        let ordinary = task();
8530        let next = advance_interrupt(
8531            Interrupt::Idle,
8532            std::slice::from_ref(&ordinary.id),
8533            std::slice::from_ref(&ordinary),
8534        );
8535        assert_eq!(next, Interrupt::Idle);
8536    }
8537
8538    #[test]
8539    fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
8540        // Nothing to interrupt - this is just an ordinary candidate, and the
8541        // loop's normal dispatch will pick it up like any other.
8542        let marked = interrupt_task("marked");
8543        let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8544        assert_eq!(next, Interrupt::Idle);
8545    }
8546
8547    #[test]
8548    fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
8549        let marked = interrupt_task("marked");
8550        let next = advance_interrupt(
8551            Interrupt::Idle,
8552            &["running".to_owned()],
8553            std::slice::from_ref(&marked),
8554        );
8555        assert_eq!(
8556            next,
8557            Interrupt::Parking {
8558                parked: vec!["running".to_owned()],
8559                interrupt_task: "marked".to_owned(),
8560            }
8561        );
8562    }
8563
8564    /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
8565    /// one run can be in flight when a task becomes runnable and marked.
8566    /// Parking all of them would mean `Resuming` later has more than one id
8567    /// to release back to ordinary dispatch, which cannot be made safe
8568    /// against that same setting's own extra concurrency slots letting two
8569    /// of them start together - see `advance_interrupt`'s own `Idle` branch.
8570    /// The simplification the task's own constraints ask for: do not begin
8571    /// a sequence at all until the herd settles back to exactly one.
8572    #[test]
8573    fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
8574        let marked = interrupt_task("marked");
8575
8576        let two = advance_interrupt(
8577            Interrupt::Idle,
8578            &["a".to_owned(), "b".to_owned()],
8579            std::slice::from_ref(&marked),
8580        );
8581        assert_eq!(two, Interrupt::Idle);
8582
8583        let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
8584        assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
8585    }
8586
8587    #[test]
8588    fn parking_holds_until_every_parked_id_has_actually_left_flight() {
8589        let state = Interrupt::Parking {
8590            parked: vec!["running".to_owned()],
8591            interrupt_task: "marked".to_owned(),
8592        };
8593        // Still in flight: no change.
8594        let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
8595        assert_eq!(still_going, state);
8596
8597        // Left flight, but the interrupt task has not been dispatched yet on
8598        // this tick - stays `Parking` so `interrupt_gate` can let it through,
8599        // as long as it is still runnable.
8600        let stopped_but_not_yet_dispatched =
8601            advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
8602        assert_eq!(stopped_but_not_yet_dispatched, state);
8603
8604        // Left flight, and the interrupt task is now in flight itself.
8605        let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
8606        assert_eq!(
8607            dispatched,
8608            Interrupt::Running {
8609                parked: vec!["running".to_owned()],
8610                interrupt_task: "marked".to_owned(),
8611            }
8612        );
8613    }
8614
8615    #[test]
8616    fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
8617        let state = Interrupt::Running {
8618            parked: vec!["running".to_owned()],
8619            interrupt_task: "marked".to_owned(),
8620        };
8621        let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
8622        assert_eq!(still_running, state);
8623
8624        // Whatever it ended as - merged, failed, held - is not this
8625        // function's concern: leaving flight is the only trigger, driven
8626        // straight off the same in-flight list `poll` already reaps. It does
8627        // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
8628        // why that would let an unrelated task start ahead of, or alongside,
8629        // the guaranteed resume.
8630        let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
8631        assert_eq!(
8632            ended,
8633            Interrupt::Resuming {
8634                parked: vec!["running".to_owned()]
8635            }
8636        );
8637    }
8638
8639    #[test]
8640    fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
8641        let state = Interrupt::Resuming {
8642            parked: vec!["running".to_owned()],
8643        };
8644        let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
8645        assert_eq!(still_waiting, state);
8646
8647        let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
8648        assert_eq!(dispatched, Interrupt::Idle);
8649    }
8650
8651    /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
8652    /// or otherwise moved on by an operator with no claim standing in the
8653    /// way - must not wedge the sequence (and so the whole loop's dispatch,
8654    /// via `interrupt_gate`) waiting forever for a dispatch that can never
8655    /// come. The parked run still gets its resume.
8656    #[test]
8657    fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
8658    {
8659        let state = Interrupt::Parking {
8660            parked: vec!["running".to_owned()],
8661            interrupt_task: "marked".to_owned(),
8662        };
8663        // `marked` has been held/blocked/deleted since the sequence began:
8664        // it no longer appears in `runnable` at all.
8665        let next = advance_interrupt(state, &[], &[]);
8666        assert_eq!(
8667            next,
8668            Interrupt::Resuming {
8669                parked: vec!["running".to_owned()]
8670            },
8671            "abandoning the interrupt must not abandon the resume it owes"
8672        );
8673    }
8674
8675    /// The same abandonment, one step later: `Resuming` itself must not wait
8676    /// forever for a parked task that has since become unrunnable.
8677    #[test]
8678    fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
8679        let state = Interrupt::Resuming {
8680            parked: vec!["running".to_owned()],
8681        };
8682        let next = advance_interrupt(state, &[], &[]);
8683        assert_eq!(
8684            next,
8685            Interrupt::Idle,
8686            "nothing is left to wait for; the loop must not stay wedged"
8687        );
8688    }
8689
8690    #[test]
8691    fn disabled_by_config_the_sequence_can_never_leave_idle() {
8692        let marked = interrupt_task("marked");
8693        let next = advance_interrupt_tick(
8694            false,
8695            Interrupt::Idle,
8696            &["running".to_owned()],
8697            std::slice::from_ref(&marked),
8698        );
8699        assert_eq!(
8700            next,
8701            Interrupt::Idle,
8702            "an unmarked, unconfigured daemon must behave exactly as before"
8703        );
8704    }
8705
8706    #[test]
8707    fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
8708        let state = Interrupt::Parking {
8709            parked: vec!["running".to_owned()],
8710            interrupt_task: "marked".to_owned(),
8711        };
8712        let candidates = vec![interrupt_task("marked"), task()];
8713        let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8714        assert!(
8715            allowed.is_empty(),
8716            "nothing may dispatch - not even the interrupt task itself - \
8717             until the parked run has actually stopped"
8718        );
8719    }
8720
8721    /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
8722    /// grow a special case for it: an urgent candidate that is not the
8723    /// interrupt task withholds exactly like an ordinary one for as long as
8724    /// the parked run it is racing has not actually left flight. A version
8725    /// of this feature once bypassed the gate for urgent candidates, on the
8726    /// theory that a genuinely separate concurrency lane could not collide
8727    /// with 75dd's own; it could, and did - the bypassed task dispatched
8728    /// alongside a run 75dd's own state machine had only *asked* to park,
8729    /// not yet confirmed gone, which is exactly the second run
8730    /// `Interrupt::Parking`'s own doc says must never happen. There is no
8731    /// tick during Parking/Running/Resuming where letting an extra
8732    /// candidate through is safe, urgent or not - the parked run may still
8733    /// be genuinely mid-call.
8734    #[test]
8735    fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
8736        for state in [
8737            Interrupt::Parking {
8738                parked: vec!["running".to_owned()],
8739                interrupt_task: "marked".to_owned(),
8740            },
8741            Interrupt::Running {
8742                parked: vec!["running".to_owned()],
8743                interrupt_task: "marked".to_owned(),
8744            },
8745            Interrupt::Resuming {
8746                parked: vec!["running".to_owned()],
8747            },
8748        ] {
8749            let candidates = vec![
8750                interrupt_task("marked"),
8751                urgent_task("hot"),
8752                task_with_id("ordinary"),
8753            ];
8754            let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
8755            assert!(
8756                !allowed.iter().any(|t| t.id == "hot"),
8757                "an urgent candidate must wait out the same gate as anything \
8758                 else while the run it would run alongside has not actually \
8759                 left flight, for state {state:?}: {allowed:?}"
8760            );
8761        }
8762    }
8763
8764    /// The one case where marking a task `--urgent` and `interrupt` at once
8765    /// is not redundant: once the interrupt sequence's own guaranteed
8766    /// resume/dispatch actually admits the task, it is unaffected by also
8767    /// carrying `urgent` - `interrupt_gate` decides purely on identity,
8768    /// never on the urgent flag.
8769    #[test]
8770    fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
8771        let state = Interrupt::Resuming {
8772            parked: vec!["hot".to_owned()],
8773        };
8774        let candidates = vec![urgent_task("hot"), task()];
8775        let allowed = interrupt_gate(&state, &[], candidates);
8776        assert_eq!(
8777            allowed.iter().filter(|t| t.id == "hot").count(),
8778            1,
8779            "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
8780        );
8781    }
8782
8783    #[test]
8784    fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
8785        let state = Interrupt::Parking {
8786            parked: vec!["running".to_owned()],
8787            interrupt_task: "marked".to_owned(),
8788        };
8789        let other = task();
8790        let candidates = vec![interrupt_task("marked"), other.clone()];
8791        let allowed = interrupt_gate(&state, &[], candidates);
8792        assert_eq!(allowed.len(), 1);
8793        assert_eq!(allowed[0].id, "marked");
8794    }
8795
8796    #[test]
8797    fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
8798        let state = Interrupt::Running {
8799            parked: vec!["running".to_owned()],
8800            interrupt_task: "marked".to_owned(),
8801        };
8802        let candidates = vec![task(), task()];
8803        let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
8804        assert!(allowed.is_empty());
8805    }
8806
8807    /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
8808    /// sequence began (only reachable above the default
8809    /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
8810    /// never both in the same tick, which is what "exactly one resume, no
8811    /// simultaneous run" actually requires structurally rather than by
8812    /// coincidence of how many ordinary slots happen to be free.
8813    #[test]
8814    fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
8815        let state = Interrupt::Resuming {
8816            parked: vec!["a".to_owned(), "c".to_owned()],
8817        };
8818        let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
8819        let allowed = interrupt_gate(&state, &[], candidates);
8820        assert_eq!(
8821            allowed.len(),
8822            1,
8823            "at most one candidate may be offered while resuming: {allowed:?}"
8824        );
8825        assert_eq!(allowed[0].id, "a");
8826    }
8827
8828    #[test]
8829    fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
8830        let state = Interrupt::Resuming {
8831            parked: vec!["a".to_owned()],
8832        };
8833        let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
8834        assert!(allowed.is_empty());
8835    }
8836
8837    /// The invariant the completion criteria ask for by name: across a whole
8838    /// simulated sequence, there is never a tick where the gate would let
8839    /// through both the parked run's resume and the interrupt task, and
8840    /// exactly one candidate resumes the instant the interrupt task's run
8841    /// ends - never zero, never more than one.
8842    #[test]
8843    fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
8844        let running = task(); // id: whatever `Task::new` minted
8845        let marked = interrupt_task("marked");
8846
8847        let mut state = Interrupt::Idle;
8848        // Tick 1: `running` is in flight, `marked` becomes runnable.
8849        let in_flight = vec![running.id.clone()];
8850        state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
8851        let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
8852        assert!(gated.is_empty(), "still waiting on `running` to park");
8853
8854        // Tick 2: `running` parked and left flight; nothing dispatched yet.
8855        state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
8856        let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
8857        assert_eq!(
8858            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8859            vec!["marked"],
8860            "only the interrupt task may be offered to the dispatcher now"
8861        );
8862
8863        // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
8864        state = advance_interrupt_tick(
8865            true,
8866            state,
8867            &["marked".to_owned()],
8868            std::slice::from_ref(&running),
8869        );
8870        let gated = interrupt_gate(
8871            &state,
8872            &["marked".to_owned()],
8873            vec![marked.clone(), running.clone()],
8874        );
8875        assert!(
8876            gated.is_empty(),
8877            "the parked run must not be offered back while the interrupt \
8878             task is still running"
8879        );
8880
8881        // Tick 4: `marked`'s run reached a terminal status and left flight.
8882        // A higher-priority ordinary task `other` is also runnable now - it
8883        // must not be let through instead of, or alongside, `running`.
8884        let other = task_with_id("other");
8885        state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
8886        assert_eq!(
8887            state,
8888            Interrupt::Resuming {
8889                parked: vec![running.id.clone()]
8890            }
8891        );
8892        let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
8893        assert_eq!(
8894            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8895            vec![running.id.as_str()],
8896            "exactly the parked run resumes - not the unrelated task, even \
8897             though it was offered first"
8898        );
8899
8900        // Tick 5: `running` is now in flight (dispatched from tick 4's
8901        // gate). Only now does the sequence end and ordinary dispatch fully
8902        // resume.
8903        state = advance_interrupt_tick(
8904            true,
8905            state,
8906            std::slice::from_ref(&running.id),
8907            std::slice::from_ref(&other),
8908        );
8909        assert_eq!(state, Interrupt::Idle);
8910        let gated = interrupt_gate(
8911            &state,
8912            std::slice::from_ref(&running.id),
8913            vec![other.clone()],
8914        );
8915        assert_eq!(
8916            gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
8917            vec![other.id.as_str()],
8918            "ordinary dispatch is unrestricted again"
8919        );
8920    }
8921
8922    #[test]
8923    fn every_run_status_settles_the_task_it_came_from() {
8924        // run status, resulting task status, attempts still standing after one
8925        let table = [
8926            (RunStatus::Merged, TaskStatus::Done, 1),
8927            (RunStatus::Ready, TaskStatus::Done, 1),
8928            (RunStatus::Stalled, TaskStatus::Failed, 0),
8929            (RunStatus::Blocked, TaskStatus::Failed, 1),
8930            (RunStatus::Failed, TaskStatus::Failed, 1),
8931            (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
8932            (RunStatus::Prep, TaskStatus::Failed, 1),
8933            (RunStatus::Implementing, TaskStatus::Failed, 1),
8934            (RunStatus::Judging, TaskStatus::Failed, 1),
8935            (RunStatus::Deliberating, TaskStatus::Failed, 1),
8936            (RunStatus::Voting, TaskStatus::Failed, 1),
8937            (RunStatus::Reviewing, TaskStatus::Failed, 1),
8938            (RunStatus::Gating, TaskStatus::Failed, 1),
8939        ];
8940        for (run, want, attempts) in table {
8941            let mut t = task();
8942            t.start("20260902-000000-aaaa".to_owned());
8943            settle(
8944                &mut t,
8945                Verdict {
8946                    status: run,
8947                    left_pr: false,
8948                    parked: false,
8949                    quota_hit: matches!(run, RunStatus::Stalled),
8950                    no_viable_candidates: false,
8951                },
8952                "why",
8953                2,
8954            );
8955            assert_eq!(t.status, want, "task status after {}", label(run));
8956            assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
8957        }
8958    }
8959
8960    #[test]
8961    fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
8962        let mut stalled = task();
8963        stalled.start("20260902-000000-aaaa".to_owned());
8964        settle(
8965            &mut stalled,
8966            Verdict {
8967                status: RunStatus::Stalled,
8968                left_pr: false,
8969                parked: false,
8970                quota_hit: true,
8971                no_viable_candidates: false,
8972            },
8973            "quota",
8974            1,
8975        );
8976        assert_eq!(stalled.attempts, 0);
8977        assert!(
8978            stalled.status.runnable(),
8979            "a machine problem must leave the task in line"
8980        );
8981
8982        let mut blocked = task();
8983        blocked.start("20260902-000000-aaaa".to_owned());
8984        settle(
8985            &mut blocked,
8986            Verdict {
8987                status: RunStatus::Blocked,
8988                left_pr: false,
8989                parked: false,
8990                quota_hit: false,
8991                no_viable_candidates: false,
8992            },
8993            "findings open",
8994            1,
8995        );
8996        assert_eq!(blocked.attempts, 1);
8997        assert_eq!(
8998            blocked.status,
8999            TaskStatus::Held,
9000            "the last attempt hands the task to a human"
9001        );
9002    }
9003
9004    #[test]
9005    fn a_run_that_opened_a_pull_request_is_never_re_competed() {
9006        // Attempts to spare: without the pull request this task would go
9007        // straight back in line and run the whole competition again.
9008        let mut delivered = task();
9009        delivered.start("20260903-080619-01c2".to_owned());
9010        settle(
9011            &mut delivered,
9012            Verdict {
9013                status: RunStatus::Blocked,
9014                left_pr: true,
9015                parked: false,
9016                quota_hit: false,
9017                no_viable_candidates: false,
9018            },
9019            "no check status",
9020            4,
9021        );
9022        assert_eq!(
9023            delivered.status,
9024            TaskStatus::Held,
9025            "a pull request waiting on CI or a person is not a retryable failure"
9026        );
9027        assert!(
9028            !delivered.status.runnable(),
9029            "the loop must not pick this task up again"
9030        );
9031        assert_eq!(
9032            delivered.last_error.as_deref(),
9033            Some("no check status"),
9034            "the operator needs to be told what the gate was waiting for"
9035        );
9036
9037        // The same status without a pull request is a plain failure, and with
9038        // attempts left it is retried.
9039        let mut empty_handed = task();
9040        empty_handed.start("20260903-080619-01c2".to_owned());
9041        settle(
9042            &mut empty_handed,
9043            Verdict {
9044                status: RunStatus::Blocked,
9045                left_pr: false,
9046                parked: false,
9047                quota_hit: false,
9048                no_viable_candidates: false,
9049            },
9050            "findings open",
9051            4,
9052        );
9053        assert_eq!(empty_handed.status, TaskStatus::Failed);
9054        assert!(empty_handed.status.runnable());
9055    }
9056
9057    #[test]
9058    fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
9059        // Every candidate agreed, with evidence, that nothing belonged in the
9060        // worktree. That is not a confirmed success to close automatically -
9061        // a human still has to check the claim - and it is not an ordinary
9062        // failure either, so this settles exactly like a pull request nobody
9063        // merged yet: `Held`, same as `Blocked` with a PR.
9064        let mut noop = task();
9065        noop.start("20260912-131304-391f".to_owned());
9066        settle(
9067            &mut noop,
9068            Verdict {
9069                status: RunStatus::VerifiedNoop,
9070                left_pr: false,
9071                parked: false,
9072                quota_hit: false,
9073                no_viable_candidates: true,
9074            },
9075            "candidate A: already fixed by b32cfc4, on main",
9076            4,
9077        );
9078        assert_eq!(
9079            noop.status,
9080            TaskStatus::Held,
9081            "an unverified claim is a request for a human, not a failure"
9082        );
9083        assert!(
9084            !noop.status.runnable(),
9085            "the loop must not requeue this on the same unverified claim"
9086        );
9087        // `Task::release` resets attempts to zero the moment a human looks at
9088        // the evidence and lets it run again, so it does not matter here
9089        // whether the one attempt already spent stays spent - what matters is
9090        // that nothing retries this task unattended in the meantime.
9091        assert_eq!(noop.attempts, 1);
9092    }
9093
9094    #[test]
9095    fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
9096        // Parking is the operator asking for the process back - to replace the
9097        // binary, most of all. The run's work is intact on disk, so this is
9098        // not a failed attempt, and charging for it would mean a few upgrades
9099        // could exhaust a budget meant for agents that misbehaved.
9100        let mut parked = task();
9101        parked.start("20260903-183634-2d98".to_owned());
9102        settle(
9103            &mut parked,
9104            Verdict {
9105                status: RunStatus::Implementing,
9106                left_pr: false,
9107                quota_hit: false,
9108                parked: true,
9109                no_viable_candidates: false,
9110            },
9111            "parked after `implementing`",
9112            2,
9113        );
9114        assert_eq!(parked.attempts, 0, "a park is refunded");
9115        assert!(
9116            parked.status.runnable(),
9117            "and the task stays in line so the next loop resumes its run"
9118        );
9119        assert_eq!(parked.status, TaskStatus::Parked);
9120        assert_eq!(
9121            parked.park_reason.as_deref(),
9122            Some("parked after `implementing`"),
9123            "the card says where it stopped"
9124        );
9125        assert_eq!(parked.last_error, None, "nothing failed");
9126
9127        // Without the park flag the same non-terminal status is what it always
9128        // was: `execute` returning mid-flight, which is a bug and spends an
9129        // attempt so a task cannot loop on it forever.
9130        let mut broken = task();
9131        broken.start("20260903-183634-2d98".to_owned());
9132        settle(
9133            &mut broken,
9134            Verdict {
9135                status: RunStatus::Implementing,
9136                left_pr: false,
9137                quota_hit: false,
9138                parked: false,
9139                no_viable_candidates: false,
9140            },
9141            "returned mid-flight",
9142            2,
9143        );
9144        assert_eq!(broken.attempts, 1);
9145    }
9146
9147    #[test]
9148    fn only_a_rate_limit_buys_the_task_its_attempt_back() {
9149        // Run e633: quorum lost because two judges answered with the wrong
9150        // JSON shape, `quota: []`. Refunding that takes the bound off the
9151        // retry loop, and each retry pays for a fresh hour-long implement
9152        // wave before it can fail the same way.
9153        let mut flaky = task();
9154        flaky.start("20260903-123023-e633".to_owned());
9155        settle(
9156            &mut flaky,
9157            Verdict {
9158                status: RunStatus::Stalled,
9159                left_pr: false,
9160                parked: false,
9161                quota_hit: false,
9162                no_viable_candidates: false,
9163            },
9164            "verdict rests on 1 of 3 judges",
9165            2,
9166        );
9167        assert_eq!(
9168            flaky.attempts, 1,
9169            "flakiness spends an attempt, so `max_attempts` still bounds it"
9170        );
9171        assert!(flaky.status.runnable(), "and it is still worth retrying");
9172
9173        // The same status, lost to a rate limit, is the machine's fault.
9174        let mut limited = task();
9175        limited.start("20260903-123023-e633".to_owned());
9176        settle(
9177            &mut limited,
9178            Verdict {
9179                status: RunStatus::Stalled,
9180                left_pr: false,
9181                parked: false,
9182                quota_hit: true,
9183                no_viable_candidates: false,
9184            },
9185            "judge-2, judge-3 out of quota",
9186            2,
9187        );
9188        assert_eq!(limited.attempts, 0, "a quota window is refunded");
9189        assert!(limited.status.runnable());
9190
9191        // And the bound really binds: a task that keeps stalling on flakiness
9192        // reaches a human instead of running the roster forever.
9193        let mut worn = task();
9194        for _ in 0..2 {
9195            worn.release();
9196        }
9197        worn.start("20260903-123023-e633".to_owned());
9198        worn.attempts = 2;
9199        settle(
9200            &mut worn,
9201            Verdict {
9202                status: RunStatus::Stalled,
9203                left_pr: false,
9204                parked: false,
9205                quota_hit: false,
9206                no_viable_candidates: false,
9207            },
9208            "no quorum again",
9209            2,
9210        );
9211        assert_eq!(worn.status, TaskStatus::Held);
9212        assert!(!worn.status.runnable());
9213    }
9214
9215    #[test]
9216    fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
9217        // The implement wave loses every seat to the same rate limit and
9218        // `after_implement` bails with nothing viable, which surfaces as
9219        // `Failed` rather than `Stalled`. That is the same machine fact the
9220        // `Stalled`-quota row already refunds, and must be refunded the same
9221        // way, or a quota outage quietly holds every task it touches instead
9222        // of leaving them in line for the reset.
9223        let mut wiped_out = task();
9224        wiped_out.start("20260907-025000-a1b2".to_owned());
9225        settle(
9226            &mut wiped_out,
9227            Verdict {
9228                status: RunStatus::Failed,
9229                left_pr: false,
9230                parked: false,
9231                quota_hit: true,
9232                no_viable_candidates: true,
9233            },
9234            "no candidate produced a change; nothing to judge",
9235            2,
9236        );
9237        assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
9238        assert!(
9239            wiped_out.status.runnable(),
9240            "a machine problem must leave the task in line"
9241        );
9242
9243        // This is the exemption that must stay narrow: a candidate that did
9244        // produce a change, and then failed for some other reason, still
9245        // spends the attempt even though a seat elsewhere hit its quota.
9246        // Otherwise every ordinary failure that happens to share a run with
9247        // an unrelated rate limit would be refunded for free.
9248        let mut partial_progress = task();
9249        partial_progress.start("20260907-025500-c3d4".to_owned());
9250        settle(
9251            &mut partial_progress,
9252            Verdict {
9253                status: RunStatus::Failed,
9254                left_pr: false,
9255                parked: false,
9256                quota_hit: true,
9257                no_viable_candidates: false,
9258            },
9259            "gate failed on the winning candidate",
9260            2,
9261        );
9262        assert_eq!(
9263            partial_progress.attempts, 1,
9264            "a candidate that actually produced a change spends the attempt \
9265             even though some other seat hit its quota"
9266        );
9267        assert!(partial_progress.status.runnable());
9268    }
9269
9270    #[test]
9271    fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
9272        // `reclaim` builds its own `Verdict` from a `RunState` it loads off
9273        // disk, and that construction must reach the same conclusion as the
9274        // one `attempt` builds from a live run, or a crash at exactly the
9275        // wrong moment gives a recovered task a different policy than one a
9276        // daemon finished settling itself.
9277        let mut t = task();
9278        t.start("20260907-025000-a1b2".to_owned());
9279        let mut state = run_state(RunStatus::Failed);
9280        state.quota.push(QuotaLoss {
9281            cause: crate::agent::QuotaCause::UsageLimit,
9282            agent: String::new(),
9283            seat: "cand-a".to_owned(),
9284            node: "implement".to_owned(),
9285            at: Timestamp::now(),
9286            reset: None,
9287        });
9288        assert!(
9289            state.viable().is_empty(),
9290            "no candidate was added, so nothing is viable"
9291        );
9292        reclaim(&mut t, Some(state), 2, "en");
9293        assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
9294        assert!(t.status.runnable());
9295    }
9296
9297    #[test]
9298    fn a_held_task_is_never_offered_to_the_loop() {
9299        let dir = tempfile::tempdir().unwrap();
9300        let queue = Queue::at(dir.path().to_path_buf());
9301        for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
9302            let mut t = task();
9303            t.id = format!("2026090{n}-000000-000{n}");
9304            t.priority = priority;
9305            queue.put(&mut t).unwrap();
9306        }
9307        let mut held = task();
9308        held.id = "20260909-000000-9999".to_owned();
9309        held.priority = 99;
9310        held.hold_machine(None);
9311        queue.put(&mut held).unwrap();
9312
9313        let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
9314        assert_eq!(order.len(), 3);
9315        assert!(!order.contains(&held.id));
9316        assert_eq!(
9317            order.first().cloned(),
9318            queue.next_runnable().map(|t| t.id),
9319            "the loop's first candidate is exactly what the queue offers"
9320        );
9321        assert_eq!(
9322            order,
9323            vec![
9324                "20260902-000000-0002".to_owned(),
9325                "20260903-000000-0003".to_owned(),
9326                "20260901-000000-0001".to_owned(),
9327            ],
9328            "priority first, then oldest, so nothing starves"
9329        );
9330    }
9331
9332    #[test]
9333    fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
9334        let dir = tempfile::tempdir().unwrap();
9335        let queue = Queue::at(dir.path().to_path_buf());
9336        let mut old = task();
9337        old.id = "20260101-000000-old0".to_owned();
9338        queue.put(&mut old).unwrap();
9339        let mut fresh = task();
9340        fresh.id = "20260101-000000-new0".to_owned();
9341        queue.put(&mut fresh).unwrap();
9342
9343        // No parseable pid at all, so age is the only signal there is to
9344        // check - unlike a real `Queue::claim`, which always names a real,
9345        // and therefore alive, pid this test cannot fake as dead.
9346        std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
9347        std::thread::sleep(Duration::from_millis(60));
9348        let live = queue.claim(&fresh.id).unwrap();
9349
9350        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9351        assert_eq!(swept, vec![old.id.clone()]);
9352        assert!(
9353            queue.claim(&old.id).is_ok(),
9354            "an unparseable lock older than the threshold is swept"
9355        );
9356        assert!(
9357            queue.claim(&fresh.id).is_err(),
9358            "a live pid protects its lock regardless of age"
9359        );
9360        drop(live);
9361    }
9362
9363    #[test]
9364    fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
9365        // A live worker's claim remains authoritative even beyond the sweep's
9366        // age limit. Sweeping it would permit a second competing attempt.
9367        let dir = tempfile::tempdir().unwrap();
9368        let queue = Queue::at(dir.path().to_path_buf());
9369        let mut t = task();
9370        t.id = "20260101-000000-live".to_owned();
9371        queue.put(&mut t).unwrap();
9372
9373        let claim = queue.claim(&t.id).unwrap();
9374        std::thread::sleep(Duration::from_millis(60));
9375
9376        let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
9377        assert!(
9378            swept.is_empty(),
9379            "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
9380        );
9381        assert!(
9382            queue.claim(&t.id).is_err(),
9383            "the lock still protects its task"
9384        );
9385        drop(claim);
9386    }
9387
9388    /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
9389    /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
9390    fn injected_dead_pid() -> u32 {
9391        std::process::id().checked_add(1).unwrap_or(1)
9392    }
9393
9394    #[test]
9395    fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
9396        let dir = tempfile::tempdir().unwrap();
9397        let queue = Queue::at(dir.path().to_path_buf());
9398        let mut t = task();
9399        t.id = "20260101-000000-dead".to_owned();
9400        queue.put(&mut t).unwrap();
9401        let dead_pid = injected_dead_pid();
9402
9403        // Written directly rather than through `Queue::claim`, which would
9404        // stamp this test process's own very much alive pid and defeat the
9405        // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
9406        // like moments after it died, not six hours later.
9407        std::fs::write(
9408            dir.path().join(format!("{}.lock", t.id)),
9409            dead_pid.to_string(),
9410        )
9411        .unwrap();
9412
9413        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9414            pid != dead_pid
9415        });
9416        assert_eq!(
9417            swept,
9418            vec![t.id.clone()],
9419            "a dead owner is reclaimed immediately, not after STALE_CLAIM"
9420        );
9421        assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
9422    }
9423
9424    #[test]
9425    fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
9426        let dir = tempfile::tempdir().unwrap();
9427        let queue = Queue::at(dir.path().to_path_buf());
9428        let mut t = task();
9429        t.id = "20260101-000000-late".to_owned();
9430        queue.put(&mut t).unwrap();
9431        let dead_pid = injected_dead_pid();
9432
9433        // Tick one, standing in for the sweep `poll` already runs at
9434        // startup: nothing to find yet.
9435        assert!(
9436            sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
9437            "nothing has claimed the task yet"
9438        );
9439
9440        // A second daemon claims the task and dies before it ever writes
9441        // `running`, well after this loop's own startup sweep already ran.
9442        std::fs::write(
9443            dir.path().join(format!("{}.lock", t.id)),
9444            dead_pid.to_string(),
9445        )
9446        .unwrap();
9447
9448        // Tick two, standing in for a poll long into this daemon's uptime:
9449        // the same function, called again, notices what only just appeared -
9450        // proving the sweep is not a one-shot startup check.
9451        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9452            pid != dead_pid
9453        });
9454        assert_eq!(swept, vec![t.id.clone()]);
9455    }
9456
9457    #[test]
9458    fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
9459        // `reclaim_orphaned_running` looks up the task's last run, which
9460        // touches `run::home()`; the first call anywhere in this binary wins,
9461        // so this is a no-op if another test already pinned one, and either
9462        // way the run id below is never written under it.
9463        crate::run::pin_test_home();
9464        let dir = tempfile::tempdir().unwrap();
9465        let queue = Queue::at(dir.path().to_path_buf());
9466        let mut t = task();
9467        t.id = "20260101-000000-crsh".to_owned();
9468        t.status = TaskStatus::Running;
9469        t.attempts = 1;
9470        // No `run.json` behind this id: standing in for a run this test does
9471        // not need to make readable, since the point is the lock, not the
9472        // recovery table `reclaim` already has its own tests for.
9473        t.runs.push("20260904-000000-4043".to_owned());
9474        queue.put(&mut t).unwrap();
9475        let dead_pid = injected_dead_pid();
9476
9477        // The crashed daemon's own claim, naming a pid nothing on the
9478        // machine holds anymore.
9479        std::fs::write(
9480            dir.path().join(format!("{}.lock", t.id)),
9481            dead_pid.to_string(),
9482        )
9483        .unwrap();
9484
9485        // Before the lock is swept the task looks claimed, and
9486        // `reclaim_orphaned_running` must leave it alone - this is exactly
9487        // the bug: a `running` task stranded behind a dead daemon's lock,
9488        // invisible to the claim-as-proof check because the lock outlived
9489        // the process that wrote it.
9490        assert!(reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty());
9491        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
9492
9493        let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
9494            pid != dead_pid
9495        });
9496        assert_eq!(swept, vec![t.id.clone()]);
9497
9498        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
9499        assert_eq!(reclaimed, vec![t.id.clone()]);
9500        let after = queue.get(&t.id).unwrap();
9501        assert_eq!(
9502            after.status,
9503            TaskStatus::Held,
9504            "no run.json to recover from, so a human is asked"
9505        );
9506        assert_eq!(
9507            after.runs,
9508            vec!["20260904-000000-4043".to_owned()],
9509            "the crashed run's id is kept as evidence, not discarded"
9510        );
9511    }
9512
9513    #[test]
9514    fn a_lock_is_kept_when_the_process_query_is_unavailable() {
9515        let dir = tempfile::tempdir().unwrap();
9516        let queue = Queue::at(dir.path().to_path_buf());
9517        let mut t = task();
9518        t.id = "20260101-000000-unknown".to_owned();
9519        queue.put(&mut t).unwrap();
9520        let dead_pid = injected_dead_pid();
9521        std::fs::write(
9522            dir.path().join(format!("{}.lock", t.id)),
9523            dead_pid.to_string(),
9524        )
9525        .unwrap();
9526
9527        let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
9528        assert!(swept.is_empty(), "an unknown pid must keep its lock");
9529        assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
9530    }
9531
9532    fn run_state_in(status: RunStatus, language: &str) -> RunState {
9533        let mut s = run_state(status);
9534        s.config.graph.language = language.to_owned();
9535        s
9536    }
9537
9538    fn unstarted_verdict(status: RunStatus) -> Verdict {
9539        Verdict {
9540            status,
9541            left_pr: false,
9542            quota_hit: false,
9543            parked: false,
9544            no_viable_candidates: false,
9545        }
9546    }
9547
9548    #[test]
9549    fn an_already_in_base_run_finishes_the_task_without_spending_an_attempt() {
9550        let mut t = task();
9551        t.attempts = 1;
9552        settle_in(
9553            &mut t,
9554            unstarted_verdict(RunStatus::AlreadyInBase),
9555            "already in main",
9556            1,
9557            phrases("en"),
9558            None,
9559        );
9560        assert_eq!(t.status, TaskStatus::Done);
9561        assert_eq!(t.attempts, 0);
9562    }
9563
9564    #[test]
9565    fn settle_renders_the_non_terminal_reason_in_the_configured_language() {
9566        let reason = |language: &str| {
9567            let mut t = task();
9568            settle_in(
9569                &mut t,
9570                unstarted_verdict(RunStatus::Judging),
9571                "boom",
9572                1,
9573                phrases(language),
9574                None,
9575            );
9576            t.last_error.or(t.hold_reason).unwrap_or_default()
9577        };
9578        assert!(
9579            reason("en").starts_with("the graph stopped at `"),
9580            "{}",
9581            reason("en")
9582        );
9583        assert!(reason("ja").starts_with("グラフが終端状態に達しないまま"));
9584        assert!(reason("日本語").contains("boom"));
9585        assert_eq!(reason("fr"), reason("en"));
9586    }
9587
9588    #[test]
9589    fn describe_follows_the_run_language_and_keeps_the_run_id() {
9590        let en = describe(&run_state_in(RunStatus::Stalled, "en"));
9591        assert!(en.starts_with("the judging panel lost its quorum"), "{en}");
9592        let ja = describe(&run_state_in(RunStatus::Stalled, "ja"));
9593        assert!(ja.starts_with("審査パネルが定足数を失いました"), "{ja}");
9594        assert!(ja.contains("[run "), "{ja}");
9595        let ended = describe(&run_state_in(RunStatus::Failed, "jp"));
9596        assert!(ended.starts_with("run 終了: "), "{ended}");
9597        let mut de = run_state_in(RunStatus::Failed, "de");
9598        let mut en = run_state_in(RunStatus::Failed, "en");
9599        de.id = "same".to_owned();
9600        en.id = "same".to_owned();
9601        assert_eq!(describe(&de), describe(&en));
9602    }
9603
9604    #[test]
9605    fn handover_refusals_follow_the_language_and_keep_the_detail_apart() {
9606        use crate::handover::Refused;
9607        let cases = [
9608            Refused::Foreign {
9609                branch: "b".into(),
9610                path: "/w/x".into(),
9611                why: "made by hand".into(),
9612            },
9613            Refused::Unsafe {
9614                branch: "b".into(),
9615                path: "/w/x".into(),
9616                why: "its worktree has uncommitted changes (a.rs)".into(),
9617            },
9618            Refused::ReleaseFailed {
9619                branch: "b".into(),
9620                path: "/w/x".into(),
9621                run: "ab12".into(),
9622            },
9623        ];
9624        for r in &cases {
9625            let en = (phrases("en").handover_refused)(r);
9626            assert_eq!(en, r.to_string());
9627            let ja = (phrases("ja").handover_refused)(r);
9628            assert!(
9629                !ja.contains("is checked out") && !ja.contains("try again"),
9630                "{ja}"
9631            );
9632            assert!(ja.contains("`b`") && ja.contains("/w/x"), "{ja}");
9633            if let Refused::Foreign { why, .. } | Refused::Unsafe { why, .. } = r {
9634                assert!(ja.contains(&format!("(詳細: {why})")), "{ja}");
9635            }
9636        }
9637        assert!(phrases("en").handover_hint.contains("release the task"));
9638        assert!(phrases("ja").handover_hint.contains("解放"));
9639    }
9640
9641    #[test]
9642    fn describe_translates_the_unanswered_reviewer_stop_only_in_ja() {
9643        let build = |lang: &str| {
9644            let mut s = run_state_in(RunStatus::Blocked, lang);
9645            s.id = "same".to_owned();
9646            s.config.graph.review_rounds = 3;
9647            let mut r = review_round(3);
9648            r.expected = 3;
9649            r.answered = 1;
9650            s.reviews.push(r);
9651            s.event(
9652                "review",
9653                "2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean",
9654            );
9655            s
9656        };
9657        let en = describe(&build("en"));
9658        assert!(en.contains("(review: 2 reviewer seat(s) never answered after 3 rounds; refusing to call it clean)"), "{en}");
9659        let ja = describe(&build("ja"));
9660        assert!(ja.contains("2 席のレビュアーが 3 ラウンド"), "{ja}");
9661        assert!(!ja.contains("never answered"), "{ja}");
9662        assert!(ja.contains("[run "), "{ja}");
9663
9664        // An incomplete panel whose verification failed is a different stop:
9665        // the real event must survive in ja too.
9666        let mut failed = build("ja");
9667        failed.reviews[0].e2e.push(crate::run::CommandOutcome {
9668            command: "cargo test".to_owned(),
9669            code: Some(1),
9670            output_tail: String::new(),
9671            duration_ms: 0,
9672            resource_blocked: false,
9673            ..Default::default()
9674        });
9675        failed.event("review", "stopped; e2e failed: cargo test");
9676        let ja = describe(&failed);
9677        assert!(ja.contains("stopped; e2e failed: cargo test"), "{ja}");
9678        assert!(!ja.contains("席のレビュアー"), "{ja}");
9679    }
9680
9681    #[test]
9682    fn refusals_and_recovery_prose_follow_the_language() {
9683        let home = crate::run::test_home();
9684        let t = held_task_with("r1");
9685        let q = action_question(
9686            "r1",
9687            ask::ChoiceAction::Resume {
9688                run: "r1".to_owned(),
9689            },
9690        );
9691        let refuse = |p: &Phrases| match decide_action(&home, &t, &q, p, |_: &str| bail!("gone")) {
9692            ActionDecision::Refuse(s) => s,
9693            other => panic!("{other:?}"),
9694        };
9695        assert!(refuse(phrases("en")).contains("could not be read: gone"));
9696        assert!(refuse(phrases("ja")).contains("読み込めませんでした: gone"));
9697        assert_eq!(refuse(phrases("fr")), refuse(phrases("en")));
9698
9699        let mut held = task();
9700        reclaim(&mut held, None, 2, "ja");
9701        assert!(held.hold_reason.unwrap().contains("保留にしました"));
9702        let mut held = task();
9703        reclaim(&mut held, None, 2, "xx");
9704        assert!(held.hold_reason.unwrap().contains("held for a human"));
9705    }
9706
9707    fn run_state(status: RunStatus) -> RunState {
9708        let mut state = RunState::new(
9709            PathBuf::from("/repo"),
9710            "main".to_owned(),
9711            "abc1234def".to_owned(),
9712            "add retries".to_owned(),
9713            Config::default(),
9714        );
9715        state.status = status;
9716        state
9717    }
9718
9719    #[test]
9720    fn settlement_audits_the_loaded_run_instead_of_reloading_a_stale_snapshot() {
9721        crate::run::pin_test_home();
9722        let dir = tempfile::tempdir().unwrap();
9723        let mut state = run_state(RunStatus::Blocked);
9724        state.id = "20260101-000000-audit".into();
9725        state.save_under(dir.path()).unwrap();
9726        let mut t = task();
9727        t.start(state.id.clone());
9728        // The final state is newer than disk, as when a worker settles its
9729        // in-memory outcome or recovery is passed an already loaded run.
9730        state.status = RunStatus::Ready;
9731        settle_and_diagnose(
9732            &mut t,
9733            unstarted_verdict(RunStatus::Ready),
9734            "Verified local delivery",
9735            2,
9736            &state,
9737        );
9738        let completion = t.completion_history.last().unwrap();
9739        assert_eq!(completion.actor, CompletionActor::DaemonSettle);
9740        assert_eq!(completion.prior_status, TaskStatus::Running);
9741        assert_eq!(
9742            completion.reason.as_deref(),
9743            Some("Verified local delivery")
9744        );
9745        let snapshot = completion.run.as_ref().unwrap();
9746        assert_eq!(snapshot.id, state.id);
9747        assert_eq!(snapshot.status, Some(RunStatus::Ready));
9748        assert_eq!(
9749            RunState::load_under(&state.id, dir.path()).unwrap().status,
9750            RunStatus::Blocked,
9751            "settlement records the actual outcome without rewriting run history"
9752        );
9753    }
9754
9755    fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
9756        Candidate {
9757            index: 0,
9758            label,
9759            agent: "claude".to_owned(),
9760            branch: format!("magi/x/{label}"),
9761            worktree: PathBuf::from("/repo"),
9762            summary: summary.to_owned(),
9763            stat: String::new(),
9764            files: 0,
9765            commits: usize::from(!empty),
9766            empty,
9767            failed: failed.map(str::to_owned),
9768            verified_noop: None,
9769            duration_ms: 0,
9770            folded: false,
9771        }
9772    }
9773
9774    #[test]
9775    fn diagnostic_names_the_failing_gate_checks_and_their_output() {
9776        let mut state = run_state(RunStatus::Blocked);
9777        state.gate = vec![
9778            CommandOutcome {
9779                command: "cargo make check".to_owned(),
9780                code: Some(0),
9781                output_tail: "ok".to_owned(),
9782                duration_ms: 0,
9783                resource_blocked: false,
9784                ..Default::default()
9785            },
9786            CommandOutcome {
9787                command: "cargo test".to_owned(),
9788                code: Some(101),
9789                output_tail: "thread 'x' panicked: assertion failed".to_owned(),
9790                duration_ms: 0,
9791                resource_blocked: false,
9792                ..Default::default()
9793            },
9794        ];
9795        let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
9796        assert!(d.contains("cargo test"), "{d}");
9797        assert!(
9798            !d.contains("cargo make check"),
9799            "a passing check is not a diagnostic: {d}"
9800        );
9801        assert!(d.contains("assertion failed"), "{d}");
9802    }
9803
9804    #[test]
9805    fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
9806        let mut state = run_state(RunStatus::Blocked);
9807        state.event(
9808            "land",
9809            "stopped: the fixer produced no commit while 2 check(s) were failing \
9810             (build, lint); stopping instead of looping on an unchanged tree",
9811        );
9812        let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
9813        assert!(d.contains("build"), "{d}");
9814        assert!(d.contains("lint"), "{d}");
9815        assert!(d.contains("fixer produced no commit"), "{d}");
9816    }
9817
9818    #[test]
9819    fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
9820        // `describe`'s output becomes `Task::last_error` verbatim, and the
9821        // phone renders that in the same alarm-styled box an ordinary
9822        // failure gets. A bare `verified_noop` there would read exactly like
9823        // the failure this status exists to be told apart from.
9824        let state = run_state(RunStatus::VerifiedNoop);
9825        let d = describe(&state);
9826        assert!(
9827            d.contains("agent-verified no-op"),
9828            "expected the display label, not the wire spelling: {d}"
9829        );
9830        assert!(!d.contains("verified_noop"), "{d}");
9831    }
9832
9833    #[test]
9834    fn diagnostic_keeps_gate_panic_before_large_backtrace() {
9835        let mut state = run_state(RunStatus::Failed);
9836        state.gate.push(crate::run::CommandOutcome {
9837            command: "cargo test".into(),
9838            code: Some(101),
9839            output_tail: format!(
9840                "---- widget stdout ----\nwidget log\nthread 'widget' panicked at widget.rs:12:\nassertion failed: widget missing\n{}test result: FAILED\n",
9841                "  41: 0x1234 - backtrace frame\n".repeat(10000)
9842            ),
9843            duration_ms: 1,
9844            resource_blocked: false,
9845            ..Default::default()
9846        });
9847        let d = diagnostic(&state).unwrap();
9848        assert!(d.contains("panicked at widget.rs:12"), "{d}");
9849        assert!(d.contains("assertion failed: widget missing"));
9850        assert!(d.contains("widget log"));
9851    }
9852
9853    #[test]
9854    fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
9855        // The whole point of the feature: a run held as "no candidate produced
9856        // a change" can mean the implementer actually finished the task and
9857        // only left a clean local tree behind - see AGENTS.md on this exact
9858        // failure mode. The diagnostic has to carry what the agent actually
9859        // said, not just the fact that nothing was there to judge.
9860        let mut state = run_state(RunStatus::Failed);
9861        state.candidates = vec![candidate(
9862            'A',
9863            "opened pull request #42, merged it, tagged v1.2.3 and published the release",
9864            true,
9865            None,
9866        )];
9867        let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
9868        assert!(d.contains("candidate A"), "{d}");
9869        assert!(d.contains("tagged v1.2.3"), "{d}");
9870    }
9871
9872    #[test]
9873    fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
9874        let mut state = run_state(RunStatus::Failed);
9875        state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
9876        let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
9877        assert!(d.contains("candidate A"), "{d}");
9878        assert!(d.contains("agent timed out"), "{d}");
9879    }
9880
9881    #[test]
9882    fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
9883        // A viable candidate existed, the gate never ran, and nothing land
9884        // said matches - `Task::last_error` is left to explain this one alone.
9885        let mut state = run_state(RunStatus::Failed);
9886        state.candidates = vec![candidate('A', "did the work", false, None)];
9887        assert!(diagnostic(&state).is_none());
9888    }
9889
9890    #[test]
9891    fn diagnostic_is_bounded_however_much_a_run_printed() {
9892        let mut state = run_state(RunStatus::Blocked);
9893        state.gate = vec![
9894            CommandOutcome {
9895                command: "cargo test".to_owned(),
9896                code: Some(101),
9897                output_tail: "x".repeat(50_000),
9898                duration_ms: 0,
9899                resource_blocked: false,
9900                ..Default::default()
9901            },
9902            CommandOutcome {
9903                command: "cargo clippy".to_owned(),
9904                code: Some(1),
9905                output_tail: "y".repeat(50_000),
9906                duration_ms: 0,
9907                resource_blocked: false,
9908                ..Default::default()
9909            },
9910        ];
9911        state.candidates = vec![
9912            candidate('A', &"z".repeat(50_000), true, None),
9913            candidate('B', &"w".repeat(50_000), true, None),
9914        ];
9915        let d = diagnostic(&state).expect("plenty here to diagnose");
9916        assert!(
9917            d.len() <= DIAGNOSTIC_MAX,
9918            "diagnostic grew to {} bytes, unbounded",
9919            d.len()
9920        );
9921    }
9922
9923    #[test]
9924    fn selected_delivery_guards_survive_recovery_failure_accounting() {
9925        for status in [RunStatus::Ready, RunStatus::Blocked, RunStatus::Failed] {
9926            let mut t = task();
9927            let mut state = run_state(status);
9928            t.pr_recovery = Some(crate::pr_recovery::Selection {
9929                url: "url".into(),
9930                branch: format!("magi/task-{}", t.id),
9931                head: "a".repeat(40),
9932                source_head: None,
9933                source_run: None,
9934                source_proof: None,
9935                disposition: Some(crate::pr_recovery::Disposition::Land),
9936                instruction: t.instruction.clone(),
9937                approved_at: Timestamp::now(),
9938            });
9939            state.pr_recovery = t.pr_recovery.clone();
9940            t.start(state.id.clone());
9941            settle_and_diagnose(
9942                &mut t,
9943                Verdict {
9944                    status,
9945                    left_pr: false,
9946                    quota_hit: false,
9947                    parked: false,
9948                    no_viable_candidates: false,
9949                },
9950                "delivery stopped",
9951                5,
9952                &state,
9953            );
9954            assert_eq!(t.status, TaskStatus::Held);
9955            let reason = t.hold_reason.as_deref().unwrap();
9956            if status == RunStatus::Ready {
9957                assert!(reason.contains("Selected PR delivery is incomplete"));
9958                assert!(t.recovery_budget.is_none());
9959            } else {
9960                assert!(reason.contains("Selected recovery stopped"));
9961                assert_eq!(t.recovery_budget.as_ref().unwrap().failures, 1);
9962            }
9963            assert!(t.pr_recovery.is_some());
9964        }
9965    }
9966
9967    #[test]
9968    fn base_recovery_settlement_holds_without_replacement_or_duplicate_notice_cause() {
9969        let mut state = run_state(RunStatus::Voting);
9970        state.base_sync = Some(crate::run::BaseSync {
9971            tip: "base-tip".into(),
9972            behind: 3,
9973            attempts: 4,
9974            conflict: Some("base stopped".into()),
9975            already_in: None,
9976        });
9977        state.record_base_sync_stop("candidate-head");
9978        let mut t = task();
9979        t.start(state.id.clone());
9980        let verdict = Verdict {
9981            status: RunStatus::Blocked,
9982            left_pr: false,
9983            quota_hit: false,
9984            parked: false,
9985            no_viable_candidates: false,
9986        };
9987        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9988        assert_eq!(
9989            t.status,
9990            TaskStatus::Held,
9991            "unspent task attempts cannot start another competition"
9992        );
9993        let at = t.held_at;
9994        let cause = t.hold_notice_cause.clone();
9995        state.begin_pass();
9996        t.release_operator("test-resume", None);
9997        t.start(state.id.clone());
9998        settle_and_diagnose(&mut t, verdict, "base stopped", 10, &state);
9999        assert_eq!(t.status, TaskStatus::Held);
10000        assert_eq!(t.held_at, at);
10001        assert_eq!(t.hold_notice_cause, cause);
10002    }
10003
10004    #[test]
10005    fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
10006        let mut state = run_state(RunStatus::Blocked);
10007        state.gate = vec![CommandOutcome {
10008            command: "cargo test".to_owned(),
10009            code: Some(101),
10010            output_tail: "assertion failed".to_owned(),
10011            duration_ms: 0,
10012            resource_blocked: false,
10013            ..Default::default()
10014        }];
10015        let verdict = Verdict {
10016            status: RunStatus::Blocked,
10017            left_pr: false,
10018            quota_hit: false,
10019            parked: false,
10020            no_viable_candidates: false,
10021        };
10022
10023        // Attempt one of two still has a retry coming: no diagnostic yet, the
10024        // task is going to run again and this run's evidence would go stale.
10025        let mut t = task();
10026        t.start("run-1".to_owned());
10027        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
10028        assert_eq!(t.status, TaskStatus::Failed);
10029        assert!(t.diagnostic.is_none());
10030
10031        // Attempt two exhausts the budget: now it is held, and the
10032        // diagnostic is what `magi task show` has to say more than one line.
10033        t.start("run-2".to_owned());
10034        settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
10035        assert_eq!(t.status, TaskStatus::Held);
10036        let d = t.diagnostic.expect("a held task must carry its diagnostic");
10037        assert!(d.contains("cargo test"), "{d}");
10038    }
10039
10040    fn verified_noop_run_state() -> RunState {
10041        let mut state = run_state(RunStatus::VerifiedNoop);
10042        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":[]}"#;
10043        let mut c = candidate('A', summary, true, None);
10044        c.verified_noop = Some(summary.to_owned());
10045        state.candidates = vec![c];
10046        state
10047    }
10048
10049    #[test]
10050    fn a_held_task_names_the_open_question_it_is_waiting_on() {
10051        // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
10052        // `magi ask` question settled Held with `hold_reason: null`, so the
10053        // notification said nothing actionable. `note_open_question` should
10054        // append the question id to whatever `handed_off` already wrote.
10055        crate::run::pin_test_home();
10056        let home = crate::run::home();
10057        let state = verified_noop_run_state();
10058        let mut q = ask::Question::new(
10059            state.id.clone(),
10060            "implement".to_owned(),
10061            "impl-A".to_owned(),
10062            "is this really a no-op?".to_owned(),
10063            String::new(),
10064            Vec::new(),
10065        );
10066        Questions::at(home.join("questions")).put(&mut q).unwrap();
10067
10068        let verdict = Verdict {
10069            status: RunStatus::VerifiedNoop,
10070            left_pr: false,
10071            quota_hit: false,
10072            parked: false,
10073            no_viable_candidates: true,
10074        };
10075        let mut t = task();
10076        t.start(state.id.clone());
10077        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
10078
10079        assert_eq!(t.status, TaskStatus::Held);
10080        let reason = t.hold_reason.expect("a held task must record why");
10081        assert!(
10082            reason.starts_with("run ended agent-verified no-op"),
10083            "the original settle reason must survive unchanged: {reason}"
10084        );
10085        assert!(
10086            reason.contains(q.short()),
10087            "the open question's id must be named so the notice is actionable: {reason}"
10088        );
10089    }
10090
10091    #[test]
10092    fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
10093        crate::run::pin_test_home();
10094        let state = verified_noop_run_state();
10095
10096        let verdict = Verdict {
10097            status: RunStatus::VerifiedNoop,
10098            left_pr: false,
10099            quota_hit: false,
10100            parked: false,
10101            no_viable_candidates: true,
10102        };
10103        let mut t = task();
10104        t.start(state.id.clone());
10105        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
10106
10107        assert_eq!(t.status, TaskStatus::Held);
10108        assert_eq!(
10109            t.hold_reason.as_deref(),
10110            Some("run ended agent-verified no-op"),
10111            "nothing to append when the question was already answered or never asked"
10112        );
10113    }
10114
10115    #[test]
10116    fn inconsistent_verified_noop_state_settles_and_reclaims_as_ordinary_failure() {
10117        crate::run::pin_test_home();
10118
10119        // Case 1: Saved `VerifiedNoop` run carrying the exact operational
10120        // regression prose instead of valid structured evidence.
10121        let mut bad = run_state(RunStatus::VerifiedNoop);
10122        let mut c = candidate(
10123            'A',
10124            "NO CHANGE NEEDED: Not established. No source changes, commit, or reproduction checks were completed. The reported Git configuration lock contention remains unresolved.",
10125            true,
10126            None,
10127        );
10128        c.verified_noop = Some("Not established.".to_owned());
10129        bad.candidates = vec![c];
10130
10131        let mut t = task();
10132        t.start(bad.id.clone());
10133        let verdict = Verdict {
10134            status: RunStatus::VerifiedNoop,
10135            left_pr: false,
10136            quota_hit: true,
10137            parked: false,
10138            no_viable_candidates: true,
10139        };
10140        settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 3, &bad);
10141        assert_eq!(
10142            t.status,
10143            TaskStatus::Failed,
10144            "inconsistent verified_noop must retry as Failed when attempts remain"
10145        );
10146        assert_eq!(t.attempts, 1);
10147        assert_eq!(
10148            t.last_error.as_deref(),
10149            Some("no-change result lacks verified evidence")
10150        );
10151        assert!(t.hold_reason.is_none());
10152
10153        // Case 2: Reclaim on an inconsistent `VerifiedNoop` state with
10154        // attempts exhausted holds as `failed`, never `verified_noop`, and
10155        // never auto-closes to `Done`.
10156        let mut t_exhausted = task();
10157        t_exhausted.start(bad.id.clone());
10158        reclaim(&mut t_exhausted, Some(bad.clone()), 1, "en");
10159        assert_eq!(t_exhausted.status, TaskStatus::Held);
10160        assert_eq!(t_exhausted.attempts, 1);
10161        assert_eq!(
10162            t_exhausted
10163                .hold_notice_cause
10164                .as_ref()
10165                .map(|c| c.stage.as_str()),
10166            Some("failed"),
10167            "exhausted inconsistent verified_noop must not emit a verified_noop notice cause"
10168        );
10169        let diag = t_exhausted.diagnostic.as_deref().unwrap_or("");
10170        assert!(
10171            !diag.contains("agent-verified no-op"),
10172            "diagnostic must not mislabel an invalid claim as verified no-op: {diag}"
10173        );
10174        assert!(diag.contains("Not established"), "{diag}");
10175    }
10176
10177    #[test]
10178    fn saved_noop_declaration_is_the_evidence_not_the_display_summary() {
10179        let mut state = verified_noop_run_state();
10180        let summary = state.candidates[0].summary.clone();
10181        state.candidates[0].summary = "Already satisfied.".to_owned();
10182        assert!(state.all_candidates_verified_noop());
10183
10184        state.candidates[0].summary = summary;
10185        state.candidates[0].verified_noop = Some("Historical prose only.".to_owned());
10186        assert!(!state.all_candidates_verified_noop());
10187    }
10188
10189    #[test]
10190    fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
10191        crate::run::pin_test_home();
10192        let mut first = run_state(RunStatus::Blocked);
10193        first.id = "20260101-000000-sup1".to_owned();
10194        first.save().unwrap();
10195        let mut second = run_state(RunStatus::Merged);
10196        second.id = "20260101-000000-sup2".to_owned();
10197        second.save().unwrap();
10198
10199        let mut t = task();
10200        t.runs = vec![first.id.clone(), second.id.clone()];
10201        t.status = TaskStatus::Done;
10202
10203        supersede_prior_runs(&t, &crate::run::home());
10204
10205        assert_eq!(
10206            RunState::load(&first.id).unwrap().status,
10207            RunStatus::Superseded,
10208            "the first attempt's Blocked no longer needs anyone's attention"
10209        );
10210        assert_eq!(
10211            RunState::load(&second.id).unwrap().status,
10212            RunStatus::Merged,
10213            "the run that actually succeeded is left exactly as it was"
10214        );
10215    }
10216
10217    #[test]
10218    fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
10219        // `is_working_on` alone only proves a *daemon* claim; a `magi run
10220        // --resume` invoked by hand outside the daemon never touches
10221        // `daemon.json` at all, so it would look identical to a genuinely
10222        // idle run without also consulting `RunState::liveness`, which reads
10223        // this run's own recorded `driver_pid` instead.
10224        crate::run::pin_test_home();
10225        let mut first = run_state(RunStatus::Blocked);
10226        first.id = "20260101-000000-sup9".to_owned();
10227        // This test process's own pid: guaranteed alive without needing a
10228        // real second process or daemon.
10229        first.driver_pid = Some(std::process::id());
10230        first.driver_started_at = Some(
10231            crate::proc::process_started_at(std::process::id())
10232                .expect("this test process's own start time must be queryable"),
10233        );
10234        first.save().unwrap();
10235        let mut second = run_state(RunStatus::Merged);
10236        second.id = "20260101-000000-supa".to_owned();
10237        second.save().unwrap();
10238
10239        let mut t = task();
10240        t.runs = vec![first.id.clone(), second.id.clone()];
10241        t.status = TaskStatus::Done;
10242
10243        supersede_prior_runs(&t, &crate::run::home());
10244
10245        assert_eq!(
10246            RunState::load(&first.id).unwrap().status,
10247            RunStatus::Blocked,
10248            "a live driver_pid means something is still actually working this run, \
10249             even though no daemon claims it - rewriting under it would just be \
10250             undone the next time that process saves"
10251        );
10252    }
10253
10254    #[test]
10255    fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
10256        // The first resweep must skip a still-live attempt exactly like
10257        // `supersede_prior_runs` itself does; a later resweep, once that
10258        // process is no longer actually driving it, is what closes the gap
10259        // `supersede_prior_runs` alone leaves - a task only ever reaches
10260        // `Done` once, so nothing else would ever look at this run again.
10261        let dir = tempfile::tempdir().unwrap();
10262        let home = dir.path().to_path_buf();
10263        let queue = Queue::at(dir.path().join("queue"));
10264
10265        let mut first = run_state(RunStatus::Blocked);
10266        first.id = "20260101-000000-supd".to_owned();
10267        first.driver_pid = Some(std::process::id());
10268        first.driver_started_at = Some(
10269            crate::proc::process_started_at(std::process::id())
10270                .expect("this test process's own start time must be queryable"),
10271        );
10272        first.save_under(&home).unwrap();
10273        let mut second = run_state(RunStatus::Merged);
10274        second.id = "20260101-000000-supe".to_owned();
10275        second.save_under(&home).unwrap();
10276
10277        let mut t = task();
10278        t.runs = vec![first.id.clone(), second.id.clone()];
10279        t.status = TaskStatus::Done;
10280        queue.put(&mut t).unwrap();
10281
10282        resweep_superseded_attempts(&queue, &home);
10283        assert_eq!(
10284            RunState::load_under(&first.id, &home).unwrap().status,
10285            RunStatus::Blocked,
10286            "still live on the first pass, so still untouched"
10287        );
10288
10289        // Stand in for the manual process no longer being the one driving
10290        // this run: same pid (this test process really is still alive), but
10291        // an identity marker that no longer matches it - see
10292        // `RunState::liveness`'s own doc for why a mismatched
10293        // `driver_started_at` reads as `Dead`, not merely `Unknown`.
10294        let mut stale = RunState::load_under(&first.id, &home).unwrap();
10295        stale.driver_started_at = Some("1".to_owned());
10296        stale.save_under(&home).unwrap();
10297
10298        resweep_superseded_attempts(&queue, &home);
10299        assert_eq!(
10300            RunState::load_under(&first.id, &home).unwrap().status,
10301            RunStatus::Superseded,
10302            "the second pass catches up what the first one correctly skipped"
10303        );
10304    }
10305
10306    #[test]
10307    fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
10308        crate::run::pin_test_home();
10309        let mut first = run_state(RunStatus::Blocked);
10310        first.id = "20260101-000000-sup3".to_owned();
10311        first.save().unwrap();
10312        let mut second = run_state(RunStatus::Blocked);
10313        second.id = "20260101-000000-sup4".to_owned();
10314        second.save().unwrap();
10315
10316        let mut t = task();
10317        t.runs = vec![first.id.clone(), second.id.clone()];
10318        // Still retrying: nothing about this task's story is settled yet, so
10319        // neither Blocked run may be relabelled, even though a later attempt
10320        // already exists.
10321        t.status = TaskStatus::Failed;
10322
10323        supersede_prior_runs(&t, &crate::run::home());
10324
10325        assert_eq!(
10326            RunState::load(&first.id).unwrap().status,
10327            RunStatus::Blocked
10328        );
10329        assert_eq!(
10330            RunState::load(&second.id).unwrap().status,
10331            RunStatus::Blocked
10332        );
10333    }
10334
10335    #[test]
10336    fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
10337        // `magi task done` (or the API's equivalent) can close a task with no
10338        // run of its own ever having succeeded - there is nothing here that
10339        // counts as "the attempt that finished it", so nothing is rewritten.
10340        crate::run::pin_test_home();
10341        let mut first = run_state(RunStatus::Blocked);
10342        first.id = "20260101-000000-sup5".to_owned();
10343        first.save().unwrap();
10344
10345        let mut t = task();
10346        t.runs = vec![first.id.clone()];
10347        t.status = TaskStatus::Done;
10348
10349        supersede_prior_runs(&t, &crate::run::home());
10350
10351        assert_eq!(
10352            RunState::load(&first.id).unwrap().status,
10353            RunStatus::Blocked,
10354            "a single-attempt task has no earlier run to supersede"
10355        );
10356    }
10357
10358    #[test]
10359    fn supersede_prior_runs_preserves_blocked_work_after_an_audited_manual_close() {
10360        for status in [
10361            RunStatus::Blocked,
10362            RunStatus::Stalled,
10363            RunStatus::Failed,
10364            RunStatus::Ready,
10365            RunStatus::Merged,
10366        ] {
10367            let dir = tempfile::tempdir().unwrap();
10368            let home = dir.path();
10369            let mut first = run_state(RunStatus::Blocked);
10370            first.id = "20260101-000000-supb".to_owned();
10371            first.save_under(home).unwrap();
10372            let mut second = run_state(status);
10373            second.id = "20260101-000000-supc".to_owned();
10374            second.save_under(home).unwrap();
10375
10376            let mut t = task();
10377            t.runs = vec![first.id.clone(), second.id.clone()];
10378            t.hold_manual(Some("Unmerged work remains".into()));
10379            let mut context = CompletionContext::new(
10380                CompletionActor::Cli,
10381                Some("Discard the unmerged attempts".into()),
10382                home,
10383                &t,
10384            );
10385            context.discard = true;
10386            t.succeed(context);
10387            assert_eq!(t.completion_history.len(), 1);
10388
10389            supersede_prior_runs(&t, home);
10390
10391            assert_eq!(
10392                RunState::load_under(&first.id, home).unwrap().status,
10393                RunStatus::Blocked,
10394                "an audited manual close is not proof the earlier work landed"
10395            );
10396            assert_eq!(
10397                RunState::load_under(&second.id, home).unwrap().status,
10398                status,
10399                "the latest attempt retains its actual outcome"
10400            );
10401        }
10402    }
10403
10404    #[test]
10405    fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
10406        // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
10407        // to look" - `Failed` and `VerifiedNoop` are already their own
10408        // terminal answers and must not be relabelled into a third one.
10409        crate::run::pin_test_home();
10410        let mut failed = run_state(RunStatus::Failed);
10411        failed.id = "20260101-000000-sup6".to_owned();
10412        failed.save().unwrap();
10413        let mut noop = run_state(RunStatus::VerifiedNoop);
10414        noop.id = "20260101-000000-sup7".to_owned();
10415        noop.save().unwrap();
10416        let mut winner = run_state(RunStatus::Ready);
10417        winner.id = "20260101-000000-sup8".to_owned();
10418        winner.save().unwrap();
10419
10420        let mut t = task();
10421        t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
10422        t.status = TaskStatus::Done;
10423
10424        supersede_prior_runs(&t, &crate::run::home());
10425
10426        assert_eq!(
10427            RunState::load(&failed.id).unwrap().status,
10428            RunStatus::Failed
10429        );
10430        assert_eq!(
10431            RunState::load(&noop.id).unwrap().status,
10432            RunStatus::VerifiedNoop
10433        );
10434    }
10435
10436    fn approval_question(run: &str) -> ask::Question {
10437        ask::Question::new(
10438            run.to_owned(),
10439            land::APPROVAL_NODE.to_owned(),
10440            "land".to_owned(),
10441            "merge?".to_owned(),
10442            String::new(),
10443            vec!["merge".to_owned(), "hold".to_owned()],
10444        )
10445    }
10446
10447    #[test]
10448    fn land_resume_state_leaves_a_fresh_open_question_waiting() {
10449        crate::run::pin_test_home();
10450        let mut state = run_state(RunStatus::Landing);
10451        state.id = "20260101-000000-fre1".to_owned();
10452        state.parked = true;
10453        state.save().unwrap();
10454        ask::Questions::open()
10455            .put(&mut approval_question(&state.id))
10456            .unwrap();
10457
10458        let mut t = task();
10459        t.runs.push(state.id.clone());
10460        assert_eq!(
10461            land_resume_state(&t),
10462            LandResume::StillWaiting,
10463            "nobody has answered and the timeout has not passed"
10464        );
10465    }
10466
10467    #[test]
10468    fn land_resume_state_waits_on_a_withheld_text_question_then_resumes() {
10469        crate::run::pin_test_home();
10470        let mut state = run_state(RunStatus::Gating);
10471        state.id = "20260101-000000-gt01".to_owned();
10472        state.parked = true;
10473        state.config.graph.answer_timeout = 60;
10474        state.github_text = Some(crate::run::GithubTextAsk {
10475            rewrite: None,
10476            fingerprint: "f".into(),
10477            title: true,
10478            body: false,
10479            categories: vec!["title-language".into()],
10480            question: None,
10481            asks: 1,
10482            resolved: false,
10483            chosen_title: None,
10484            choice: None,
10485            publication: None,
10486        });
10487        state.save().unwrap();
10488        let store = ask::Questions::open();
10489        let mut q = ask::Question::new(
10490            state.id.clone(),
10491            crate::github_text::ASK_NODE.to_owned(),
10492            crate::github_text::ASK_SEAT.to_owned(),
10493            "s".into(),
10494            String::new(),
10495            vec!["use fallback".into()],
10496        );
10497        store.put(&mut q).unwrap();
10498        let mut t = task();
10499        t.runs.push(state.id.clone());
10500        assert_eq!(land_resume_state(&t), LandResume::StillWaiting);
10501        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10502        store.put(&mut q).unwrap();
10503        assert_eq!(land_resume_state(&t), LandResume::Ready);
10504        assert!(!store.get(&q.id).unwrap().status.open());
10505        // Once decided, a parked run is an ordinary candidate again.
10506        state.github_text.as_mut().unwrap().resolved = true;
10507        state.save().unwrap();
10508        assert_eq!(land_resume_state(&t), LandResume::NotLanding);
10509    }
10510
10511    #[test]
10512    fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
10513        // `ask::ask_and_wait`'s own deadline used to retire a question
10514        // nobody answered; land's approval bypasses that wait (see
10515        // `land::approval_gate`), so this is now the only place
10516        // `graph.answer_timeout` is enforced for a land approval at all.
10517        crate::run::pin_test_home();
10518        let mut state = run_state(RunStatus::Landing);
10519        state.id = "20260101-000000-exp1".to_owned();
10520        state.parked = true;
10521        state.config.graph.answer_timeout = 60;
10522        state.save().unwrap();
10523
10524        let store = ask::Questions::open();
10525        let mut q = approval_question(&state.id);
10526        q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
10527        store.put(&mut q).unwrap();
10528
10529        let mut t = task();
10530        t.runs.push(state.id.clone());
10531        assert_eq!(
10532            land_resume_state(&t),
10533            LandResume::Ready,
10534            "an expired question must not be waited on forever"
10535        );
10536
10537        let after = store.get(&q.id).unwrap();
10538        assert!(
10539            !after.status.open(),
10540            "the question is abandoned, not silently ignored"
10541        );
10542        assert!(
10543            after.resolution().is_none(),
10544            "an abandoned question is not read as a decision"
10545        );
10546    }
10547
10548    #[test]
10549    fn reclaim_settles_a_running_task_against_its_last_run() {
10550        let mut t = task();
10551        t.start("20260904-000000-4043".to_owned());
10552        reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2, "en");
10553        assert_eq!(
10554            t.status,
10555            TaskStatus::Done,
10556            "a run that actually finished must not stay `running` forever"
10557        );
10558    }
10559
10560    #[test]
10561    fn reclaim_preserves_dispatched_inquiries_until_a_committed_pass() {
10562        let dir = tempfile::tempdir().unwrap();
10563        let queue = Queue::at(dir.path().join("queue"));
10564        let mut task = task();
10565        let mut run = run_state(RunStatus::Blocked);
10566        run.reserve_under(dir.path()).unwrap();
10567        run.driver_exited = true;
10568        run.save_under(dir.path()).unwrap();
10569        queue.put(&mut task).unwrap();
10570        let stale = task.clone();
10571        task.resume_override = Some(crate::queue::OperatorResume {
10572            question_id: "pending-resume".into(),
10573            at: Timestamp::now(),
10574            conductor_rehold: None,
10575            forced: true,
10576            pinned_run: Some(run.id.clone()),
10577        });
10578        task.start(run.id.clone());
10579        queue.put(&mut task).unwrap();
10580        // Discard every in-memory handoff, as a worker death before execute does.
10581        let mut recovered = queue.get(&task.id).unwrap();
10582        let disk = RunState::load_under(&run.id, dir.path()).unwrap();
10583        reclaim(&mut recovered, Some(disk), 2, "en");
10584        queue.put(&mut recovered).unwrap();
10585        assert!(recovered.resume_override.is_none());
10586        assert_eq!(
10587            recovered.dispatched_resumes.get("pending-resume"),
10588            Some(&run.id)
10589        );
10590        let mut stale = stale;
10591        queue.put(&mut stale).unwrap();
10592        assert_eq!(
10593            stale.dispatched_resumes, recovered.dispatched_resumes,
10594            "a stale task writer cannot erase dispatch ownership"
10595        );
10596        let mut resumed = RunState::load_under(&run.id, dir.path()).unwrap();
10597        assert!(resumed.decision_starts.is_empty());
10598        resumed.carry_dispatched_resumes(&queue.get(&task.id).unwrap());
10599        assert!(
10600            resumed.decision_starts.is_empty(),
10601            "handoff is not execution proof"
10602        );
10603        resumed.begin_pass();
10604        resumed.save_under(dir.path()).unwrap();
10605        let mut disk = RunState::load_under(&run.id, dir.path()).unwrap();
10606        assert_eq!(disk.decision_starts.get("pending-resume"), Some(&0));
10607        disk.carry_dispatched_resumes(&recovered);
10608        disk.begin_pass();
10609        assert_eq!(
10610            disk.decision_starts.get("pending-resume"),
10611            Some(&0),
10612            "later execution must preserve the original pass receipt"
10613        );
10614    }
10615
10616    #[test]
10617    fn reclaim_maps_a_parked_run_to_parked_without_touching_last_error() {
10618        let mut t = task();
10619        t.start("20260904-000000-4043".to_owned());
10620        t.last_error = Some("earlier trouble".to_owned());
10621        let mut state = run_state(RunStatus::Judging);
10622        state.parked = true;
10623        reclaim(&mut t, Some(state), 1, "en");
10624        assert_eq!(t.status, TaskStatus::Parked);
10625        assert_eq!(t.attempts, 0, "the park is refunded, even at max_attempts");
10626        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10627        assert!(t.park_reason.is_some());
10628        assert_eq!(t.runs, ["20260904-000000-4043"], "the same run is kept");
10629        assert!(!t.fresh_start);
10630        assert!(t.status.runnable());
10631    }
10632
10633    #[test]
10634    fn settle_parks_a_task_without_a_failure_and_a_new_start_clears_the_reason() {
10635        let mut t = task();
10636        t.start("20260904-000000-4043".to_owned());
10637        t.last_error = Some("earlier trouble".to_owned());
10638        settle(
10639            &mut t,
10640            Verdict {
10641                status: RunStatus::Judging,
10642                left_pr: false,
10643                quota_hit: false,
10644                parked: true,
10645                no_viable_candidates: false,
10646            },
10647            "parked after `judging`",
10648            1,
10649        );
10650        assert_eq!(t.status, TaskStatus::Parked);
10651        assert_eq!(t.attempts, 0);
10652        assert_eq!(t.last_error.as_deref(), Some("earlier trouble"));
10653        assert_eq!(t.park_reason.as_deref(), Some("parked after `judging`"));
10654        assert_eq!(t.schema, crate::queue::SCHEMA);
10655        assert!(
10656            crate::notices::task_held(&t).is_none(),
10657            "a park is not news"
10658        );
10659        t.start("20260904-000000-4043".to_owned());
10660        assert_eq!(t.park_reason, None);
10661    }
10662
10663    #[test]
10664    fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
10665        // A blocked run with attempts left goes back to `Failed`, exactly as
10666        // it would from `attempt` itself - `reclaim` must not invent a second
10667        // policy for a task a daemon merely stopped without reporting.
10668        let mut t = task();
10669        t.start("20260904-000000-4043".to_owned());
10670        reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2, "en");
10671        assert_eq!(t.status, TaskStatus::Failed);
10672        assert!(t.status.runnable());
10673    }
10674
10675    #[test]
10676    fn a_settled_parked_pass_records_its_cause_and_the_refund() {
10677        let mut t = task();
10678        t.start("20260904-000000-4043".to_owned());
10679        assert_eq!(t.attempts, 1);
10680        let mut run = run_state(RunStatus::Implementing);
10681        run.id = "20260904-000000-4043".to_owned();
10682        run.begin_pass();
10683        let cause = crate::run::ParkCause::Upgrade {
10684            from: "0.121.0".to_owned(),
10685            to: Some("0.121.1".to_owned()),
10686        };
10687        run.end_pass_parked(cause.clone());
10688        run.parked = true;
10689        let verdict = Verdict {
10690            status: run.status,
10691            left_pr: false,
10692            quota_hit: false,
10693            parked: true,
10694            no_viable_candidates: false,
10695        };
10696        // A crash after the checkpoint but before queue settlement must
10697        // recover exactly the same scheduling evidence and refund.
10698        let mut orphan = t.clone();
10699        reclaim(&mut orphan, Some(run.clone()), 2, "en");
10700        assert_eq!(orphan.status, TaskStatus::Parked);
10701        assert_eq!(orphan.attempts, 0);
10702        assert_eq!(
10703            orphan.upgrade_resume_key(),
10704            Some((run.passes[0].started_at, orphan.id.as_str()))
10705        );
10706        settle_and_diagnose(&mut t, verdict, "parked", 2, &run);
10707        assert_eq!(t.attempts, 0);
10708        assert_eq!(t.passes.len(), 1);
10709        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10710        assert_eq!(t.passes[0].parked, Some(cause));
10711        assert_eq!(t.passes[0].pass_index, 0);
10712        assert_eq!(t.passes[0].started_at, Some(run.passes[0].started_at));
10713        assert!(t.upgrade_resume_key().is_some());
10714
10715        // A resumed pass that then fails spends its attempt, and the earlier
10716        // pass's entry is untouched.
10717        t.start("20260904-000000-4043".to_owned());
10718        run.begin_pass();
10719        run.status = RunStatus::Failed;
10720        let verdict = Verdict {
10721            status: RunStatus::Failed,
10722            left_pr: false,
10723            quota_hit: false,
10724            parked: false,
10725            no_viable_candidates: false,
10726        };
10727        settle_and_diagnose(&mut t, verdict, "failed", 2, &run);
10728        assert_eq!(t.passes.len(), 2);
10729        assert_eq!(t.passes[0].cost, crate::queue::PassCost::Refunded);
10730        assert_eq!(t.passes[1].cost, crate::queue::PassCost::Spent);
10731        assert_eq!(t.passes[1].pass_index, 1);
10732        assert_eq!(t.attempts, 1);
10733    }
10734
10735    #[test]
10736    fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
10737        let mut t = task();
10738        t.start("20260904-000000-4043".to_owned());
10739        reclaim(&mut t, None, 2, "en");
10740        assert_eq!(t.status, TaskStatus::Held);
10741        assert!(
10742            t.last_error
10743                .as_deref()
10744                .is_some_and(|e| e.contains("running")),
10745            "the operator needs to know why this task was held"
10746        );
10747    }
10748
10749    #[test]
10750    fn sync_base_only_orphan_holds_without_replay_or_attempt_change() {
10751        let dir = tempfile::tempdir().unwrap();
10752        let queue = Queue::at(dir.path().to_path_buf());
10753        let mut task = task();
10754        let run = "20261124-000000-dead";
10755        task.link_run(run);
10756        task.attempts = 2;
10757        task.status = TaskStatus::Running;
10758        task.sync_only = Some(crate::base_sync_only::Request {
10759            run: run.into(),
10760            at: Timestamp::now(),
10761        });
10762        queue.put(&mut task).unwrap();
10763        assert_eq!(
10764            reclaim_orphaned_running(&queue, 3, &Default::default()),
10765            vec![task.id.clone()]
10766        );
10767        let saved = queue.get(&task.id).unwrap();
10768        assert_eq!(saved.status, TaskStatus::Held);
10769        assert_eq!(saved.attempts, 2);
10770        assert_eq!(saved.execution_runs(), [run]);
10771        assert!(
10772            saved
10773                .last_error
10774                .unwrap()
10775                .contains("verification was not allowed")
10776        );
10777        assert!(reclaim_orphaned_running(&queue, 3, &Default::default()).is_empty());
10778    }
10779
10780    #[test]
10781    fn sync_base_only_completed_orphan_holds_without_charging_or_double_refunding() {
10782        use crate::base_sync_only::{Outcome, Pass, Request};
10783
10784        let mut state = run_state(RunStatus::Blocked);
10785        let mut task = task();
10786        let request = Request {
10787            run: state.id.clone(),
10788            at: Timestamp::now(),
10789        };
10790        task.start(state.id.clone());
10791        task.sync_only = Some(request.clone());
10792        // Dedicated dispatch saves Running with the pre-pass attempt count.
10793        task.attempts = 2;
10794        let mut pass = Pass::new(request, &state);
10795        pass.result = Outcome::AlreadyCurrent;
10796        state.sync_only_passes.push(pass);
10797        state.begin_pass();
10798
10799        reclaim(&mut task, Some(state), 3, "en");
10800
10801        assert_eq!(task.status, TaskStatus::Held);
10802        assert_eq!(task.attempts, 2);
10803        assert!(task.sync_only.is_none());
10804        let detail = task.hold_reason.unwrap();
10805        assert!(detail.contains("HEAD already contains the base"));
10806        assert!(detail.contains("verification was not allowed"));
10807    }
10808
10809    #[test]
10810    fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
10811        let dir = tempfile::tempdir().unwrap();
10812        let queue = Queue::at(dir.path().to_path_buf());
10813
10814        // No run recorded, so this never has to touch `RunState::load`.
10815        let mut orphaned = task();
10816        orphaned.id = "20260904-000000-orph".to_owned();
10817        orphaned.status = TaskStatus::Running;
10818        orphaned.attempts = 1;
10819        queue.put(&mut orphaned).unwrap();
10820
10821        let mut alive = task();
10822        alive.id = "20260904-000000-live".to_owned();
10823        alive.status = TaskStatus::Running;
10824        alive.attempts = 1;
10825        queue.put(&mut alive).unwrap();
10826        let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
10827
10828        let mut queued = task();
10829        queued.id = "20260904-000000-wait".to_owned();
10830        queue.put(&mut queued).unwrap();
10831
10832        let reclaimed = reclaim_orphaned_running(&queue, 2, &Default::default());
10833        assert_eq!(reclaimed, vec![orphaned.id.clone()]);
10834
10835        assert_eq!(
10836            queue.get(&orphaned.id).unwrap().status,
10837            TaskStatus::Held,
10838            "nothing was driving it and there was no run to recover"
10839        );
10840        assert_eq!(
10841            queue.get(&alive.id).unwrap().status,
10842            TaskStatus::Running,
10843            "a live claim must protect the task it belongs to"
10844        );
10845        assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
10846    }
10847
10848    /// Read a run.json back from an explicit `home`, the same way
10849    /// `reclaim_abandoned_runs` itself does - never through the
10850    /// process-global `RunState::load`, which this test's own `home` (an
10851    /// isolated tempdir, never pinned into the shared `OnceLock`) does not
10852    /// use at all.
10853    fn read_run_under(home: &Path, id: &str) -> RunState {
10854        let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
10855        serde_json::from_str(&body).unwrap()
10856    }
10857
10858    #[test]
10859    fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
10860        let dir = tempfile::tempdir().unwrap();
10861        let home = dir.path().to_path_buf();
10862        let now = Timestamp::now();
10863        let overrun_seat = || crate::run::ActiveSeat {
10864            node: "implement".to_owned(),
10865            started_at: now - jiff::SignedDuration::new(21_000, 0),
10866            timeout_secs: 3_600,
10867            attempt: 0,
10868            task: None,
10869            command: None,
10870            index: None,
10871            total: None,
10872        };
10873
10874        let mut dead = run_state(RunStatus::Implementing);
10875        dead.id = "20260101-000000-dead".to_owned();
10876        dead.active.insert("impl-A".to_owned(), overrun_seat());
10877        // A `driver_pid` the injected query below confirms gone outright —
10878        // `liveness` reads this as `Dead`, not merely "no daemon claims it".
10879        dead.driver_pid = Some(4242);
10880        dead.save_under(&home).unwrap();
10881
10882        // Same shape, but a live daemon's heartbeat names it: must be left
10883        // exactly alone, however far past its own timeout the seat sits.
10884        let mut alive = run_state(RunStatus::Implementing);
10885        alive.id = "20260101-000000-aliv".to_owned();
10886        alive.active.insert("impl-A".to_owned(), overrun_seat());
10887        alive.save_under(&home).unwrap();
10888        let mut status = Status::new();
10889        status.current = vec![Current {
10890            worker: None,
10891            task: "20260101-000000-task".to_owned(),
10892            run: alive.id.clone(),
10893        }];
10894        write_status_to(&home.join("daemon.json"), &status).unwrap();
10895
10896        // The abandoned seat left an open question behind: nobody is left to
10897        // read an answer once the run is failed, and this must not wait for
10898        // some later daemon startup's own sweep to notice that.
10899        let questions = Questions::at(home.join("questions"));
10900        let mut q = ask::Question::new(
10901            dead.id.clone(),
10902            "implement".to_owned(),
10903            "impl-A".to_owned(),
10904            "Which storage backend?".to_owned(),
10905            String::new(),
10906            vec!["SQLite".to_owned(), "Redis".to_owned()],
10907        );
10908        questions.put(&mut q).unwrap();
10909
10910        let abandoned = reclaim_abandoned_runs_with(
10911            &home,
10912            now,
10913            |pid| if pid == 4242 { Some(false) } else { None },
10914            |_| panic!("a query answering Dead outright needs no identity corroboration"),
10915        );
10916        assert_eq!(abandoned, vec![dead.id.clone()]);
10917
10918        let reloaded = read_run_under(&home, &dead.id);
10919        assert_eq!(reloaded.status, RunStatus::Failed);
10920        assert!(reloaded.active.is_empty());
10921        assert!(
10922            !questions.get(&q.id).unwrap().status.open(),
10923            "the failed run's own open question must be settled in the same pass"
10924        );
10925
10926        let still_alive = read_run_under(&home, &alive.id);
10927        assert_eq!(
10928            still_alive.status,
10929            RunStatus::Implementing,
10930            "a live daemon's claim protects it"
10931        );
10932        assert!(!still_alive.active.is_empty());
10933    }
10934
10935    /// The exact shape a review round flagged as broken: `magi serve` running
10936    /// in this same `home` scans *every* run on disk, including a manual
10937    /// `magi review` / `magi run` this daemon never started and that
10938    /// therefore claims no heartbeat of its own. Before this scan asked
10939    /// `liveness` rather than just `is_working_on`, a manual run whose active
10940    /// seat merely ran a little past its own timeout — the CLI finishing up,
10941    /// its result still being collected — got wiped and failed by a daemon
10942    /// that had nothing to do with it, out from under a process that was
10943    /// still very much running.
10944    #[test]
10945    fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
10946        let dir = tempfile::tempdir().unwrap();
10947        let home = dir.path().to_path_buf();
10948        let now = Timestamp::now();
10949
10950        let mut manual = run_state(RunStatus::Reviewing);
10951        manual.id = "20260101-000000-manl".to_owned();
10952        manual.active.insert(
10953            "review-1".to_owned(),
10954            crate::run::ActiveSeat {
10955                node: "review".to_owned(),
10956                started_at: now - jiff::SignedDuration::new(21_000, 0),
10957                timeout_secs: 3_600,
10958                attempt: 0,
10959                task: None,
10960                command: None,
10961                index: None,
10962                total: None,
10963            },
10964        );
10965        // Not claimed by any daemon (no `daemon.json` at all in this `home`),
10966        // but a real, still-running process: `liveness` must corroborate this
10967        // as `Live`, not read the missing daemon claim as death.
10968        manual.driver_pid = Some(4242);
10969        manual.driver_started_at = Some("1790000000".to_owned());
10970        manual.save_under(&home).unwrap();
10971
10972        let abandoned = reclaim_abandoned_runs_with(
10973            &home,
10974            now,
10975            |pid| if pid == 4242 { Some(true) } else { None },
10976            |pid| {
10977                if pid == 4242 {
10978                    Some("1790000000".to_owned())
10979                } else {
10980                    None
10981                }
10982            },
10983        );
10984        assert!(
10985            abandoned.is_empty(),
10986            "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
10987        );
10988
10989        let reloaded = read_run_under(&home, &manual.id);
10990        assert_eq!(reloaded.status, RunStatus::Reviewing);
10991        assert!(!reloaded.active.is_empty());
10992    }
10993
10994    #[test]
10995    fn an_already_claimed_task_is_skipped_rather_than_failed() {
10996        let dir = tempfile::tempdir().unwrap();
10997        let queue = Queue::at(dir.path().to_path_buf());
10998        let mut only = task();
10999        queue.put(&mut only).unwrap();
11000
11001        let _elsewhere = queue.claim(&only.id).unwrap();
11002        let candidates = runnable(&queue);
11003        assert_eq!(candidates.len(), 1, "the task is still runnable");
11004        assert!(
11005            queue.claim(&candidates[0].id).is_err(),
11006            "the loop cannot take a claim somebody else holds"
11007        );
11008
11009        let after = queue.get(&only.id).unwrap();
11010        assert_eq!(after.status, TaskStatus::Queued);
11011        assert_eq!(
11012            after.attempts, 0,
11013            "losing the race is not an attempt at the task"
11014        );
11015        assert_eq!(after.last_error, None);
11016    }
11017
11018    #[test]
11019    fn the_status_file_round_trips_and_its_heartbeat_advances() {
11020        let dir = tempfile::tempdir().unwrap();
11021        let path = dir.path().join("daemon.json");
11022
11023        let mut status = Status::new();
11024        status.idle = false;
11025        status.completed = 7;
11026        status.current = vec![Current {
11027            worker: None,
11028            task: "20260902-000000-t111".to_owned(),
11029            run: "20260902-000001-r111".to_owned(),
11030        }];
11031        write_status_to(&path, &status).unwrap();
11032        let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
11033        assert_eq!(first.schema, SCHEMA);
11034        assert_eq!(first.pid, std::process::id());
11035        assert!(!first.idle);
11036        assert_eq!(first.completed, 7);
11037        assert_eq!(first.current, status.current);
11038        assert!(
11039            !path.with_extension("json.tmp").exists(),
11040            "the temp file is renamed, not left behind"
11041        );
11042
11043        std::thread::sleep(Duration::from_millis(5));
11044        status.updated_at = Timestamp::now();
11045        status.polls = 3;
11046        write_status_to(&path, &status).unwrap();
11047        let second: Status =
11048            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
11049        assert!(
11050            second.updated_at > first.updated_at,
11051            "a reader can only detect staleness if the heartbeat moves"
11052        );
11053        assert_eq!(
11054            second.started_at, first.started_at,
11055            "the start time is not a heartbeat"
11056        );
11057        assert_eq!(second.polls, 3);
11058    }
11059
11060    #[test]
11061    fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
11062        let dir = tempfile::tempdir().unwrap();
11063
11064        assert!(read_status(dir.path()).is_none(), "no file, no daemon");
11065
11066        let mut status = Status::new();
11067        status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
11068        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11069        let stale = read_status(dir.path()).unwrap();
11070        assert!(
11071            !stale.running(Timestamp::now()),
11072            "a minute without a heartbeat is a dead daemon, not a busy one"
11073        );
11074        assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
11075
11076        status.updated_at = Timestamp::now();
11077        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11078        let fresh = read_status(dir.path()).unwrap();
11079        assert!(fresh.running(Timestamp::now()));
11080    }
11081
11082    #[test]
11083    fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
11084        let dir = tempfile::tempdir().unwrap();
11085        let now = Timestamp::now();
11086        let mine = "20260903-080619-01c2";
11087
11088        assert!(
11089            !is_working_on(dir.path(), mine, now),
11090            "no status file means nobody is working on anything"
11091        );
11092
11093        let mut status = Status::new();
11094        status.current = vec![Current {
11095            worker: None,
11096            task: "20260903-080340-0167".to_owned(),
11097            run: mine.to_owned(),
11098        }];
11099        status.updated_at = now;
11100        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11101        assert!(is_working_on(dir.path(), mine, now));
11102        assert!(
11103            !is_working_on(dir.path(), "20260903-105039-3cbf", now),
11104            "a daemon busy with one run is not working on another"
11105        );
11106
11107        // A killed daemon stops writing heartbeats but leaves the file behind
11108        // naming the run it died in. That run must not be undeletable forever.
11109        status.updated_at = now - jiff::SignedDuration::from_secs(600);
11110        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11111        assert!(
11112            !is_working_on(dir.path(), mine, now),
11113            "a stale heartbeat is a dead daemon, so its run is a leftover"
11114        );
11115    }
11116
11117    #[test]
11118    fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
11119        let dir = tempfile::tempdir().unwrap();
11120        let now = Timestamp::now();
11121
11122        assert!(
11123            !is_working_on_short(dir.path(), "01c2", now),
11124            "no status file means nobody is working on anything"
11125        );
11126
11127        let mut status = Status::new();
11128        status.current = vec![Current {
11129            worker: None,
11130            task: "20260903-080340-0167".to_owned(),
11131            run: "20260903-080619-01c2".to_owned(),
11132        }];
11133        status.updated_at = now;
11134        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
11135        assert!(
11136            is_working_on_short(dir.path(), "01c2", now),
11137            "the run's short id is the last block of its full id"
11138        );
11139        assert!(
11140            !is_working_on_short(dir.path(), "3cbf", now),
11141            "a daemon busy with one worktree bay is not working on another"
11142        );
11143    }
11144
11145    #[test]
11146    fn a_newer_status_file_still_yields_a_reading() {
11147        let dir = tempfile::tempdir().unwrap();
11148        // A field this build has never heard of must not turn the reading into
11149        // nothing at all; that is the whole reason the reader is permissive.
11150        std::fs::write(
11151            dir.path().join("daemon.json"),
11152            serde_json::json!({
11153                "schema": 2,
11154                "updated_at": Timestamp::now().to_string(),
11155                "idle": true,
11156                "surprise": { "nested": [1, 2, 3] },
11157            })
11158            .to_string(),
11159        )
11160        .unwrap();
11161
11162        let reading = read_status(dir.path()).expect("a forward-compatible read");
11163        assert!(reading.running(Timestamp::now()));
11164        assert!(reading.idle);
11165        assert!(reading.current.is_empty());
11166    }
11167
11168    #[test]
11169    fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
11170        // A daemon started before `current` became a list keeps writing this
11171        // shape on every heartbeat until it is restarted. A rolling upgrade
11172        // - a newer `magi web` or `magi doctor` reading an older `magi
11173        // serve`'s heartbeat - must still see the run it is on, not "no
11174        // daemon" from a type mismatch failing the whole struct.
11175        let dir = tempfile::tempdir().unwrap();
11176        std::fs::write(
11177            dir.path().join("daemon.json"),
11178            serde_json::json!({
11179                "schema": 1,
11180                "pid": 4242,
11181                "updated_at": Timestamp::now().to_string(),
11182                "idle": false,
11183                "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
11184                "completed": 3,
11185                "polls": 9,
11186            })
11187            .to_string(),
11188        )
11189        .unwrap();
11190
11191        let reading = read_status(dir.path()).expect("an older shape must still parse");
11192        assert!(reading.running(Timestamp::now()));
11193        assert_eq!(
11194            reading.current,
11195            vec![Current {
11196                worker: None,
11197                task: "20260902-140501-aaaa".to_owned(),
11198                run: "20260902-140502-bbbb".to_owned(),
11199            }]
11200        );
11201    }
11202
11203    #[test]
11204    fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
11205        let dir = tempfile::tempdir().unwrap();
11206        std::fs::write(
11207            dir.path().join("daemon.json"),
11208            serde_json::json!({
11209                "schema": 1,
11210                "updated_at": Timestamp::now().to_string(),
11211                "idle": true,
11212                "current": null,
11213            })
11214            .to_string(),
11215        )
11216        .unwrap();
11217        let with_null = read_status(dir.path()).expect("null must still parse");
11218        assert!(with_null.current.is_empty());
11219
11220        std::fs::write(
11221            dir.path().join("daemon.json"),
11222            serde_json::json!({
11223                "schema": 1,
11224                "updated_at": Timestamp::now().to_string(),
11225                "idle": true,
11226            })
11227            .to_string(),
11228        )
11229        .unwrap();
11230        let absent = read_status(dir.path()).expect("a missing field must still parse");
11231        assert!(absent.current.is_empty());
11232    }
11233
11234    #[test]
11235    fn a_task_without_a_repository_runs_in_the_daemons_default() {
11236        let fallback = Path::new("/default");
11237        let mut blank = task();
11238        blank.repo = PathBuf::new();
11239        assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
11240        let mut dot = task();
11241        dot.repo = PathBuf::from(".");
11242        assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
11243        assert_eq!(
11244            repo_for(&task(), fallback),
11245            PathBuf::from("/repo"),
11246            "a task that names a repository keeps it"
11247        );
11248    }
11249
11250    #[test]
11251    fn new_tasks_inherit_the_daemon_build_cache_but_historical_tasks_remain_shared() {
11252        let dir = tempfile::tempdir().unwrap();
11253        let repo = dir.path();
11254        let path = repo.join("explicit.toml");
11255        std::fs::write(
11256            &path,
11257            "[verify]\nbuild_cache = 'isolated'\n[graph]\njudges = 1\n",
11258        )
11259        .unwrap();
11260        let opts = Opts {
11261            config: Some(path),
11262            ..Opts::default()
11263        };
11264        let queue = Queue::at(repo.join("queue"));
11265        let mut new = task();
11266        queue.put(&mut new).unwrap();
11267        let resolved = |task: &Task| prepare_for(repo, &opts, task).unwrap();
11268        assert_eq!(
11269            resolved(&queue.get(&new.id).unwrap()).verify.build_cache,
11270            BuildCache::Isolated
11271        );
11272
11273        let mut old = task();
11274        old.schema = 22;
11275        queue.put(&mut old).unwrap();
11276        let mut old = queue.get(&old.id).unwrap();
11277        let config = resolved(&old);
11278        assert_eq!(config.verify.build_cache, BuildCache::Shared);
11279        assert_eq!(config.graph.judges, 1, "preserve daemon config inheritance");
11280        old.hold_manual(Some("wait".into()));
11281        queue.put(&mut old).unwrap();
11282
11283        let mut saved = queue.get(&old.id).unwrap();
11284        assert_eq!(resolved(&saved).verify.build_cache, BuildCache::Shared);
11285        saved
11286            .overrides
11287            .as_mut()
11288            .unwrap()
11289            .merge_over(&crate::queue::RunOverrides {
11290                build_cache: Some(BuildCache::Isolated),
11291                ..Default::default()
11292            });
11293        queue.put(&mut saved).unwrap();
11294        assert_eq!(
11295            resolved(&queue.get(&saved.id).unwrap()).verify.build_cache,
11296            BuildCache::Isolated
11297        );
11298    }
11299
11300    #[test]
11301    fn urgent_build_cache_precedes_config_but_not_an_explicit_choice() {
11302        let dir = tempfile::tempdir().unwrap();
11303        let path = dir.path().join("explicit.toml");
11304        let write = |verify: &str| {
11305            std::fs::write(&path, format!("[verify]\nbuild_cache = 'shared'\n{verify}")).unwrap();
11306        };
11307        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test\"]\n");
11308        let opts = Opts {
11309            config: Some(path.clone()),
11310            ..Opts::default()
11311        };
11312        let mut task = task();
11313        task.set_urgent(true).unwrap();
11314        let resolved = |task: &Task| {
11315            prepare_for(dir.path(), &opts, task)
11316                .unwrap()
11317                .verify
11318                .build_cache
11319        };
11320        assert_eq!(resolved(&task), BuildCache::Isolated);
11321        task.change_build_cache(Some(BuildCache::Shared)).unwrap();
11322        assert_eq!(resolved(&task), BuildCache::Shared);
11323        task.change_build_cache(None).unwrap();
11324        assert_eq!(resolved(&task), BuildCache::Isolated);
11325        task.set_urgent(false).unwrap();
11326        assert_eq!(resolved(&task), BuildCache::Shared);
11327
11328        // Urgent work must never be the one stopped by isolation: with no
11329        // shared cache to wait behind, or with a verification command isolated
11330        // mode cannot run, an urgent task keeps the configured mode.
11331        task.set_urgent(true).unwrap();
11332        write("e2e = [\"npm test\"]\n");
11333        assert_eq!(resolved(&task), BuildCache::Shared);
11334        write("e2e = [\"CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log\"]\n");
11335        assert_eq!(resolved(&task), BuildCache::Shared);
11336        // An explicit choice stays strict and is applied as asked.
11337        task.change_build_cache(Some(BuildCache::Isolated)).unwrap();
11338        assert_eq!(resolved(&task), BuildCache::Isolated);
11339    }
11340
11341    #[test]
11342    fn task_implementers_edit_inherits_daemon_config_and_merge() {
11343        let dir = tempfile::tempdir().unwrap();
11344        let path = dir.path().join("explicit.toml");
11345        std::fs::write(&path, "[graph]\nimplementers = 3\njudges = 1\n").unwrap();
11346        let opts = Opts {
11347            config: Some(path),
11348            merge: Some("none".into()),
11349            ..Default::default()
11350        };
11351        let mut t = task();
11352        t.set_implementers(
11353            2,
11354            &toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11355                .unwrap(),
11356        )
11357        .unwrap();
11358        let cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11359        assert_eq!(cfg.graph.implementers, 2);
11360        assert_eq!(cfg.graph.judges, 1);
11361        assert_eq!(cfg.merge.mode, MergeMode::None);
11362        t.set_implementers(1, &cfg).unwrap();
11363        let mut cfg = prepare_for(dir.path(), &opts, &t).unwrap();
11364        apply_task_implementers(&mut cfg, &t);
11365        assert_eq!(cfg.graph.implementers, 1);
11366        assert_eq!(cfg.graph.judges, 1);
11367        assert_eq!(cfg.merge.mode, MergeMode::None);
11368    }
11369
11370    #[test]
11371    fn task_implementers_direct_overrides_stay_isolated_after_edits() {
11372        let dir = tempfile::tempdir().unwrap();
11373        let repo = dir.path().join("repo");
11374        std::fs::create_dir(&repo).unwrap();
11375        std::fs::write(
11376            repo.join("magi.toml"),
11377            "[graph]\njudges = 2\n[merge]\nmode = 'none'\n",
11378        )
11379        .unwrap();
11380        let daemon_config = dir.path().join("daemon.toml");
11381        std::fs::write(
11382            &daemon_config,
11383            "[graph]\njudges = 1\n[merge]\nmode = 'pr'\n",
11384        )
11385        .unwrap();
11386        let opts = Opts {
11387            config: Some(daemon_config),
11388            merge: Some("pr".into()),
11389            ..Default::default()
11390        };
11391        let q = Queue::at(dir.path().join("queue"));
11392        let validation: Config =
11393            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11394                .unwrap();
11395        // No provenance field on legacy direct tasks: both shapes stay isolated.
11396        for record in ["{}", r#"{"candidates":2}"#] {
11397            let overrides = serde_json::from_str(record).unwrap();
11398            let filing = crate::direct::Filing {
11399                instruction: "work".into(),
11400                title: "direct".into(),
11401                repo: repo.clone(),
11402                source: crate::queue::Source::Human,
11403                solo: false,
11404                overrides,
11405                review_of: None,
11406                sources: Default::default(),
11407            };
11408            let filed =
11409                crate::direct::file(&q, dir.path(), Timestamp::now(), 1, filing, true).unwrap();
11410            let crate::direct::Filed::Standalone {
11411                mut task,
11412                claim: _claim,
11413            } = filed
11414            else {
11415                panic!("local filing")
11416            };
11417            let before = prepare_for(&repo, &opts, &task).unwrap();
11418            assert_eq!(before.graph.judges, 2, "daemon --config must not leak");
11419            assert_eq!(
11420                before.merge.mode,
11421                MergeMode::None,
11422                "daemon --merge must not leak"
11423            );
11424            for n in [2, 1, 2] {
11425                task.set_implementers(n, &validation).unwrap();
11426                q.put(&mut task).unwrap();
11427                task = q.get(&task.id).unwrap();
11428                assert!(!task.overrides.as_ref().unwrap().inherit_daemon_options);
11429                let mut cfg = prepare_for(&repo, &opts, &task).unwrap();
11430                apply_task_implementers(&mut cfg, &task);
11431                assert_eq!(cfg.graph.implementers, usize::from(n));
11432                assert_eq!(cfg.graph.judges, 2);
11433                assert_eq!(cfg.merge.mode, MergeMode::None);
11434            }
11435        }
11436    }
11437
11438    #[test]
11439    fn task_implementers_mismatch_keeps_explicit_reviews_review_only() {
11440        let cfg: Config =
11441            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11442                .unwrap();
11443        let mut t = task();
11444        t.review_of = Some("review-target".into());
11445        t.hold_manual(Some("retry".into()));
11446        let mut previous = RunState::new(
11447            PathBuf::from("/repo"),
11448            "main".into(),
11449            "abc1234".into(),
11450            "review".into(),
11451            cfg.clone(),
11452        );
11453        previous.config.graph.implementers = 2;
11454        for count in [1, 3] {
11455            t.set_implementers(count, &cfg).unwrap();
11456            t.release();
11457            assert_eq!(t.review_of.as_deref(), Some("review-target"));
11458            for proposed in [
11459                Starter::Resume(previous.id.clone()),
11460                Starter::Review("recovery-target".into()),
11461            ] {
11462                assert_eq!(
11463                    starter_with_implementers(&t, Some(&previous), proposed),
11464                    Starter::Review("review-target".into())
11465                );
11466            }
11467            let mut configured = cfg.clone();
11468            apply_task_implementers(&mut configured, &t);
11469            assert_eq!(configured.graph.implementers, usize::from(count));
11470            assert_eq!(previous.config.graph.implementers, 2);
11471        }
11472    }
11473
11474    #[test]
11475    fn task_implementers_dispatch_and_resume_agree() {
11476        let mut t = task();
11477        let cfg: crate::config::Config =
11478            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
11479                .unwrap();
11480        let mut run = RunState::new(
11481            PathBuf::from("/repo"),
11482            "main".into(),
11483            "abc1234".into(),
11484            "work".into(),
11485            cfg.clone(),
11486        );
11487        run.config.graph.implementers = 2;
11488        for n in [2, 1, 3, 2] {
11489            t.set_implementers(n, &cfg).unwrap();
11490            let mut dispatched = cfg.clone();
11491            apply_task_implementers(&mut dispatched, &t);
11492            assert_eq!(dispatched.graph.implementers, usize::from(n));
11493            assert_eq!(implementers_match(&t, &run), n == 2);
11494            for proposed in [
11495                Starter::Resume(run.id.clone()),
11496                Starter::Review("old-branch".into()),
11497            ] {
11498                let expected = if n == 2 {
11499                    proposed.clone()
11500                } else {
11501                    Starter::Start
11502                };
11503                assert_eq!(
11504                    starter_with_implementers(&t, Some(&run), proposed),
11505                    expected
11506                );
11507            }
11508            assert_eq!(
11509                run.config.graph.implementers, 2,
11510                "history must not be rewritten"
11511            );
11512        }
11513        t.solo = false;
11514        t.overrides = None;
11515        assert!(implementers_match(&t, &run));
11516    }
11517
11518    #[test]
11519    fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
11520        // Three seats said out loud. What `solo` promises is one candidate
11521        // *whatever the config asks for*, so the contrast has to be a number
11522        // this test owns - it used to be `Config::default()`'s, which became
11523        // 1 when one implementation became the default and left the two
11524        // halves of this test asserting the same thing.
11525        let mut solo_cfg = Config::default();
11526        solo_cfg.graph.implementers = 3;
11527        let mut solo_task = task();
11528        solo_task.solo = true;
11529        apply_task_implementers(&mut solo_cfg, &solo_task);
11530        assert_eq!(solo_cfg.graph.implementers, 1);
11531
11532        let mut plain_cfg = Config::default();
11533        plain_cfg.graph.implementers = 3;
11534        let plain_task = task();
11535        assert!(!plain_task.solo);
11536        apply_task_implementers(&mut plain_cfg, &plain_task);
11537        assert_eq!(
11538            plain_cfg.graph.implementers, 3,
11539            "a task that did not ask to run alone keeps the config's candidates"
11540        );
11541    }
11542
11543    fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
11544        QuotaLoss {
11545            cause: crate::agent::QuotaCause::UsageLimit,
11546            agent: String::new(),
11547            seat: seat.into(),
11548            node: "judge".into(),
11549            at: at.parse().unwrap(),
11550            reset: reset.map(str::to_string),
11551        }
11552    }
11553
11554    #[test]
11555    fn authentication_losses_never_arm_a_cooldown_even_with_reset_hints() {
11556        let now = Timestamp::now();
11557        for reset in [None, Some("in 1h")] {
11558            let auth = crate::agent::Quota {
11559                cause: crate::agent::QuotaCause::Authentication,
11560                agent: "alpha".into(),
11561                reset: reset.map(str::to_owned),
11562            };
11563            let loss = QuotaLoss::from_report("advisor-1".into(), "advise", Some(&auth));
11564            assert_eq!(cooldown_until(&[loss], now), None);
11565        }
11566    }
11567
11568    #[test]
11569    fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
11570        let old: Vec<QuotaLoss> = (1..=4)
11571            .map(|i| {
11572                loss(
11573                    &format!("judge-{i}"),
11574                    "2026-09-23T05:23:00Z",
11575                    Some("2:40pm (Asia/Tokyo)"),
11576                )
11577            })
11578            .collect();
11579        let fresh = losses_this_attempt(&old, &old);
11580        assert!(fresh.is_empty());
11581        assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
11582        // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
11583    }
11584
11585    #[test]
11586    fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
11587        let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
11588        let now = Timestamp::now();
11589        let mut after = old.clone();
11590        after.push(loss("judge-2", &now.to_string(), None));
11591        let fresh = losses_this_attempt(&old, &after);
11592        assert_eq!(fresh, vec![after[1].clone()]);
11593        let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
11594        assert_eq!(
11595            until,
11596            now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
11597        );
11598    }
11599
11600    #[test]
11601    fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
11602        // `recover_stall` removes judge-1's loss and the retry then hits quota
11603        // again: the vector is the same length, so an index diff sees nothing.
11604        let before = vec![
11605            loss("judge-1", "2026-09-23T05:23:00Z", None),
11606            loss("judge-2", "2026-09-23T05:24:00Z", None),
11607        ];
11608        let after = vec![
11609            loss("judge-2", "2026-09-23T05:24:00Z", None),
11610            loss("judge-1", "2026-09-24T01:00:00Z", None),
11611        ];
11612        assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
11613    }
11614
11615    #[test]
11616    fn merge_overrides_are_parsed_or_refused() {
11617        assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
11618        assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
11619        assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
11620        assert!(merge_mode("squash").is_err());
11621    }
11622
11623    #[test]
11624    fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
11625        let now = Timestamp::now();
11626        let fallback = Duration::from_secs(300);
11627        let cap = Duration::from_secs(1800);
11628
11629        // No reset hint at all: the fallback.
11630        assert_eq!(quota_wait(None, now, fallback, cap), fallback);
11631
11632        // A reset ten minutes out, well inside the cap: waited for exactly.
11633        let soon = now + jiff::SignedDuration::from_secs(600);
11634        assert_eq!(
11635            quota_wait(Some(soon), now, fallback, cap),
11636            Duration::from_secs(600)
11637        );
11638
11639        // A reset already in the past is not trusted: the fallback, not a
11640        // zero or negative wait that would spin the loop right back around.
11641        let past = now - jiff::SignedDuration::from_secs(60);
11642        assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
11643
11644        // A reset further out than the cap is trusted for direction but not
11645        // for magnitude: a parsing slip must not sleep the loop for a day.
11646        let far = now + jiff::SignedDuration::from_secs(3 * 3600);
11647        assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
11648    }
11649
11650    #[test]
11651    fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
11652        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11653
11654        let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
11655        assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
11656
11657        // Same clock reading, but it has already gone by today: read as
11658        // tomorrow's, since the CLI would not still be reporting a limit past
11659        // its own stated reset.
11660        let already_past =
11661            parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
11662        assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
11663
11664        assert!(
11665            parse_reset_hint("session limit reached", now, now).is_none(),
11666            "free text with no recognised shape is not guessed at"
11667        );
11668        assert!(
11669            parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
11670            "an unresolvable zone name is not guessed at either"
11671        );
11672    }
11673
11674    #[test]
11675    fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
11676        let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
11677
11678        let at = parse_reset_hint(
11679            "You've hit your usage limit. Visit \
11680             https://chatgpt.com/codex/settings/usage to purchase more \
11681             credits or try again at Sep 19th, 2026 5:10 PM.",
11682            now,
11683            now,
11684        )
11685        .expect("the codex reset wording is a recognised shape");
11686        assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
11687
11688        // The month is explicit, so a date already earlier in the same
11689        // sentence-implied year than `now` is trusted as written rather than
11690        // rolled forward a year the way the bracketed shape rolls a
11691        // same-day clock reading to tomorrow.
11692        let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
11693            .expect("an explicit year needs no rollover");
11694        assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
11695
11696        assert!(
11697            parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
11698            "a two-digit year is not the documented shape and is not guessed at"
11699        );
11700        assert!(
11701            parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
11702            "a four-letter month name is not the documented three-letter abbreviation"
11703        );
11704        assert!(
11705            parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
11706            "an explicit zone on the dated shape is a format nobody has \
11707             documented, and is refused rather than guessed at as UTC"
11708        );
11709    }
11710
11711    #[test]
11712    fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
11713        let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
11714        let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
11715
11716        let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
11717        assert_eq!(at.as_second() - recorded.as_second(), 3769);
11718
11719        let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
11720        assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
11721
11722        for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
11723            assert!(
11724                parse_reset_hint(bad, now, recorded).is_none(),
11725                "{bad:?} must not be guessed at"
11726            );
11727        }
11728    }
11729
11730    /// A loop whose queue lives in a temp tree and whose poll interval is far
11731    /// longer than the test's patience, so anything that waits out a poll
11732    /// instead of noticing the stop fails rather than merely being slow.
11733    fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
11734        let config = dir.join("magi.toml");
11735        std::fs::write(
11736            &config,
11737            "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
11738        )
11739        .unwrap();
11740        let opts = Opts {
11741            poll: Duration::from_secs(30),
11742            config: Some(config),
11743            // The explicit fixture config keeps startup cleanup from reading
11744            // machine configuration. This fictional repository likewise
11745            // keeps any best-effort git cleanup away from this checkout.
11746            repo: dir.join("repo"),
11747            ..Opts::default()
11748        };
11749        // The status file goes in a directory that does not exist yet, so its
11750        // creation is itself evidence the loop published one. `worktrees`
11751        // must be just as fictional: the janitor reclaims worktrees under it
11752        // for real, and a test that let it fall through to
11753        // `crate::run::default_worktree_root()` would have it reclaim
11754        // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
11755        // which is exactly what happened before this function took the
11756        // parameter at all.
11757        let home = dir.join("home");
11758        // These control-only fixtures do not launch native workers. Give the
11759        // independently tested maintenance services a fresh cadence receipt.
11760        let stamps = home.join("service-ticks");
11761        std::fs::create_dir_all(&stamps).unwrap();
11762        for service in ["waiter", "deputies", "release-watch"] {
11763            std::fs::write(
11764                stamps.join(service),
11765                Timestamp::now().as_second().to_string(),
11766            )
11767            .unwrap();
11768        }
11769        for operation in [
11770            "conductor",
11771            "maintenance",
11772            "housekeeping",
11773            "disk-pressure",
11774            "cache",
11775            "fetch",
11776            "chat-goals",
11777        ] {
11778            std::fs::write(
11779                stamps.join(format!("daemon-{operation}")),
11780                serde_json::to_vec(&Timestamp::now()).unwrap(),
11781            )
11782            .unwrap();
11783        }
11784        let worktrees = dir.join("wt");
11785        (
11786            opts,
11787            Queue::at(dir.join("queue")),
11788            home.join("daemon.json"),
11789            home,
11790            worktrees,
11791        )
11792    }
11793
11794    #[tokio::test]
11795    async fn disk_wait_maintenance_recovers_while_another_task_is_running() {
11796        let dir = tempfile::tempdir().unwrap();
11797        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11798        let mut waiting = task();
11799        waiting.repo = opts.repo.clone();
11800        waiting.hold_machine(crate::disk::gate(1, 100));
11801        waiting.mark_disk_capacity();
11802        waiting.attempts = 2;
11803        queue.put(&mut waiting).unwrap();
11804        let mut busy = task();
11805        busy.status = TaskStatus::Running;
11806        queue.put(&mut busy).unwrap();
11807        let payload = serde_json::to_value(ServiceWorker {
11808            opts,
11809            queue: queue.root().to_owned(),
11810            worktrees_root: worktrees,
11811            operation: "maintenance".into(),
11812        })
11813        .unwrap();
11814        run_service_worker(&home, payload.clone()).await.unwrap();
11815        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Queued);
11816        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11817        assert_eq!(queue.get(&busy.id).unwrap().status, TaskStatus::Running);
11818        run_service_worker(&home, payload).await.unwrap();
11819        assert!(
11820            crate::worker::active(&home).unwrap().is_empty(),
11821            "monitoring only queues; normal dispatch owns launches"
11822        );
11823        assert_eq!(queue.get(&waiting.id).unwrap().attempts, 2);
11824    }
11825
11826    #[tokio::test]
11827    async fn source_eviction_service_receipts_explain_idle_and_active_skips() {
11828        let dir = tempfile::tempdir().unwrap();
11829        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
11830        let cfg = Config::default();
11831        start_service(
11832            &home,
11833            &opts,
11834            &queue,
11835            &worktrees,
11836            "housekeeping",
11837            Some(&cfg),
11838            true,
11839        )
11840        .await
11841        .unwrap();
11842        let receipt = home.join("source-eviction-housekeeping-dispatch.json");
11843        let read = |path: &Path| -> serde_json::Value {
11844            serde_json::from_slice(&std::fs::read(path).unwrap()).unwrap()
11845        };
11846        assert_eq!(read(&receipt)["detail"], "cadence not due");
11847        std::fs::remove_file(home.join("service-ticks/daemon-housekeeping")).unwrap();
11848        start_service(
11849            &home,
11850            &opts,
11851            &queue,
11852            &worktrees,
11853            "housekeeping",
11854            Some(&cfg),
11855            true,
11856        )
11857        .await
11858        .unwrap();
11859        assert_eq!(
11860            read(&receipt)["detail"],
11861            "active work or runnable task queue"
11862        );
11863        assert_eq!(read(&receipt)["version"], env!("CARGO_PKG_VERSION"));
11864        assert_eq!(read(&receipt)["auto_fold"], cfg.disk.auto_fold);
11865        std::fs::remove_file(home.join("service-ticks/daemon-disk-pressure")).unwrap();
11866        start_service(
11867            &home,
11868            &opts,
11869            &queue,
11870            &worktrees,
11871            "disk-pressure",
11872            Some(&cfg),
11873            false,
11874        )
11875        .await
11876        .unwrap();
11877        assert_eq!(
11878            read(&home.join("source-eviction-disk-pressure-dispatch.json"))["detail"],
11879            "no active work; idle housekeeping owns scan"
11880        );
11881        assert!(crate::worker::active(&home).unwrap().is_empty());
11882    }
11883
11884    #[tokio::test]
11885    async fn goal_observation_service_does_not_block_scheduler_decisions() {
11886        let dir = tempfile::tempdir().unwrap();
11887        let (opts, _, _, home, worktrees) = idle_loop(dir.path());
11888        let queue = Queue::at(home.join("queue"));
11889        let mut task = task();
11890        task.repo = opts.repo.clone();
11891        task.chat = Some("decision-chat".into());
11892        task.hold_machine(Some("waiting for a decision".into()));
11893        queue.put(&mut task).unwrap();
11894        let questions = Questions::at(home.join("questions"));
11895        let mut question = action_question(&task.id, ask::ChoiceAction::Done);
11896        question.node = crate::conduct::NODE.into();
11897        question.status = ask::QuestionStatus::Open;
11898        question.answer = None;
11899        question.answered_at = None;
11900        questions.put(&mut question).unwrap();
11901        questions
11902            .update(&question.id, |q| {
11903                q.answer(ask::Answer::Choice("resume で続行する".into()))
11904            })
11905            .unwrap();
11906
11907        let talks = crate::talk::Talks::at(home.join("talks"));
11908        let mut decision_chat = crate::talk::seeded_for_test("decision-chat", opts.repo.clone());
11909        decision_chat.pending = "Keep this unsent status question".into();
11910        talks.put(&mut decision_chat).unwrap();
11911        let mut talk = crate::talk::seeded_for_test("observing-chat", opts.repo.clone());
11912        talk.goals.push(serde_json::from_value(serde_json::json!({
11913            "id":"goal","purpose":"follow the retained job","scope":"one task",
11914            "condition":{"description":"land the result","kind":"runs_merged"},
11915            "state":"runnable","step":"reading the forge","source_turn":0,"owner_input":"land this job",
11916            "tasks":[],"runs":[],"watches":[],"evidence":"","wake":1,"handled":0,
11917            "started":1,"wakes":1,"last_checked":null,"fingerprint":""
11918        })).unwrap());
11919        talks.put(&mut talk).unwrap();
11920
11921        // A retained service lease models an observation still waiting on its
11922        // external dependency. Admission must neither await nor repeat it.
11923        let directory = home.join("workers/jobs/abcdef");
11924        std::fs::create_dir_all(&directory).unwrap();
11925        let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
11926        crate::pr_head::try_lock_file(&lease).unwrap();
11927        let mut job = crate::worker::Job {
11928            id: "abcdef".into(),
11929            sequence: 1,
11930            kind: "daemon-service".into(),
11931            key: "service:daemon-chat-goals".into(),
11932            payload: serde_json::Value::Null,
11933            generation: "fixture".into(),
11934            version: None,
11935            status: crate::worker::Status::Running,
11936            result: None,
11937            pid: Some(std::process::id()),
11938            created_at: Timestamp::now().as_second() as u64,
11939            finished_at: None,
11940        };
11941        let record = directory.join("job.json");
11942        std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
11943        let status = Arc::new(Mutex::new(Status::new()));
11944        let stop = Stop::new();
11945        let mut dispatch = Box::pin(poll(
11946            &opts,
11947            &queue,
11948            &status,
11949            &home,
11950            &worktrees,
11951            &stop,
11952            DispatchLimits {
11953                max_concurrent: 1,
11954                pause_for_interrupts: false,
11955                recovery_cfg: None,
11956            },
11957        ));
11958        std::future::poll_fn(|cx| {
11959            assert!(dispatch.as_mut().poll(cx).is_pending());
11960            std::task::Poll::Ready(())
11961        })
11962        .await;
11963        assert!(lock(&status).polls > 0);
11964        let saved = queue.get(&task.id).unwrap();
11965        assert_eq!(saved.status, TaskStatus::Done);
11966        assert!(saved.action_applied(&question.id));
11967        assert!(
11968            talks
11969                .get("decision-chat")
11970                .unwrap()
11971                .pending
11972                .contains("Keep this unsent status question")
11973        );
11974        let goal = talks.get(&talk.id).unwrap().goals.remove(0);
11975        assert_eq!(goal.state, crate::chat_goal::State::Runnable);
11976        assert_eq!(
11977            goal.started,
11978            Some(1),
11979            "only the observation worker may reconcile its goal"
11980        );
11981        assert_eq!(crate::worker::active(&home).unwrap()[0].id, job.id);
11982
11983        stop.stop();
11984        dispatch.await.unwrap();
11985        job.status = crate::worker::Status::Finished;
11986        std::fs::write(record, serde_json::to_vec(&job).unwrap()).unwrap();
11987        drop(lease);
11988    }
11989
11990    #[test]
11991    fn a_stop_is_idempotent_and_once_set_stays_set() {
11992        let stop = Stop::new();
11993        assert!(!stop.stopped());
11994
11995        stop.stop();
11996        assert!(stop.stopped());
11997        stop.stop();
11998        assert!(stop.stopped(), "a second stop is not a toggle");
11999
12000        let shared = stop.clone();
12001        assert!(
12002            shared.stopped(),
12003            "a clone is the same stop; that is how the loop and its caller share one"
12004        );
12005    }
12006
12007    #[tokio::test]
12008    async fn once_drain_rechecks_answers_after_queue_services_release_their_claims() {
12009        for operation in ["conductor", "maintenance", "housekeeping"] {
12010            let dir = tempfile::tempdir().unwrap();
12011            let (mut opts, queue, _, home, worktrees) = idle_loop(dir.path());
12012            opts.once = true;
12013            opts.poll = Duration::from_millis(1);
12014            // This test exercises answer scheduling, not explicit discard:
12015            // ordinary Done requires a completed retained execution.
12016            let mut state = run_state(RunStatus::Ready);
12017            state.reserve_under(&home).unwrap();
12018            state.save_under(&home).unwrap();
12019            let mut task = task();
12020            task.runs.push(state.id.clone());
12021            queue.put(&mut task).unwrap();
12022            let claim = queue.claim(&task.id).unwrap();
12023
12024            // Model a live service holding the task's claim across the
12025            // scheduler's dispatch scan. No real subprocess or timed race.
12026            let directory = home.join("workers/jobs/abcdef");
12027            std::fs::create_dir_all(&directory).unwrap();
12028            let lease = std::fs::File::create(directory.join("live.lock")).unwrap();
12029            crate::pr_head::try_lock_file(&lease).unwrap();
12030            let mut job = crate::worker::Job {
12031                id: "abcdef".into(),
12032                sequence: 1,
12033                kind: "daemon-service".into(),
12034                key: format!("service:daemon-{operation}"),
12035                payload: serde_json::Value::Null,
12036                generation: "fixture".into(),
12037                version: None,
12038                status: crate::worker::Status::Running,
12039                result: None,
12040                pid: Some(std::process::id()),
12041                created_at: Timestamp::now().as_second() as u64,
12042                finished_at: None,
12043            };
12044            let record = directory.join("job.json");
12045            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
12046
12047            let status = Arc::new(Mutex::new(Status::new()));
12048            let stop = Stop::new();
12049            let mut drain = Box::pin(poll(
12050                &opts,
12051                &queue,
12052                &status,
12053                &home,
12054                &worktrees,
12055                &stop,
12056                DispatchLimits {
12057                    max_concurrent: 1,
12058                    pause_for_interrupts: false,
12059                    recovery_cfg: None,
12060                },
12061            ));
12062            std::future::poll_fn(|cx| {
12063                use std::future::Future;
12064                assert!(
12065                    drain.as_mut().poll(cx).is_pending(),
12066                    "--once must wait for {operation} to release its queue claim"
12067                );
12068                std::task::Poll::Ready(())
12069            })
12070            .await;
12071            assert!(lock(&status).polls > 0, "the dispatch scan was exercised");
12072
12073            // An answer arrives while the service still owns the claim. A
12074            // fresh scheduling pass must apply it before declaring idle.
12075            let questions = Questions::at(home.join("questions"));
12076            let mut q = action_question(&state.id, ask::ChoiceAction::Done);
12077            questions.put(&mut q).unwrap();
12078            drop(claim);
12079            // Model services that took longer than their cadence, without a
12080            // wall-clock sleep. The final scans must not respawn them even
12081            // though their receipts now permit another periodic invocation.
12082            let expired =
12083                serde_json::to_vec(&"2000-01-01T00:00:00Z".parse::<Timestamp>().unwrap()).unwrap();
12084            for service in [operation, "housekeeping"] {
12085                std::fs::write(
12086                    home.join("service-ticks").join(format!("daemon-{service}")),
12087                    &expired,
12088                )
12089                .unwrap();
12090            }
12091            job.status = crate::worker::Status::Finished;
12092            std::fs::write(&record, serde_json::to_vec(&job).unwrap()).unwrap();
12093            drop(lease);
12094            tokio::time::timeout(Duration::from_secs(2), drain)
12095                .await
12096                .expect("the settled service must allow the drain to finish")
12097                .unwrap();
12098            let after = queue.get(&task.id).unwrap();
12099            assert_eq!(after.status, TaskStatus::Done, "answer after {operation}");
12100            assert!(after.action_applied(&q.id));
12101            for service in [operation, "housekeeping"] {
12102                assert_eq!(
12103                    std::fs::read(home.join("service-ticks").join(format!("daemon-{service}")))
12104                        .unwrap(),
12105                    expired,
12106                    "the final once rescan must not restart {service}"
12107                );
12108            }
12109        }
12110    }
12111
12112    #[test]
12113    fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
12114        let stop = Stop::new();
12115        stop.busy.store(1, Ordering::SeqCst);
12116        assert!(
12117            !stop.finishing(),
12118            "a busy loop nobody has asked to stop is just running"
12119        );
12120
12121        stop.stop();
12122        assert!(
12123            stop.finishing(),
12124            "a stop asked for mid-run has not landed until the run is settled"
12125        );
12126
12127        stop.busy.store(0, Ordering::SeqCst);
12128        assert!(
12129            !stop.finishing(),
12130            "once the run is settled the stop has landed and there is nothing to finish"
12131        );
12132    }
12133
12134    #[test]
12135    fn finishing_stays_true_until_the_last_of_several_runs_exits() {
12136        let stop = Stop::new();
12137        stop.busy.store(2, Ordering::SeqCst);
12138        stop.stop();
12139        assert!(stop.finishing(), "two runs still in flight");
12140
12141        stop.busy.store(1, Ordering::SeqCst);
12142        assert!(
12143            stop.finishing(),
12144            "one run finished, but a sibling is still working"
12145        );
12146
12147        stop.busy.store(0, Ordering::SeqCst);
12148        assert!(
12149            !stop.finishing(),
12150            "the last run out is what actually lands the stop"
12151        );
12152    }
12153
12154    #[tokio::test]
12155    async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
12156        let dir = tempfile::tempdir().unwrap();
12157        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12158        let stop = Stop::new();
12159        stop.stop();
12160
12161        let began = std::time::Instant::now();
12162        tokio::time::timeout(
12163            Duration::from_secs(2),
12164            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12165        )
12166        .await
12167        .expect("a stopped loop must return, not sit out its poll interval")
12168        .expect("the loop's own setup and teardown must not fail");
12169        assert!(
12170            began.elapsed() < opts.poll,
12171            "returned only after {:?}, which is a poll interval, not a stop",
12172            began.elapsed()
12173        );
12174    }
12175
12176    #[tokio::test]
12177    async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
12178        let dir = tempfile::tempdir().unwrap();
12179        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12180        let stop = Stop::new();
12181
12182        // Asked for after the loop is already parked on its empty queue, which
12183        // is the case an operator tapping stop on a phone actually hits.
12184        let asker = {
12185            let stop = stop.clone();
12186            tokio::spawn(async move {
12187                tokio::time::sleep(Duration::from_millis(20)).await;
12188                stop.stop();
12189            })
12190        };
12191
12192        let began = std::time::Instant::now();
12193        tokio::time::timeout(
12194            Duration::from_secs(2),
12195            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12196        )
12197        .await
12198        .expect("a stop asked for while idle must wake the wait")
12199        .expect("the loop's own setup and teardown must not fail");
12200        asker.await.unwrap();
12201        assert!(
12202            began.elapsed() < opts.poll,
12203            "returned only after {:?}, so the stop waited on the sleep",
12204            began.elapsed()
12205        );
12206    }
12207
12208    #[tokio::test]
12209    async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
12210        let dir = tempfile::tempdir().unwrap();
12211        let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
12212        let stop = Stop::new();
12213        stop.stop();
12214
12215        tokio::time::timeout(
12216            Duration::from_secs(2),
12217            drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
12218        )
12219        .await
12220        .expect("a stopped loop must return")
12221        .expect("the loop's own setup and teardown must not fail");
12222
12223        assert!(
12224            home.is_dir(),
12225            "the loop did publish a status file, so its removal is the teardown and not an absence"
12226        );
12227        assert!(
12228            !status_file.exists(),
12229            "a stopped loop clears its status file"
12230        );
12231        assert!(
12232            read_status(&home).is_none(),
12233            "a reader must see no daemon at all, not a heartbeat that merely stopped"
12234        );
12235    }
12236
12237    #[tokio::test]
12238    async fn housekeeping_worker_settles_questions_without_a_scheduler() {
12239        let dir = tempfile::tempdir().unwrap();
12240        let (opts, queue, _, home, worktrees) = idle_loop(dir.path());
12241
12242        let mut settled = RunState::new(
12243            dir.path().join("repo"),
12244            "main".to_owned(),
12245            "abc1234".to_owned(),
12246            "fixture".to_owned(),
12247            Config::default(),
12248        );
12249        settled.status = RunStatus::Ready;
12250        let run_dir = home.join("runs").join(&settled.id);
12251        std::fs::create_dir_all(&run_dir).unwrap();
12252        std::fs::write(
12253            run_dir.join("run.json"),
12254            serde_json::to_string_pretty(&settled).unwrap(),
12255        )
12256        .unwrap();
12257        let questions = Questions::at(home.join("questions"));
12258        let mut question = ask::Question::new(
12259            settled.id.clone(),
12260            "review".to_owned(),
12261            "reviewer-1".to_owned(),
12262            "Continue?".to_owned(),
12263            String::new(),
12264            Vec::new(),
12265        );
12266        questions.put(&mut question).unwrap();
12267
12268        run_service_worker(
12269            &home,
12270            serde_json::to_value(ServiceWorker {
12271                opts,
12272                queue: queue.root().to_path_buf(),
12273                worktrees_root: worktrees,
12274                operation: "housekeeping".to_owned(),
12275            })
12276            .unwrap(),
12277        )
12278        .await
12279        .unwrap();
12280
12281        assert_eq!(
12282            questions.get(&question.id).unwrap().status,
12283            ask::QuestionStatus::Abandoned,
12284            "the independent housekeeping worker settles ended-run questions"
12285        );
12286    }
12287
12288    #[test]
12289    fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
12290        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12291
12292        assert!(
12293            cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
12294            "never checked before: due at once"
12295        );
12296
12297        let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
12298        assert!(
12299            !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
12300            "well inside the interval: not due yet"
12301        );
12302
12303        let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
12304        assert!(
12305            !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
12306            "exactly at the edge: not yet due, same convention as `clean::due`"
12307        );
12308
12309        let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12310        assert!(
12311            cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
12312            "past the interval: due again"
12313        );
12314    }
12315
12316    /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
12317    /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
12318    /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
12319    /// and the congestion test below both need, and must not drift apart.
12320    fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
12321        let config = dir.join("magi.toml");
12322        // A literal (single-quoted) TOML string, not a basic one: the cache
12323        // path is a Windows path full of backslashes, and a basic string
12324        // would have TOML try to interpret `\U` (from `\Users\...`) as a
12325        // Unicode escape and fail to parse - the same trap `magi.toml`'s own
12326        // `{{ vars.cache }}` rendering documents.
12327        std::fs::write(
12328            &config,
12329            format!(
12330                "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
12331                 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
12332                cache_dir.display()
12333            ),
12334        )
12335        .unwrap();
12336        Opts {
12337            config: Some(config),
12338            repo: dir.join("repo"),
12339            ..Opts::default()
12340        }
12341    }
12342
12343    #[tokio::test]
12344    async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
12345        let dir = tempfile::tempdir().unwrap();
12346        let home = dir.path().join("home");
12347        let cache_dir = dir.path().join("cache");
12348        std::fs::create_dir_all(&cache_dir).unwrap();
12349        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12350        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12351
12352        // Nobody has asked this daemon to stop, which is the ordinary case;
12353        // the skip that a stop buys is asserted by its own test below.
12354        let running = Stop::new();
12355        let mut last_checked = None;
12356        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12357        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
12358            .await;
12359        assert_eq!(
12360            crate::disk::dir_size(&cache_dir),
12361            0,
12362            "over the cap on the first check ever: pruned at once, no idle queue required"
12363        );
12364        assert_eq!(last_checked, Some(t0));
12365
12366        // A fresh oversized file lands, but the next check is not due yet.
12367        std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
12368        let too_soon = t0 + jiff::SignedDuration::from_secs(1);
12369        maybe_prune_cache_between_runs(
12370            &opts.repo,
12371            &opts,
12372            &home,
12373            &running,
12374            &mut last_checked,
12375            too_soon,
12376        )
12377        .await;
12378        assert_eq!(
12379            crate::disk::dir_size(&cache_dir),
12380            10,
12381            "too soon since the last check: left alone rather than rescanned every call"
12382        );
12383        assert_eq!(
12384            last_checked,
12385            Some(t0),
12386            "an idle check does not reset the clock"
12387        );
12388
12389        // Once the interval elapses, the same oversized cache is caught again.
12390        let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
12391        maybe_prune_cache_between_runs(
12392            &opts.repo,
12393            &opts,
12394            &home,
12395            &running,
12396            &mut last_checked,
12397            due_again,
12398        )
12399        .await;
12400        assert_eq!(
12401            crate::disk::dir_size(&cache_dir),
12402            0,
12403            "due again: pruned back under the cap"
12404        );
12405    }
12406
12407    /// A stop must not queue behind housekeeping. The prune below is a
12408    /// synchronous walk of the whole cache with no await point in it, so a
12409    /// loop that entered it could not get back to its own `stopped()` test
12410    /// until the walk finished - and because no run is in flight at this
12411    /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
12412    /// the stop had already landed. The idle branch has always made this same
12413    /// check before reaching `janitor`; the between-runs path makes it too.
12414    #[tokio::test]
12415    async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
12416        let dir = tempfile::tempdir().unwrap();
12417        let home = dir.path().join("home");
12418        let cache_dir = dir.path().join("cache");
12419        std::fs::create_dir_all(&cache_dir).unwrap();
12420        std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
12421        let opts = cache_check_opts(dir.path(), &cache_dir, 1);
12422
12423        let stop = Stop::new();
12424        stop.stop();
12425        assert!(
12426            !stop.finishing(),
12427            "no run is in flight at a between-runs boundary, so nothing else \
12428             would tell the operator this stop had not taken effect yet"
12429        );
12430
12431        let mut last_checked = None;
12432        let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
12433        maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
12434            .await;
12435        assert_eq!(
12436            crate::disk::dir_size(&cache_dir),
12437            10,
12438            "over its cap, and due for the first check ever, but a stop outranks \
12439             it: the cap is a standing policy the next start measures again"
12440        );
12441        assert_eq!(
12442            last_checked, None,
12443            "a check that never happened must not claim the interval"
12444        );
12445    }
12446
12447    /// A backlog must not starve cache pruning. The finite cache worker runs
12448    /// independently of queue drain and must not consume any task attempts.
12449    #[tokio::test]
12450    async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
12451        let dir = tempfile::tempdir().unwrap();
12452        let cache_dir = dir.path().join("cache");
12453        std::fs::create_dir_all(&cache_dir).unwrap();
12454        std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
12455
12456        let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
12457        opts.poll = Duration::from_millis(20);
12458        opts.max_attempts = 1_000;
12459
12460        let queue = Queue::at(dir.path().join("queue"));
12461        for i in 0..128 {
12462            let mut task = Task::new(
12463                format!("queued work {i}"),
12464                format!("queued work {i}"),
12465                opts.repo.clone(),
12466                Source::Human,
12467            );
12468            queue.put(&mut task).unwrap();
12469        }
12470
12471        let home = dir.path().join("home");
12472        let worktrees = dir.path().join("wt");
12473        run_service_worker(
12474            &home,
12475            serde_json::to_value(ServiceWorker {
12476                opts,
12477                queue: queue.root().to_path_buf(),
12478                worktrees_root: worktrees,
12479                operation: "cache".to_owned(),
12480            })
12481            .unwrap(),
12482        )
12483        .await
12484        .unwrap();
12485        let after = queue.list();
12486        assert_eq!(after.len(), 128);
12487        assert!(
12488            after
12489                .iter()
12490                .all(|task| task.status.runnable() && task.attempts == 0)
12491        );
12492
12493        assert_eq!(
12494            crate::disk::dir_size(&cache_dir),
12495            0,
12496            "an oversized cache must not be left to grow unboundedly just because the \
12497             queue kept the loop busy the whole time"
12498        );
12499    }
12500
12501    #[test]
12502    fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
12503        let dir = tempfile::tempdir().unwrap();
12504        let queue = Queue::at(dir.path().join("queue"));
12505        let questions = Questions::at(dir.path().join("questions"));
12506        let mut task = task();
12507        queue.put(&mut task).unwrap();
12508
12509        let mut task_question = ask::Question::new(
12510            task.id.clone(),
12511            crate::conduct::NODE.to_owned(),
12512            "conduct".to_owned(),
12513            "Which backend?".to_owned(),
12514            String::new(),
12515            Vec::new(),
12516        );
12517        questions.put(&mut task_question).unwrap();
12518        task.block(vec![task_question.id.clone()], None);
12519        queue.put(&mut task).unwrap();
12520
12521        let mut run_question = ask::Question::new(
12522            "20260101-000000-run1".to_owned(),
12523            "review".to_owned(),
12524            "reviewer-1".to_owned(),
12525            "Run question".to_owned(),
12526            String::new(),
12527            Vec::new(),
12528        );
12529        questions.put(&mut run_question).unwrap();
12530
12531        // A question from another node whose `run` happens to equal this
12532        // task's id — the same field, filled in for an unrelated reason. Only
12533        // `crate::conduct::NODE` questions use `run` as a task id; this one
12534        // must never be touched by this reconciliation, even after release.
12535        let mut coincidental = ask::Question::new(
12536            task.id.clone(),
12537            "review".to_owned(),
12538            "reviewer-1".to_owned(),
12539            "Unrelated review question".to_owned(),
12540            String::new(),
12541            Vec::new(),
12542        );
12543        questions.put(&mut coincidental).unwrap();
12544
12545        reconcile_task_questions(&queue, &questions);
12546        assert!(questions.get(&task_question.id).unwrap().status.open());
12547        assert!(questions.get(&run_question.id).unwrap().status.open());
12548        assert!(questions.get(&coincidental.id).unwrap().status.open());
12549
12550        task.release();
12551        queue.put(&mut task).unwrap();
12552        reconcile_task_questions(&queue, &questions);
12553        assert_eq!(
12554            questions.get(&task_question.id).unwrap().status,
12555            ask::QuestionStatus::Abandoned
12556        );
12557        assert!(
12558            questions.get(&run_question.id).unwrap().status.open(),
12559            "run questions remain the run janitor's responsibility"
12560        );
12561        assert!(
12562            questions.get(&coincidental.id).unwrap().status.open(),
12563            "a non-conductor question must not be abandoned just because its \
12564             run id coincides with a task id"
12565        );
12566    }
12567
12568    #[test]
12569    fn a_freshly_started_running_task_is_never_stalled() {
12570        let dir = tempfile::tempdir().unwrap();
12571        let mut t = task();
12572        t.start("run-1".to_owned());
12573        // `updated_at` is `Timestamp::now()`, left alone: no live daemon
12574        // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
12575        assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
12576    }
12577
12578    #[test]
12579    fn a_long_running_task_with_no_live_daemon_is_stalled() {
12580        let dir = tempfile::tempdir().unwrap();
12581        let mut t = task();
12582        t.start("run-1".to_owned());
12583        t.updated_at = Timestamp::now()
12584            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12585        assert!(is_stalled(&t, dir.path(), Timestamp::now()));
12586        assert_eq!(
12587            stalled_tasks(
12588                &Queue::at(dir.path().join("q")),
12589                dir.path(),
12590                Timestamp::now()
12591            )
12592            .len(),
12593            0,
12594            "the task was never written to this queue"
12595        );
12596    }
12597
12598    #[test]
12599    fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
12600        let dir = tempfile::tempdir().unwrap();
12601        let mut t = task();
12602        t.id = "20260903-080340-0167".to_owned();
12603        t.start("20260903-080619-01c2".to_owned());
12604        t.updated_at = Timestamp::now()
12605            - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
12606
12607        let mut status = Status::new();
12608        status.current = vec![Current {
12609            worker: None,
12610            task: t.id.clone(),
12611            run: "20260903-080619-01c2".to_owned(),
12612        }];
12613        write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
12614
12615        assert!(
12616            !is_stalled(&t, dir.path(), Timestamp::now()),
12617            "a live daemon's own heartbeat rules out stalled, however long the task has run"
12618        );
12619    }
12620
12621    /// Rewrite a task's `updated_at` on disk directly, bypassing
12622    /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
12623    /// a fixture look like it has genuinely been `running` for a while.
12624    fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
12625        let path = queue.path_of(id);
12626        let body = std::fs::read_to_string(&path).unwrap();
12627        let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
12628        let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
12629        v["updated_at"] = serde_json::Value::String(old.to_string());
12630        std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
12631    }
12632
12633    #[test]
12634    fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
12635        // The realistic `poll()` ordering, not `is_stalled` in isolation:
12636        // `reclaim_orphaned_running` runs first, on every poll, and settles
12637        // any `running` task whose claim it can actually take. For most
12638        // crashes that is immediate - a dead pid is proof enough for
12639        // `sweep_stale_claims` to drop the lock the same tick, and the very
12640        // next claim attempt succeeds. But a lock whose pid cannot be parsed
12641        // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
12642        // `sweep_stale_claims`'s own doc), so the lock - and the claim
12643        // failure behind it - can legitimately outlive many polls. This is
12644        // exactly the gap `stalled_tasks` exists to surface well before that
12645        // six-hour sweep would: reclaim leaves the task `running`, and it
12646        // must still reach the conductor as stalled.
12647        let dir = tempfile::tempdir().unwrap();
12648        let queue = Queue::at(dir.path().join("queue"));
12649        let home = dir.path().join("home");
12650
12651        let mut t = task();
12652        t.id = "20260101-000001-lock".to_owned();
12653        t.start("run-1".to_owned());
12654        queue.put(&mut t).unwrap();
12655        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12656        std::fs::write(
12657            dir.path().join("queue").join(format!("{}.lock", t.id)),
12658            "not a pid",
12659        )
12660        .unwrap();
12661
12662        let now = Timestamp::now();
12663        assert!(
12664            reclaim_orphaned_running(&queue, 2, &Default::default()).is_empty(),
12665            "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
12666             and reclaim must leave the task alone"
12667        );
12668        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
12669
12670        let stalled = stalled_tasks(&queue, &home, now);
12671        assert_eq!(
12672            stalled.len(),
12673            1,
12674            "reclaim's inability to claim it yet must not hide it from the conductor"
12675        );
12676        assert_eq!(stalled[0].id, t.id);
12677    }
12678
12679    #[test]
12680    fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
12681        let dir = tempfile::tempdir().unwrap();
12682        crate::run::set_home(dir.path().join("run-home"));
12683        let queue = Queue::at(dir.path().join("queue"));
12684        let home = dir.path().join("home");
12685        let questions = Questions::at(dir.path().join("questions"));
12686
12687        let mut t = task();
12688        t.id = "20260101-000003-dead".to_owned();
12689        t.start("missing-run".to_owned());
12690        queue.put(&mut t).unwrap();
12691        backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
12692
12693        // This is the real poll ordering: retain the deterministic stalled
12694        // input before a claim proves the owner is gone and reclaims it.
12695        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12696        assert_eq!(
12697            stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
12698            [&t.id]
12699        );
12700        assert_eq!(
12701            reclaim_orphaned_running(&queue, 2, &Default::default()),
12702            [t.id.clone()]
12703        );
12704        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
12705
12706        // Reclaim drops its guard before conductor decisions are applied, so
12707        // the decision for the captured stalled input has a real write path.
12708        crate::conduct::apply(
12709            &queue,
12710            &questions,
12711            &crate::conduct::Verdict {
12712                decisions: vec![crate::conduct::Decision {
12713                    id: t.id.clone(),
12714                    recovery: Some(crate::conduct::Recovery::Requeue),
12715                    ..crate::conduct::Decision::default()
12716                }],
12717            },
12718        )
12719        .unwrap();
12720        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
12721    }
12722
12723    #[test]
12724    fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
12725        let dir = tempfile::tempdir().unwrap();
12726        let queue = Queue::at(dir.path().join("queue"));
12727        let home = dir.path().join("home");
12728
12729        let mut fresh = task();
12730        fresh.id = "20260101-000001-aaaa".to_owned();
12731        fresh.start("run-1".to_owned());
12732        queue.put(&mut fresh).unwrap();
12733
12734        let mut old = task();
12735        old.id = "20260101-000002-bbbb".to_owned();
12736        old.start("run-2".to_owned());
12737        queue.put(&mut old).unwrap();
12738        backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
12739
12740        let stalled = stalled_tasks(&queue, &home, Timestamp::now());
12741        assert_eq!(stalled.len(), 1);
12742        assert_eq!(stalled[0].id, old.id);
12743    }
12744
12745    #[test]
12746    fn queued_and_finished_task_views_partition_by_status() {
12747        let dir = tempfile::tempdir().unwrap();
12748        let queue = Queue::at(dir.path().join("queue"));
12749
12750        let mut queued = task();
12751        queued.id = "20260101-000001-aaaa".to_owned();
12752        queue.put(&mut queued).unwrap();
12753
12754        let mut failed = task();
12755        failed.id = "20260101-000002-bbbb".to_owned();
12756        failed.start("run-1".to_owned());
12757        failed.fail("gate red", 5);
12758        queue.put(&mut failed).unwrap();
12759
12760        let mut held = task();
12761        held.id = "20260101-000003-cccc".to_owned();
12762        held.hold_machine(None);
12763        queue.put(&mut held).unwrap();
12764
12765        let mut running = task();
12766        running.id = "20260101-000004-dddd".to_owned();
12767        running.start("run-2".to_owned());
12768        queue.put(&mut running).unwrap();
12769
12770        let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
12771        assert_eq!(queued_ids, [queued.id.clone()]);
12772
12773        let mut finished_ids: Vec<String> =
12774            finished_tasks(&queue).into_iter().map(|t| t.id).collect();
12775        finished_ids.sort_unstable();
12776        let mut want = vec![failed.id.clone(), held.id.clone()];
12777        want.sort_unstable();
12778        assert_eq!(finished_ids, want);
12779    }
12780
12781    #[test]
12782    fn dependency_resolution_preserves_existing_short_and_full_running_chains() {
12783        for short in [false, true] {
12784            let dir = tempfile::tempdir().unwrap();
12785            let queue = Queue::at(dir.path().join("queue"));
12786            let questions = ask::Questions::at(dir.path().join("questions"));
12787            let mut running = task();
12788            running.id = "20261013-192213-feb2".into();
12789            running.start("existing-run".into());
12790            queue.put(&mut running).unwrap();
12791            let mut middle = task();
12792            middle.id = "20261013-193611-ca5b".into();
12793            middle.block(
12794                vec![if short {
12795                    "feb2".into()
12796                } else {
12797                    running.id.clone()
12798                }],
12799                None,
12800            );
12801            queue.put(&mut middle).unwrap();
12802            let mut waiting = task();
12803            waiting.id = "20261013-202849-ee37".into();
12804            waiting.block(
12805                vec![if short {
12806                    "ca5b".into()
12807                } else {
12808                    middle.id.clone()
12809                }],
12810                Some("wait for implementation".into()),
12811            );
12812            queue.put(&mut waiting).unwrap();
12813            assert_eq!(queue.get("ca5b").unwrap().id, middle.id);
12814            let inv = crate::blockers::Inventory::load(&queue, &questions);
12815            assert_eq!(inv.waits_on(&waiting), ["ca5b (blocked → feb2 running)"]);
12816            assert!(inv.stuck().is_empty());
12817            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12818            assert!(report.quarantined.is_empty());
12819            assert!(report.asked.is_empty());
12820            resolve_blockers(&queue, &questions);
12821            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12822            assert!(questions.list().is_empty());
12823            // Finishing the transitive prerequisite alone does not satisfy
12824            // the task's direct dependency.
12825            running.succeed(CompletionContext::new(
12826                CompletionActor::DaemonSettle,
12827                None,
12828                dir.path(),
12829                &running,
12830            ));
12831            queue.put(&mut running).unwrap();
12832            resolve_blockers(&queue, &questions);
12833            assert_eq!(queue.get(&middle.id).unwrap().status, TaskStatus::Queued);
12834            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12835            middle = queue.get(&middle.id).unwrap();
12836            middle.succeed(CompletionContext::new(
12837                CompletionActor::DaemonSettle,
12838                None,
12839                dir.path(),
12840                &middle,
12841            ));
12842            queue.put(&mut middle).unwrap();
12843            resolve_blockers(&queue, &questions);
12844            let after = queue.get(&waiting.id).unwrap();
12845            assert_eq!(after.status, TaskStatus::Queued);
12846            assert!(after.blocked_by.is_empty());
12847            assert_eq!(after.instruction, waiting.instruction);
12848        }
12849    }
12850
12851    #[test]
12852    fn dependency_resolution_unknown_records_never_hold_ask_or_release() {
12853        for future_schema in [false, true] {
12854            let name = "20261013-193611-ca5b";
12855            let mut future = task();
12856            future.id = name.into();
12857            future.schema = crate::queue::SCHEMA + 1;
12858            let contents = if future_schema {
12859                serde_json::to_string(&future).unwrap()
12860            } else {
12861                "corrupt".into()
12862            };
12863            let dir = tempfile::tempdir().unwrap();
12864            let queue = Queue::at(dir.path().join("queue"));
12865            let questions = ask::Questions::at(dir.path().join("questions"));
12866            let mut waiting = task();
12867            waiting.id = "20261013-202849-ee37".into();
12868            waiting.block(vec!["ca5b".into()], None);
12869            queue.put(&mut waiting).unwrap();
12870            std::fs::write(queue.path_of(name), contents).unwrap();
12871            assert_eq!(queue.resolve_id("ca5b").unwrap(), name);
12872            assert!(
12873                crate::queue::missing_blockers(&queue, &questions, &waiting.blocked_by).is_empty()
12874            );
12875            let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12876            assert!(report.asked.is_empty());
12877            resolve_blockers(&queue, &questions);
12878            assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12879            assert!(questions.list().is_empty());
12880        }
12881        let dir = tempfile::tempdir().unwrap();
12882        let queue = Queue::at(dir.path().join("queue"));
12883        let questions = ask::Questions::at(dir.path().join("questions"));
12884        let mut waiting = task();
12885        waiting.id = "20261013-202849-ee37".into();
12886        waiting.block(vec!["ca5b".into()], None);
12887        queue.put(&mut waiting).unwrap();
12888        let mut done = task();
12889        done.id = "20261013-193611-ca5b".into();
12890        done.succeed(CompletionContext::new(
12891            CompletionActor::Cli,
12892            None,
12893            dir.path(),
12894            &done,
12895        ));
12896        queue.put(&mut done).unwrap();
12897        // An unreadable second match must not disappear from uniqueness
12898        // checks just because Queue::list skips it.
12899        std::fs::write(queue.path_of("20261014-193611-ca5b"), "bad").unwrap();
12900        assert!(queue.get("ca5b").is_err());
12901        assert_eq!(
12902            crate::queue::dependency(&queue, &questions, "ca5b"),
12903            crate::queue::Dependency::Ambiguous
12904        );
12905        resolve_blockers(&queue, &questions);
12906        let report = crate::triage::run_once(&queue, &questions, None, Timestamp::now());
12907        assert!(report.asked.is_empty());
12908        assert_eq!(queue.get(&waiting.id).unwrap().status, TaskStatus::Blocked);
12909        assert_eq!(queue.get(&done.id).unwrap().status, TaskStatus::Done);
12910    }
12911
12912    #[test]
12913    fn dependency_resolution_preserves_independent_consent_and_holds_after_completion() {
12914        for held in [false, true] {
12915            for question in [false, true] {
12916                for reference in ["ca5b", "20261013-193611-ca5b"] {
12917                    let dir = tempfile::tempdir().unwrap();
12918                    let queue = Queue::at(dir.path().join("queue"));
12919                    let questions = ask::Questions::at(dir.path().join("questions"));
12920                    let mut prerequisite = task();
12921                    prerequisite.id = "20261013-193611-ca5b".into();
12922                    prerequisite.start("existing-run".into());
12923                    queue.put(&mut prerequisite).unwrap();
12924                    let mut waiting = task();
12925                    waiting.id = "20261013-202849-ee37".into();
12926                    if held {
12927                        waiting.hold_machine(Some("waiting for separate consent".into()));
12928                    }
12929                    queue.put(&mut waiting).unwrap();
12930                    let reason = "Deleting saved data requires separate owner consent";
12931                    crate::conduct::apply(
12932                        &queue,
12933                        &questions,
12934                        &crate::conduct::Verdict {
12935                            decisions: vec![crate::conduct::Decision {
12936                                id: waiting.id.clone(),
12937                                blocked_by: vec![reference.into()],
12938                                question: question.then(|| "May the saved data be deleted?".into()),
12939                                recovery: (!question).then_some(crate::conduct::Recovery::Hold),
12940                                reason: Some(reason.into()),
12941                                ..crate::conduct::Decision::default()
12942                            }],
12943                        },
12944                    )
12945                    .unwrap();
12946                    let before = queue.get(&waiting.id).unwrap();
12947                    if question {
12948                        assert_eq!(before.status, TaskStatus::Blocked);
12949                        let q = questions.get(&before.blocked_by[0]).unwrap();
12950                        assert_eq!(q.summary, "May the saved data be deleted?");
12951                        assert!(q.status.open());
12952                    } else {
12953                        assert_eq!(before.status, TaskStatus::Held);
12954                        let recorded_reason = before.hold_reason.as_deref().unwrap();
12955                        assert!(recorded_reason.starts_with(reason));
12956                        if held {
12957                            assert!(recorded_reason.contains("waiting for separate consent"));
12958                        }
12959                    }
12960                    prerequisite.succeed(CompletionContext::new(
12961                        CompletionActor::DaemonSettle,
12962                        None,
12963                        dir.path(),
12964                        &prerequisite,
12965                    ));
12966                    queue.put(&mut prerequisite).unwrap();
12967                    resolve_blockers(&queue, &questions);
12968                    let after = queue.get(&waiting.id).unwrap();
12969                    assert_eq!(after.status, before.status);
12970                    assert_eq!(after.blocked_by, before.blocked_by);
12971                    assert_eq!(after.hold_reason, before.hold_reason);
12972                    assert_eq!(after.instruction, waiting.instruction);
12973                    if question {
12974                        assert!(questions.get(&after.blocked_by[0]).unwrap().status.open());
12975                    }
12976                    assert!(
12977                        queue.next_runnable().is_none(),
12978                        "dependency completion is not consent"
12979                    );
12980                }
12981            }
12982        }
12983    }
12984
12985    #[test]
12986    fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
12987        let dir = tempfile::tempdir().unwrap();
12988        let queue = Queue::at(dir.path().join("queue"));
12989        let questions = ask::Questions::at(dir.path().join("questions"));
12990
12991        let mut dep = task();
12992        dep.id = "20260101-000001-dep0".to_owned();
12993        dep.succeed(CompletionContext::new(
12994            CompletionActor::DaemonSettle,
12995            None,
12996            dir.path(),
12997            &dep,
12998        ));
12999        queue.put(&mut dep).unwrap();
13000
13001        let mut still_going = task();
13002        still_going.id = "20260101-000002-dep1".to_owned();
13003        queue.put(&mut still_going).unwrap();
13004
13005        let mut blocked = task();
13006        blocked.id = "20260101-000003-main".to_owned();
13007        blocked.block(
13008            vec![dep.id.clone(), still_going.id.clone()],
13009            Some("waits on both".to_owned()),
13010        );
13011        queue.put(&mut blocked).unwrap();
13012
13013        resolve_blockers(&queue, &questions);
13014
13015        let after = queue.get(&blocked.id).unwrap();
13016        assert_eq!(
13017            after.status,
13018            TaskStatus::Blocked,
13019            "one dependency is still outstanding"
13020        );
13021        assert_eq!(after.blocked_by, [still_going.id.clone()]);
13022    }
13023
13024    #[test]
13025    fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
13026        let dir = tempfile::tempdir().unwrap();
13027        let queue = Queue::at(dir.path().join("queue"));
13028        let questions = ask::Questions::at(dir.path().join("questions"));
13029
13030        let mut q = crate::ask::Question::new(
13031            "20260101-000001-main".to_owned(),
13032            crate::conduct::NODE.to_owned(),
13033            "conduct".to_owned(),
13034            "Which backend?".to_owned(),
13035            String::new(),
13036            Vec::new(),
13037        );
13038        questions.put(&mut q).unwrap();
13039        q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
13040            .unwrap();
13041        questions.put(&mut q).unwrap();
13042
13043        let mut blocked = task();
13044        blocked.id = "20260101-000001-main".to_owned();
13045        blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
13046        queue.put(&mut blocked).unwrap();
13047
13048        resolve_blockers(&queue, &questions);
13049
13050        let after = queue.get(&blocked.id).unwrap();
13051        assert_eq!(
13052            after.status,
13053            TaskStatus::Queued,
13054            "the only blocker resolved"
13055        );
13056        assert_eq!(after.answers.len(), 1);
13057        assert_eq!(after.answers[0].question, "Which backend?");
13058        assert_eq!(after.answers[0].answer, "SQLite");
13059
13060        // And the run this task starts next is told about it.
13061        let instruction = instruction_for(&after);
13062        assert!(instruction.contains("Which backend?"));
13063        assert!(instruction.contains("SQLite"));
13064    }
13065
13066    #[test]
13067    fn resolve_blockers_holds_a_task_whose_conductor_question_was_abandoned() {
13068        let dir = tempfile::tempdir().unwrap();
13069        let queue = Queue::at(dir.path().join("queue"));
13070        let questions = ask::Questions::at(dir.path().join("questions"));
13071
13072        let mut q = crate::ask::Question::new(
13073            "20260101-000001-main".to_owned(),
13074            crate::conduct::NODE.to_owned(),
13075            "conduct".to_owned(),
13076            "Is the setup done?".to_owned(),
13077            String::new(),
13078            Vec::new(),
13079        );
13080        q.abandon("no answer within 60s of asking");
13081        questions.put(&mut q).unwrap();
13082
13083        let mut blocked = task();
13084        blocked.id = "20260101-000001-main".to_owned();
13085        blocked.block(vec![q.id.clone()], Some("setup?".to_owned()));
13086        queue.put(&mut blocked).unwrap();
13087
13088        resolve_blockers(&queue, &questions);
13089
13090        let after = queue.get(&blocked.id).unwrap();
13091        assert_eq!(
13092            after.status,
13093            TaskStatus::Held,
13094            "never left blocked on nothing"
13095        );
13096        assert!(!after.operator_held(), "a machine hold, for triage");
13097        assert!(
13098            after
13099                .hold_reason
13100                .as_deref()
13101                .unwrap_or_default()
13102                .contains("went unanswered")
13103        );
13104    }
13105
13106    #[test]
13107    fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
13108        // Reproduces the reported bug (task 3958): a task held out of
13109        // attempts, blocked on a `crate::conduct` follow-up question, must
13110        // come back `held` once that question is answered - never `queued`,
13111        // whatever the answer said - or it silently re-enters the
13112        // competition queue with its attempts already exhausted.
13113        let dir = tempfile::tempdir().unwrap();
13114        let queue = Queue::at(dir.path().join("queue"));
13115        let questions = ask::Questions::at(dir.path().join("questions"));
13116
13117        let mut q = crate::ask::Question::new(
13118            "20260101-000001-main".to_owned(),
13119            crate::conduct::NODE.to_owned(),
13120            "conduct".to_owned(),
13121            "How should this be handled?".to_owned(),
13122            String::new(),
13123            Vec::new(),
13124        );
13125        questions.put(&mut q).unwrap();
13126        q.answer(crate::ask::Answer::Text(
13127            "leave it held, a human will look at it later".to_owned(),
13128        ))
13129        .unwrap();
13130        questions.put(&mut q).unwrap();
13131
13132        let mut held = task();
13133        held.id = "20260101-000001-main".to_owned();
13134        held.hold_machine(Some("out of attempts".to_owned()));
13135        held.block(vec![q.id.clone()], Some("what now?".to_owned()));
13136        queue.put(&mut held).unwrap();
13137
13138        resolve_blockers(&queue, &questions);
13139
13140        let after = queue.get(&held.id).unwrap();
13141        assert_eq!(after.status, TaskStatus::Held);
13142        assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
13143        assert_eq!(
13144            after.answers[0].answer,
13145            "leave it held, a human will look at it later"
13146        );
13147    }
13148
13149    #[test]
13150    fn resolve_blockers_releases_a_task_whose_dependency_was_deleted_on_purpose() {
13151        let dir = tempfile::tempdir().unwrap();
13152        let queue = Queue::at(dir.path().join("queue"));
13153        let questions = ask::Questions::at(dir.path().join("questions"));
13154        let mut dep = task();
13155        dep.id = "20260101-000001-gone".to_owned();
13156        queue.put(&mut dep).unwrap();
13157        let mut blocked = task();
13158        blocked.id = "20260101-000003-main".to_owned();
13159        blocked.block(vec![dep.id.clone()], None);
13160        queue.put(&mut blocked).unwrap();
13161
13162        // Claimed, so `remove` cannot rewrite it and the resolver must.
13163        let claim = queue.claim(&blocked.id).unwrap();
13164        queue.remove(&dep.id, false, &questions).unwrap();
13165        drop(claim);
13166        resolve_blockers(&queue, &questions);
13167
13168        let after = queue.get(&blocked.id).unwrap();
13169        assert_eq!(after.status, TaskStatus::Queued);
13170        assert!(after.blocked_by.is_empty());
13171    }
13172
13173    #[test]
13174    fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
13175        // Reproduces the reported bug: a task blocked on a task id that was
13176        // removed (`magi task rm`, or deleted by hand) can never see that id
13177        // reach `Done`, so the ordinary per-id loop has nothing to notice and
13178        // would otherwise leave the task `blocked` forever with no way for an
13179        // operator to find out why.
13180        let dir = tempfile::tempdir().unwrap();
13181        let queue = Queue::at(dir.path().join("queue"));
13182        let questions = ask::Questions::at(dir.path().join("questions"));
13183
13184        let mut still_going = task();
13185        still_going.id = "20260101-000002-dep1".to_owned();
13186        queue.put(&mut still_going).unwrap();
13187
13188        let mut blocked = task();
13189        blocked.id = "20260101-000003-main".to_owned();
13190        blocked.block(
13191            vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
13192            Some("waits on both".to_owned()),
13193        );
13194        queue.put(&mut blocked).unwrap();
13195
13196        resolve_blockers(&queue, &questions);
13197
13198        let after = queue.get(&blocked.id).unwrap();
13199        assert_eq!(
13200            after.status,
13201            TaskStatus::Held,
13202            "a missing dependency must not leave the task blocked forever"
13203        );
13204        assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
13205        assert!(after.blocked_by.is_empty());
13206        let reason = after.hold_reason.as_deref().unwrap_or_default();
13207        assert!(
13208            reason.contains("20260101-000001-gone"),
13209            "the missing id must be named so an operator can tell what happened: {reason}"
13210        );
13211        assert!(
13212            reason.contains(&still_going.id),
13213            "the still-valid dependency must not silently vanish from the record: {reason}"
13214        );
13215    }
13216
13217    #[test]
13218    fn instruction_for_is_unchanged_without_any_answers() {
13219        let t = task();
13220        assert_eq!(instruction_for(&t), t.instruction);
13221    }
13222
13223    #[test]
13224    fn task_attachments_are_absolute_and_a_missing_file_is_an_error() {
13225        let dir = tempfile::tempdir().unwrap();
13226        let q = Queue::at(dir.path().join("queue"));
13227        let src = dir.path().join("shot.png");
13228        std::fs::write(&src, "x").unwrap();
13229        let mut t = task();
13230        q.attach(&mut t, &[src]).unwrap();
13231        let paths = task_attachments(&q, &t).unwrap();
13232        assert_eq!(paths.len(), 1);
13233        assert!(paths[0].is_absolute() && paths[0].is_file());
13234        std::fs::remove_file(&paths[0]).unwrap();
13235        let err = task_attachments(&q, &t).unwrap_err().to_string();
13236        assert!(err.contains("shot.png"), "{err}");
13237    }
13238
13239    #[tokio::test]
13240    async fn config_failure_notices_distinguish_boundaries_and_targets_after_restart() {
13241        let dir = tempfile::tempdir().unwrap();
13242        let queue_path = dir.path().join("queue");
13243        let queue = Queue::at(queue_path.clone());
13244        let mut t = task();
13245        t.source = Source::Agent {
13246            run: "originating-chat".into(),
13247            node: crate::queue::CHAT_NODE.into(),
13248        };
13249        let fetch = anyhow::anyhow!("network unavailable").context(crate::config::ConfigFailure {
13250            stage: "config-fetch",
13251            target: "origin/main".into(),
13252        });
13253        record_config_failure(&mut t, &fetch);
13254        t.hold_machine(Some(format!("{fetch:#}")));
13255        let fetch_key = t.chat_notice_due().unwrap();
13256        t.chat_notices.push(fetch_key.clone());
13257        queue.put(&mut t).unwrap();
13258
13259        let queue = Queue::at(queue_path);
13260        let mut t = queue.get(&t.id).unwrap();
13261        let a = dir.path().join("a.toml");
13262        let b = dir.path().join("b.toml");
13263        for (path, text, new_cause) in [
13264            (&a, "[graph", true),
13265            (&a, "[verify", false),
13266            (&a, "[graph]\nimplementers = 'invalid-type'", true),
13267            (&b, "[graph]\nimplementers = 'invalid-type'", true),
13268        ] {
13269            t.release_operator("test", None);
13270            std::fs::write(path, text).unwrap();
13271            let error = Config::discover_fetched(dir.path(), Some(path))
13272                .await
13273                .unwrap_err();
13274            record_config_failure(&mut t, &error);
13275            t.hold_machine(Some(format!("{error:#}")));
13276            let due = t.chat_notice_due();
13277            assert_eq!(due.is_some(), new_cause, "{error:#}");
13278            if let Some(key) = due {
13279                assert_ne!(key, fetch_key);
13280                t.chat_notices.push(key);
13281            }
13282        }
13283        t.succeed(CompletionContext::new(
13284            CompletionActor::DaemonSettle,
13285            None,
13286            dir.path(),
13287            &t,
13288        ));
13289        assert_eq!(
13290            t.chat_notice_due(),
13291            Some(format!(
13292                "done:{}",
13293                t.completion_history.last().unwrap().occurrence
13294            ))
13295        );
13296    }
13297
13298    #[test]
13299    fn different_missing_attachments_have_distinct_persisted_notice_causes() {
13300        let dir = tempfile::tempdir().unwrap();
13301        let queue_path = dir.path().join("queue");
13302        let queue = Queue::at(queue_path.clone());
13303        let mut t = task();
13304        t.source = crate::queue::Source::Agent {
13305            run: "originating-chat".into(),
13306            node: crate::queue::CHAT_NODE.into(),
13307        };
13308        let a = dir.path().join("a.png");
13309        let b = dir.path().join("b.png");
13310        std::fs::write(&a, "a").unwrap();
13311        std::fs::write(&b, "b").unwrap();
13312        queue.attach(&mut t, &[a, b]).unwrap();
13313        let paths = task_attachments(&queue, &t).unwrap();
13314        for path in &paths {
13315            std::fs::remove_file(path).unwrap();
13316        }
13317        let missing = task_attachments(&queue, &t).unwrap_err();
13318        t.attempts += 1;
13319        let reason = missing.to_string();
13320        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13321        let first = t.chat_notice_due().expect("first attachment notice");
13322        t.chat_notices.push(first.clone());
13323        queue.put(&mut t).unwrap();
13324
13325        let queue = Queue::at(queue_path.clone());
13326        let mut t = queue.get(&t.id).unwrap();
13327        assert!(t.chat_notice_due().is_none(), "restart does not replay");
13328        t.release_operator("test", None);
13329        t.attempts += 1;
13330        let missing = task_attachments(&queue, &t).unwrap_err();
13331        t.fail_startup_target(
13332            "startup-attachments",
13333            missing.name,
13334            "same missing attachment with regenerated wording",
13335            1,
13336        );
13337        assert!(t.chat_notice_due().is_none(), "same object stays quiet");
13338
13339        std::fs::write(&paths[0], "restored").unwrap();
13340        t.release_operator("test", None);
13341        t.attempts += 1;
13342        let missing = task_attachments(&queue, &t).unwrap_err();
13343        let reason = missing.to_string();
13344        t.fail_startup_target("startup-attachments", missing.name, reason, 1);
13345        let second = t
13346            .chat_notice_due()
13347            .expect("different attachment must notify");
13348        assert_ne!(first, second);
13349        assert!(t.hold_reason.as_ref().unwrap().contains("b.png"));
13350    }
13351
13352    #[test]
13353    fn resumed_instruction_is_unchanged_without_any_answers() {
13354        let t = task();
13355        assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
13356    }
13357
13358    #[test]
13359    fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
13360        let mut t = task();
13361        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13362        // The run's own instruction on disk predates the answer: it is the
13363        // plain original text `Runner::start` saved before the operator was
13364        // ever asked anything.
13365        let old = t.instruction.clone();
13366
13367        let refreshed = resumed_instruction(&old, &t);
13368        assert!(refreshed.starts_with(&old), "the original text is kept");
13369        assert!(refreshed.contains("Which backend?"));
13370        assert!(refreshed.contains("SQLite"));
13371    }
13372
13373    #[test]
13374    fn resumed_instruction_keeps_an_original_answers_heading() {
13375        let mut t = task();
13376        t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
13377        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13378
13379        let refreshed = resumed_instruction(&t.instruction, &t);
13380
13381        assert!(
13382            refreshed.starts_with(&t.instruction),
13383            "an answers heading in the original instruction is not the appended block"
13384        );
13385        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
13386        assert!(refreshed.contains("Which backend?"));
13387        assert!(refreshed.contains("SQLite"));
13388
13389        let repeated = resumed_instruction(&refreshed, &t);
13390        assert_eq!(
13391            repeated, refreshed,
13392            "only the final appended block is refreshed"
13393        );
13394    }
13395
13396    #[test]
13397    fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
13398        let mut t = task();
13399        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13400
13401        // A first resume appends the block; a second resume of the same run,
13402        // with no new answer in between, must reproduce exactly the same
13403        // text rather than appending the block a second time.
13404        let once = resumed_instruction(&t.instruction, &t);
13405        let twice = resumed_instruction(&once, &t);
13406        assert_eq!(once, twice);
13407        assert_eq!(once.matches("Which backend?").count(), 1);
13408
13409        // A later answer replaces the block wholesale rather than growing it.
13410        t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
13411        let refreshed = resumed_instruction(&once, &t);
13412        assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
13413        assert!(refreshed.contains("Which backend?"));
13414        assert!(refreshed.contains("Which cache?"));
13415    }
13416
13417    #[test]
13418    fn prepare_instruction_covers_all_three_starters() {
13419        let mut t = task();
13420        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
13421
13422        // Start: a fresh run gets the task text plus every answer so far —
13423        // exactly `instruction_for`.
13424        assert_eq!(
13425            prepare_instruction(&Starter::Start, None, &t),
13426            Some(instruction_for(&t))
13427        );
13428
13429        // Resume: the run's prior instruction is refreshed with the answer,
13430        // not discarded and not left stale.
13431        let old = t.instruction.clone();
13432        assert_eq!(
13433            prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
13434            Some(resumed_instruction(&old, &t))
13435        );
13436
13437        // Review: a review-only pass builds its own instruction from the
13438        // branch's history in `crate::graph`, with no task statement at all -
13439        // this boundary must leave it alone.
13440        assert_eq!(
13441            prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
13442            None
13443        );
13444    }
13445
13446    #[test]
13447    fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
13448        assert_eq!(
13449            choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
13450            Starter::Review("magi/eba2/A".to_owned())
13451        );
13452    }
13453
13454    #[test]
13455    fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
13456        assert_eq!(
13457            choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
13458            Starter::Start,
13459            "a vanished review branch must not fall back to resuming the old run either"
13460        );
13461    }
13462
13463    #[test]
13464    fn a_refused_handover_retries_as_a_review_of_the_same_branch() {
13465        let mut t = task();
13466        t.start("old-run".to_owned());
13467        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
13468        t.release();
13469        let branch = t.review_branch.take();
13470        assert_eq!(
13471            choose_starter(branch.as_deref(), true, Some("old-run")),
13472            Starter::Review("magi/eba2/A".to_owned()),
13473            "a review wins over resuming the old run"
13474        );
13475    }
13476
13477    #[test]
13478    fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
13479        assert_eq!(
13480            choose_starter(None, false, Some("some-run")),
13481            Starter::Resume("some-run".to_owned())
13482        );
13483        assert_eq!(choose_starter(None, false, None), Starter::Start);
13484    }
13485
13486    #[test]
13487    fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
13488        let mut released = task();
13489        released.start("stalled-run".to_owned());
13490        released.requeue();
13491        let unfinished = (!released.fresh_start)
13492            .then(|| Some("stalled-run".to_owned()))
13493            .flatten();
13494        assert_eq!(
13495            choose_starter(None, false, unfinished.as_deref()),
13496            Starter::Start,
13497            "release keeps run history but must not resume it"
13498        );
13499        assert_eq!(released.runs, ["stalled-run"]);
13500    }
13501
13502    #[test]
13503    fn landing_hold_receipt_survives_release_retry_and_checkpoint_removal() {
13504        let dir = tempfile::tempdir().unwrap();
13505        let queue = Queue::at(dir.path().join("queue"));
13506        let mut state = run_state(RunStatus::Blocked);
13507        state.merge_decision = Some(crate::merge_decision::Decision {
13508            question: "hold-inquiry".into(),
13509            target: crate::merge_decision::Target {
13510                pr: "https://example.test/pull/1".into(),
13511                head: "reviewed-head".into(),
13512                language: "en".into(),
13513            },
13514            choice: land::HOLD.into(),
13515            closed: false,
13516            replacement_run: None,
13517            replacement_pr: None,
13518        });
13519        let mut t = task();
13520        t.start(state.id.clone());
13521        settle_and_diagnose(
13522            &mut t,
13523            Verdict {
13524                status: RunStatus::Blocked,
13525                left_pr: true,
13526                quota_hit: false,
13527                parked: false,
13528                no_viable_candidates: false,
13529            },
13530            "held",
13531            2,
13532            &state,
13533        );
13534        queue.put(&mut t).unwrap();
13535        t.release_operator("chat", None);
13536        t.edit("revised".into(), "revised instruction".into())
13537            .unwrap();
13538        queue.put(&mut t).unwrap();
13539        drop(state);
13540        assert_eq!(
13541            queue
13542                .get(&t.id)
13543                .unwrap()
13544                .decision_effects
13545                .get("hold-inquiry"),
13546            Some(&format!("decision: {}", land::HOLD))
13547        );
13548    }
13549
13550    fn stopped_public_run(status: RunStatus) -> RunState {
13551        let mut state = run_state(status);
13552        state.driver_exited = true;
13553        state.config.graph.land = true;
13554        state.config.graph.review_rounds = 1;
13555        state.reviews = vec![review_round(1)];
13556        state.merge = Some(crate::run::MergeOutcome {
13557            mode: MergeMode::Pr,
13558            ok: false,
13559            detail: "landing stopped".into(),
13560            empty: false,
13561        });
13562        state.pr = Some(crate::run::PrRecord {
13563            url: "https://example.test/pull/1".into(),
13564            number: 1,
13565            state: "open".into(),
13566            checks: "red".into(),
13567            round: 1,
13568            rounds: 1,
13569            red_at_merge: Vec::new(),
13570        });
13571        state
13572    }
13573
13574    #[test]
13575    fn stopped_public_owner_resumes_on_release_choice_and_control_after_review_exhaustion() {
13576        for status in [RunStatus::Blocked, RunStatus::Gating] {
13577            let home = tempfile::tempdir().unwrap();
13578            let mut state = stopped_public_run(status);
13579            state.save_under(home.path()).unwrap();
13580            assert!(crate::handover::has_resume_checkpoint(&state, home.path()));
13581            assert!(!exhausted_review_budget(&state));
13582            let mut task = held_task_with(&state.id);
13583            task.release();
13584            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13585            assert_eq!(
13586                choose_starter(None, false, unfinished.as_deref()),
13587                Starter::Resume(state.id.clone())
13588            );
13589            let question = action_question(&state.id, resume_action(&state.id));
13590            assert_eq!(
13591                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13592                    state.clone()
13593                )),
13594                ActionDecision::Resume(state.id.clone())
13595            );
13596            // The control-plane command uses this same preflight before pinning.
13597            assert_eq!(
13598                crate::resume::validate(home.path(), &state.id).unwrap().id,
13599                state.id
13600            );
13601            let queue = Queue::at(home.path().join("queue"));
13602            let mut controlled = Task::new(
13603                "resume land".into(),
13604                state.instruction.clone(),
13605                state.repo.clone(),
13606                Source::Agent {
13607                    run: "talk".into(),
13608                    node: crate::queue::CHAT_NODE.into(),
13609                },
13610            );
13611            controlled.runs.push(state.id.clone());
13612            controlled.hold_machine(Some("land stopped".into()));
13613            queue.put(&mut controlled).unwrap();
13614            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13615            assert_eq!(resumed.status, TaskStatus::Queued);
13616            assert_eq!(
13617                resumed.resume_override.unwrap().pinned_run,
13618                Some(state.id.clone())
13619            );
13620            assert_eq!(resumed.attempts, 0);
13621        }
13622    }
13623
13624    #[test]
13625    fn exhausted_gate_failure_with_clean_or_disabled_reviews_is_not_resumable() {
13626        for review_rounds in [0, 1] {
13627            let home = tempfile::tempdir().unwrap();
13628            let mut state = run_state(RunStatus::Blocked);
13629            state.config.graph.review_rounds = review_rounds;
13630            if review_rounds > 0 {
13631                let mut review = review_round(1);
13632                review.clean = true;
13633                state.reviews = vec![review];
13634            }
13635            state.gate_ran = true;
13636            state.gate = vec![crate::run::CommandOutcome {
13637                command: "verify".into(),
13638                code: Some(1),
13639                output_tail: "gate failed after repair budget exhausted".into(),
13640                duration_ms: 0,
13641                resource_blocked: false,
13642                ..Default::default()
13643            }];
13644            state.save_under(home.path()).unwrap();
13645            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13646            assert!(exhausted_review_budget(&state));
13647            let mut task = held_task_with(&state.id);
13648            task.release();
13649            assert!(unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())).is_none());
13650            let question = action_question(&state.id, resume_action(&state.id));
13651            assert_ne!(
13652                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13653                    state.clone()
13654                )),
13655                ActionDecision::Resume(state.id.clone())
13656            );
13657            let error = crate::resume::validate(home.path(), &state.id)
13658                .unwrap_err()
13659                .to_string();
13660            assert!(!error.contains("review budget exhausted"), "{error}");
13661            assert!(
13662                error.contains(if review_rounds == 0 {
13663                    "review is disabled"
13664                } else {
13665                    "gate already ran"
13666                }),
13667                "{error}"
13668            );
13669
13670            // An unexecuted gate still has work to do with or without reviews.
13671            state.gate_ran = false;
13672            state.gate.clear();
13673            assert!(!exhausted_review_budget(&state));
13674            assert_eq!(
13675                unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone())),
13676                Some(state.id)
13677            );
13678        }
13679    }
13680
13681    #[test]
13682    fn sequencer_resource_resume_keeps_the_reserved_run_after_review_exhaustion() {
13683        let home = tempfile::tempdir().unwrap();
13684        let mut state = run_state(RunStatus::Blocked);
13685        state.config.graph.review_rounds = 1;
13686        let mut unresolved = review_round(1);
13687        unresolved.blocking = 1;
13688        unresolved.e2e.push(crate::run::CommandOutcome {
13689            command: "verify".into(),
13690            code: Some(1),
13691            output_tail: "previous verification failed".into(),
13692            duration_ms: 0,
13693            resource_blocked: false,
13694            artifact: None,
13695            failure_evidence: None,
13696            rerun_comparison: None,
13697        });
13698        state.reviews.push(unresolved);
13699        state.base_sync = Some(crate::run::BaseSync {
13700            tip: "base".into(),
13701            behind: 1,
13702            attempts: 0,
13703            conflict: None,
13704            already_in: None,
13705        });
13706        state.reserve_base_operation("winner", "base");
13707        state.resource_block = Some(crate::run::ResourceBlock {
13708            cause: crate::run::ResourceBlockCause::Other,
13709            node: "rebase".into(),
13710            kind: crate::rebase::SEQUENCER_INFRASTRUCTURE.into(),
13711            detail: "recording exec failed".into(),
13712            at: jiff::Timestamp::now(),
13713        });
13714        state.save_under(home.path()).unwrap();
13715        assert_eq!(
13716            crate::resume::validate(home.path(), &state.id).unwrap().id,
13717            state.id
13718        );
13719        assert_eq!(
13720            crate::repair_budget::legacy::classify(&state, "winner", "base").class,
13721            crate::repair_budget::legacy::Class::SequencerInfrastructure
13722        );
13723        state.finish_base_operation(None);
13724        state.save_under(home.path()).unwrap();
13725        assert!(crate::resume::validate(home.path(), &state.id).is_err());
13726    }
13727
13728    #[test]
13729    fn resource_blocked_verification_resumes_the_same_run() {
13730        for (kind, stage) in [
13731            ("cache", "clean"),
13732            ("coordination", "clean"),
13733            ("cache", "review-e2e"),
13734            ("coordination", "no-reviews"),
13735            ("coordination", "handoff"),
13736        ] {
13737            let home = tempfile::tempdir().unwrap();
13738            let mut state = run_state(RunStatus::Blocked);
13739            state.config.graph.review_rounds = 1;
13740            let mut review = review_round(1);
13741            review.clean = true;
13742            state.reviews = vec![review];
13743            if stage == "review-e2e" {
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: None,
13750                    output_tail: "resource wait expired".into(),
13751                    duration_ms: 0,
13752                    resource_blocked: true,
13753                    ..Default::default()
13754                }];
13755            } else if stage == "no-reviews" {
13756                state.config.graph.review_rounds = 0;
13757                state.reviews.clear();
13758            } else if stage == "handoff" {
13759                // A completed final verification can hand off to the gate
13760                // even when the review still carries contested findings.
13761                let review = &mut state.reviews[0];
13762                review.clean = false;
13763                review.blocking = 1;
13764                review.e2e = vec![crate::run::CommandOutcome {
13765                    command: "verify".into(),
13766                    code: Some(0),
13767                    output_tail: String::new(),
13768                    duration_ms: 0,
13769                    resource_blocked: false,
13770                    ..Default::default()
13771                }];
13772            }
13773            state.gate_ran = false;
13774            state.resource_block = Some(crate::run::ResourceBlock {
13775                cause: crate::run::ResourceBlockCause::Other,
13776                node: if stage == "review-e2e" {
13777                    "review"
13778                } else {
13779                    "gate"
13780                }
13781                .into(),
13782                kind: kind.into(),
13783                detail: "resource wait expired".into(),
13784                at: jiff::Timestamp::now(),
13785            });
13786            state.save_under(home.path()).unwrap();
13787            assert!(!crate::handover::has_resume_checkpoint(&state, home.path()));
13788            assert!(!exhausted_review_budget(&state));
13789            let mut task = held_task_with(&state.id);
13790            task.release();
13791            let unfinished = unfinished_run_with(&task.runs, task.short(), |_| Ok(state.clone()));
13792            assert_eq!(
13793                choose_starter(None, false, unfinished.as_deref()),
13794                Starter::Resume(state.id.clone())
13795            );
13796            let question = action_question(&state.id, resume_action(&state.id));
13797            assert_eq!(
13798                decide_action(home.path(), &task, &question, &PHRASES_EN, |_| Ok(
13799                    state.clone()
13800                )),
13801                ActionDecision::Resume(state.id.clone())
13802            );
13803            assert_eq!(
13804                crate::resume::validate(home.path(), &state.id).unwrap().id,
13805                state.id
13806            );
13807            let queue = Queue::at(home.path().join("queue"));
13808            let mut controlled = Task::new(
13809                "resume verification".into(),
13810                state.instruction.clone(),
13811                state.repo.clone(),
13812                Source::Agent {
13813                    run: "talk".into(),
13814                    node: crate::queue::CHAT_NODE.into(),
13815                },
13816            );
13817            controlled.runs.push(state.id.clone());
13818            controlled.hold_machine(Some("verification resource unavailable".into()));
13819            queue.put(&mut controlled).unwrap();
13820            let resumed = crate::chat_control::resume(&queue, home.path(), &state.id).unwrap();
13821            assert_eq!(resumed.status, TaskStatus::Queued);
13822            assert_eq!(
13823                resumed.resume_override.unwrap().pinned_run,
13824                Some(state.id.clone())
13825            );
13826            assert_eq!(resumed.attempts, 0);
13827
13828            // A genuinely unresolved final review still exhausts the budget.
13829            state.config.graph.review_rounds = 1;
13830            let mut unresolved = review_round(1);
13831            unresolved.blocking = 1;
13832            state.reviews = vec![unresolved];
13833            state.resource_block = None;
13834            state.save_under(home.path()).unwrap();
13835            assert!(exhausted_review_budget(&state));
13836            assert!(crate::resume::validate(home.path(), &state.id).is_err());
13837        }
13838    }
13839
13840    #[tokio::test]
13841    async fn ownership_contention_waits_and_reads_the_settled_record_before_resuming() {
13842        if !crate::standalone_test(
13843            "daemon::tests::ownership_contention_waits_and_reads_the_settled_record_before_resuming",
13844        ) {
13845            return;
13846        }
13847        let home = tempfile::tempdir().unwrap();
13848        let mut owner = stopped_public_run(RunStatus::Blocked);
13849        owner.save_under(home.path()).unwrap();
13850        let history = vec![owner.id.clone()];
13851        let repo = owner.repo.clone();
13852        let lock = crate::pr_head::owner_lock(home.path(), &owner.id).unwrap();
13853        let mut lookup = Box::pin(public_resume_owner(home.path(), &history, &repo));
13854        let initial =
13855            std::future::poll_fn(|cx| std::task::Poll::Ready(lookup.as_mut().poll(cx))).await;
13856        assert!(
13857            initial.is_pending(),
13858            "a busy record must not hold or resume the task"
13859        );
13860        owner.retired_to = Some("20260101-000001-bbbb".into());
13861        owner.save_under(home.path()).unwrap();
13862        drop(lock);
13863        let result = tokio::time::timeout(Duration::from_secs(10), lookup)
13864            .await
13865            .expect("ownership lock released")
13866            .expect("read settled owner");
13867        assert!(
13868            result.is_none(),
13869            "the retired owner must not be resumed from a stale read"
13870        );
13871    }
13872
13873    #[tokio::test]
13874    async fn retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds() {
13875        if !crate::standalone_test(
13876            "daemon::tests::retained_public_owner_wins_over_an_existing_successor_and_unknown_history_holds",
13877        ) {
13878            return;
13879        }
13880        let home = tempfile::tempdir().unwrap();
13881        let mut owner = stopped_public_run(RunStatus::Blocked);
13882        let repo = tempfile::tempdir().unwrap();
13883        crate::git::git(repo.path(), &["init"]).await.unwrap();
13884        owner.repo = crate::git::toplevel(repo.path()).await.unwrap();
13885        owner.id = "20260101-000000-aaaa".into();
13886        owner.save_under(home.path()).unwrap();
13887        let mut successor = run_state(RunStatus::Blocked);
13888        successor.id = "20260101-000001-bbbb".into();
13889        successor.save_under(home.path()).unwrap();
13890        let runs = vec![owner.id.clone(), successor.id.clone()];
13891        assert_eq!(
13892            public_resume_owner(home.path(), &runs, &owner.repo)
13893                .await
13894                .unwrap()
13895                .unwrap()
13896                .id,
13897            owner.id
13898        );
13899        let subdir = owner.repo.join("nested");
13900        std::fs::create_dir(&subdir).unwrap();
13901        assert_eq!(
13902            public_resume_owner(home.path(), &runs, &subdir)
13903                .await
13904                .unwrap()
13905                .unwrap()
13906                .id,
13907            owner.id
13908        );
13909        #[cfg(unix)]
13910        {
13911            let alias = home.path().join("repo-alias");
13912            std::os::unix::fs::symlink(&owner.repo, &alias).unwrap();
13913            assert_eq!(
13914                public_resume_owner(home.path(), &runs, &alias.join("nested"))
13915                    .await
13916                    .unwrap()
13917                    .unwrap()
13918                    .id,
13919                owner.id
13920            );
13921        }
13922        let different = tempfile::tempdir().unwrap();
13923        crate::git::git(different.path(), &["init"]).await.unwrap();
13924        assert!(
13925            public_resume_owner(home.path(), &runs, different.path())
13926                .await
13927                .is_err()
13928        );
13929        std::fs::remove_file(
13930            home.path()
13931                .join("runs")
13932                .join(&successor.id)
13933                .join("run.json"),
13934        )
13935        .unwrap();
13936        assert!(
13937            public_resume_owner(home.path(), &runs, &owner.repo)
13938                .await
13939                .is_err()
13940        );
13941    }
13942
13943    #[test]
13944    fn an_ordinary_release_keeps_a_resumable_run_available() {
13945        let mut released = task();
13946        released.start("stalled-run".to_owned());
13947        released.release();
13948        let unfinished = (!released.fresh_start)
13949            .then(|| Some("stalled-run".to_owned()))
13950            .flatten();
13951        assert_eq!(
13952            choose_starter(None, false, unfinished.as_deref()),
13953            Starter::Resume("stalled-run".to_owned()),
13954            "manual release must preserve the normal resume path"
13955        );
13956    }
13957
13958    #[test]
13959    fn resume_refusals_explain_admission_without_changing_task_or_run() {
13960        use crate::handover::{ResumeRefusal, resume_refusal_under};
13961        let home = tempfile::tempdir().unwrap();
13962        let mut exhausted = run_state(RunStatus::Blocked);
13963        exhausted.driver_exited = true;
13964        exhausted.config.graph.review_rounds = 3;
13965        exhausted.reviews = (1..=3).map(review_round).collect();
13966        for refusal in [
13967            ResumeRefusal::ReviewBudget { used: 3, limit: 3 },
13968            ResumeRefusal::Status(RunStatus::Ready),
13969            ResumeRefusal::Released("20261022-000000-aaaa".into()),
13970            ResumeRefusal::Retired("retirement-successor".into()),
13971            ResumeRefusal::OwnershipTransferred("20261022-000000-bbbb".into()),
13972        ] {
13973            let mut state = exhausted.clone();
13974            let expected = match refusal {
13975                ResumeRefusal::Status(_) => {
13976                    state.status = RunStatus::Ready;
13977                    "status `ready`"
13978                }
13979                ResumeRefusal::Released(ref target) => {
13980                    state.released_to = Some(target.clone());
13981                    "execution was released"
13982                }
13983                ResumeRefusal::Retired(ref target) => {
13984                    state.retired_to = Some(target.clone());
13985                    "execution was retired"
13986                }
13987                ResumeRefusal::OwnershipTransferred(ref target) => {
13988                    state.pr_taken_over_by = Some(target.clone());
13989                    "PR ownership was transferred"
13990                }
13991                _ => "review budget exhausted (3/3 rounds used)",
13992            };
13993            assert_eq!(
13994                resume_refusal_under(&state, Some(home.path())),
13995                Some(refusal.clone())
13996            );
13997            assert_eq!(
13998                refusal.successor(),
13999                state
14000                    .released_to
14001                    .as_deref()
14002                    .or(state.retired_to.as_deref())
14003                    .or(state.pr_taken_over_by.as_deref())
14004            );
14005            state.save_under(home.path()).unwrap();
14006            let queue = Queue::at(home.path().join("queue"));
14007            let mut task = Task::new(
14008                "retained implementation".into(),
14009                state.instruction.clone(),
14010                state.repo.clone(),
14011                Source::Agent {
14012                    run: "talk".into(),
14013                    node: crate::queue::CHAT_NODE.into(),
14014                },
14015            );
14016            task.runs.push(state.id.clone());
14017            task.hold_machine(Some("stopped".into()));
14018            queue.put(&mut task).unwrap();
14019            let before_task = serde_json::to_value(queue.get(&task.id).unwrap()).unwrap();
14020            let before_run = serde_json::to_value(&state).unwrap();
14021            let error = crate::chat_control::resume(&queue, home.path(), &state.id)
14022                .unwrap_err()
14023                .to_string();
14024            assert!(error.contains(expected), "{error}");
14025            assert!(!error.contains("only a stalled or blocked"), "{error}");
14026            if matches!(refusal, ResumeRefusal::Status(_)) {
14027                assert!(
14028                    error.contains("is final; there is nothing left to resume"),
14029                    "{error}"
14030                );
14031            }
14032            if matches!(refusal, ResumeRefusal::ReviewBudget { .. }) {
14033                assert!(error.contains("magi review <saved-branch> --task <task-id> --merge none"));
14034                assert!(error.contains("review-only successor with a new review budget"));
14035                assert!(error.contains("does not resume this run"));
14036            }
14037            for target in [
14038                &state.released_to,
14039                &state.retired_to,
14040                &state.pr_taken_over_by,
14041            ]
14042            .into_iter()
14043            .flatten()
14044            {
14045                let short = if state.retired_to.as_ref() == Some(target) {
14046                    target.as_str()
14047                } else {
14048                    crate::run::short_of(target)
14049                };
14050                assert!(
14051                    error.contains(&format!("run {short}; inspect `magi show {short}`")),
14052                    "{error}"
14053                );
14054                if short != target {
14055                    assert!(!error.contains(target), "full successor id leaked: {error}");
14056                }
14057            }
14058            assert_eq!(
14059                serde_json::to_value(queue.get(&task.id).unwrap()).unwrap(),
14060                before_task
14061            );
14062            assert_eq!(
14063                serde_json::to_value(RunState::load_under(&state.id, home.path()).unwrap())
14064                    .unwrap(),
14065                before_run
14066            );
14067            let question = action_question(&state.id, resume_action(&state.id));
14068            for phrases in [&PHRASES_EN, &PHRASES_JA] {
14069                let decision = decide_action(home.path(), &task, &question, phrases, |id| {
14070                    RunState::load_under(id, home.path())
14071                });
14072                let ActionDecision::Refuse(detail) = decision else {
14073                    panic!(
14074                        "refusal expected: decision={decision:?}, refusal={refusal:?}, run={}, home={}",
14075                        state.id,
14076                        home.path().display()
14077                    );
14078                };
14079                assert!(detail.contains(expected), "{detail}");
14080            }
14081        }
14082        // Preserve predicate ordering, while keeping every recorded destination visible.
14083        exhausted.status = RunStatus::Ready;
14084        exhausted.released_to = Some("released".into());
14085        exhausted.retired_to = Some("retired".into());
14086        exhausted.pr_taken_over_by = Some("owner".into());
14087        let reason = resume_refusal_under(&exhausted, Some(home.path())).unwrap();
14088        assert_eq!(reason, ResumeRefusal::Status(RunStatus::Ready));
14089        let detail = reason.diagnostic(&exhausted);
14090        for target in ["released", "retired", "owner"] {
14091            assert!(detail.contains(&format!("magi show {target}")));
14092        }
14093    }
14094
14095    #[test]
14096    fn resume_action_ignores_question_checkpoints_in_another_home() {
14097        crate::run::pin_test_home();
14098        let home = tempfile::tempdir().unwrap();
14099        let mut state = run_state(RunStatus::Blocked);
14100        // The private directory reserves this fixture's identity even while
14101        // other tests write questions into the process-wide store.
14102        state.id = format!(
14103            "resume-context-{}",
14104            home.path().file_name().unwrap().to_str().unwrap()
14105        );
14106        state.driver_exited = true;
14107        state.config.graph.review_rounds = 1;
14108        state.reviews = vec![review_round(1)];
14109        state.save_under(home.path()).unwrap();
14110        let task = held_task_with(&state.id);
14111        let answer = action_question(&state.id, resume_action(&state.id));
14112        let mut checkpoint = approval_question(&state.id);
14113        let foreign = Questions::open();
14114        foreign.put(&mut checkpoint).unwrap();
14115        let refusal = crate::handover::resume_refusal_under(&state, Some(home.path()));
14116        let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
14117            RunState::load_under(id, home.path())
14118        });
14119        let matching: Vec<_> = foreign
14120            .list()
14121            .into_iter()
14122            .filter(|q| q.run == state.id && q.status.open())
14123            .collect();
14124        std::fs::remove_file(foreign.path_of(&checkpoint.id)).unwrap();
14125        assert!(
14126            matches!(decision, ActionDecision::Refuse(_)),
14127            "decision={decision:?}, refusal={refusal:?}, run={}, home={}, foreign_home={}, matching={matching:?}",
14128            state.id,
14129            home.path().display(),
14130            crate::run::test_home().display()
14131        );
14132        assert_eq!(
14133            refusal,
14134            Some(crate::handover::ResumeRefusal::ReviewBudget { used: 1, limit: 1 })
14135        );
14136        let local = Questions::at(home.path().join("questions"));
14137        for status in [
14138            ask::QuestionStatus::Open,
14139            ask::QuestionStatus::Answered,
14140            ask::QuestionStatus::Abandoned,
14141        ] {
14142            let mut question = checkpoint.clone();
14143            match status {
14144                ask::QuestionStatus::Open => {}
14145                ask::QuestionStatus::Answered => {
14146                    question
14147                        .answer(ask::Answer::Choice(question.choices[0].clone()))
14148                        .unwrap();
14149                }
14150                ask::QuestionStatus::Abandoned => question.abandon("fixture closed"),
14151            }
14152            local.put(&mut question).unwrap();
14153            let decision = decide_action(home.path(), &task, &answer, &PHRASES_EN, |id| {
14154                RunState::load_under(id, home.path())
14155            });
14156            if status.open() {
14157                assert_eq!(decision, ActionDecision::Resume(state.id.clone()));
14158            } else {
14159                assert!(
14160                    matches!(decision, ActionDecision::Refuse(ref detail) if detail.contains("review budget exhausted")),
14161                    "status={status:?}, decision={decision:?}"
14162                );
14163            }
14164        }
14165    }
14166
14167    #[test]
14168    fn resume_action_checks_the_driver_lease_in_the_supplied_home() {
14169        let home = tempfile::tempdir().unwrap();
14170        let mut state = run_state(RunStatus::Stalled);
14171        state.id = format!(
14172            "resume-driver-{}",
14173            home.path().file_name().unwrap().to_str().unwrap()
14174        );
14175        state.driver_claimed = Some(false);
14176        state.save_under(home.path()).unwrap();
14177        let task = held_task_with(&state.id);
14178        let question = action_question(&state.id, resume_action(&state.id));
14179        let decide = || {
14180            decide_action(home.path(), &task, &question, &PHRASES_EN, |id| {
14181                RunState::load_under(id, home.path())
14182            })
14183        };
14184        let lease = crate::driver::maintenance(home.path(), &state.id).unwrap();
14185        assert_eq!(state.liveness_under(home.path(), false), Liveness::Live);
14186        let expected_lock = home.path().join("runs").join(&state.id).join("driver.lock");
14187        match decide() {
14188            ActionDecision::Refuse(detail) => {
14189                assert!(
14190                    detail.starts_with("run already has a live driver: "),
14191                    "{detail}"
14192                );
14193                assert!(
14194                    detail.contains(&expected_lock.display().to_string()),
14195                    "{detail}"
14196                );
14197            }
14198            other => panic!("expected live driver refusal, got {other:?}"),
14199        }
14200        drop(lease);
14201        assert_eq!(decide(), ActionDecision::Resume(state.id.clone()));
14202    }
14203
14204    #[test]
14205    fn resume_checkpoint_admission_uses_the_supplied_question_store() {
14206        let home = tempfile::tempdir().unwrap();
14207        let mut state = run_state(RunStatus::Blocked);
14208        state.driver_exited = true;
14209        state.config.graph.review_rounds = 1;
14210        state.reviews = vec![review_round(1)];
14211        assert!(crate::handover::resume_refusal_under(&state, Some(home.path())).is_some());
14212        for checkpoint in ["publication", "approval", "armed", "landing", "question"] {
14213            let mut saved = state.clone();
14214            match checkpoint {
14215                "publication" => saved.pr_publication_pending = true,
14216                "approval" => {
14217                    saved.land_approval = Some(crate::run::LandApproval {
14218                        question: "approval".into(),
14219                        head: "head".into(),
14220                    })
14221                }
14222                "armed" => saved.land_armed_head = Some("head".into()),
14223                "landing" => saved.status = RunStatus::Landing,
14224                _ => {
14225                    let mut question = ask::Question::new(
14226                        saved.id.clone(),
14227                        "review".into(),
14228                        "review-1".into(),
14229                        "continue?".into(),
14230                        String::new(),
14231                        vec!["continue".into()],
14232                    );
14233                    ask::Questions::at(home.path().join("questions"))
14234                        .put(&mut question)
14235                        .unwrap();
14236                }
14237            }
14238            saved.save_under(home.path()).unwrap();
14239            assert!(
14240                crate::handover::resume_refusal_under(&saved, Some(home.path())).is_none(),
14241                "{checkpoint}"
14242            );
14243            assert!(
14244                crate::resume::validate(home.path(), &saved.id).is_ok(),
14245                "{checkpoint}"
14246            );
14247        }
14248    }
14249
14250    #[test]
14251    fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
14252        let mut state = run_state(RunStatus::Blocked);
14253        state.config.graph.review_rounds = 3;
14254        state.reviews = vec![review_round(1), review_round(2), review_round(3)];
14255        assert!(exhausted_review_budget(&state));
14256
14257        // One round still unused: resuming can still ask a reviewer something.
14258        state.reviews.pop();
14259        assert!(!exhausted_review_budget(&state));
14260
14261        // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
14262        // count: only a `Blocked` run re-enters the review loop on resume.
14263        let mut stalled = run_state(RunStatus::Stalled);
14264        stalled.config.graph.review_rounds = 1;
14265        stalled.reviews = vec![review_round(1)];
14266        assert!(!exhausted_review_budget(&stalled));
14267    }
14268
14269    fn review_round(round: usize) -> crate::run::ReviewRound {
14270        crate::run::ReviewRound {
14271            round,
14272            head: "deadbeef".to_owned(),
14273            verified_head: None,
14274            verified_at: None,
14275            reviews: Vec::new(),
14276            e2e: Vec::new(),
14277            verify_retried: false,
14278            e2e_deferred: false,
14279            e2e_defer_reason: None,
14280            fix: None,
14281            blocking: 0,
14282            answered: 1,
14283            expected: 1,
14284            clean: false,
14285            progressed: true,
14286            vote_split: false,
14287            reconsideration: Vec::new(),
14288            verdict: None,
14289        }
14290    }
14291
14292    #[test]
14293    fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
14294        let mut run = RunState::new(
14295            PathBuf::from("/repo"),
14296            "main".to_owned(),
14297            "abc1234def".to_owned(),
14298            "add retries".to_owned(),
14299            Config::default(),
14300        );
14301        run.status = RunStatus::Judging;
14302        run.parked = true;
14303        let mut task = Task::new(
14304            "add retries".to_owned(),
14305            "add retries".to_owned(),
14306            PathBuf::from("/repo"),
14307            crate::queue::Source::Human,
14308        );
14309        task.status = TaskStatus::Failed;
14310        task.runs = vec![run.id.clone()];
14311        let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
14312        assert!(with(&task, &run), "parked after judging is the case");
14313        let mut parked_task = task.clone();
14314        parked_task.status = TaskStatus::Parked;
14315        assert!(with(&parked_task, &run), "the Parked status is the case");
14316
14317        let mut not_parked = run.clone();
14318        not_parked.parked = false;
14319        not_parked.status = RunStatus::Stalled;
14320        assert!(!with(&task, &not_parked), "a stall is the conductor's");
14321
14322        let mut fresh = task.clone();
14323        fresh.fresh_start = true;
14324        assert!(!with(&fresh, &run), "a requeue asked for a new competition");
14325
14326        let mut review = task.clone();
14327        review.review_branch = Some("magi/x/A".to_owned());
14328        assert!(!with(&review, &run), "review is ranked before resume");
14329
14330        let mut held = task.clone();
14331        held.status = TaskStatus::Held;
14332        assert!(!with(&held, &run), "a hold stays visible to the conductor");
14333
14334        let mut released = run.clone();
14335        released.released_to = Some("20260901-000000-new1".to_owned());
14336        assert!(!with(&task, &released), "nothing left to resume into");
14337
14338        assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
14339            "unreadable"
14340        )));
14341    }
14342
14343    #[test]
14344    fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
14345        let mut released = RunState::new(
14346            PathBuf::from("/repo"),
14347            "main".to_owned(),
14348            "abc1234def".to_owned(),
14349            "add retries".to_owned(),
14350            Config::default(),
14351        );
14352        released.status = RunStatus::Blocked;
14353        assert_eq!(
14354            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14355            Some(released.id.clone())
14356        );
14357        released.released_to = Some("20260901-000000-new1".to_owned());
14358        assert_eq!(
14359            unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
14360            None,
14361            "there is nothing left to resume it into"
14362        );
14363    }
14364
14365    #[test]
14366    fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
14367        // Mirrors the failure this exists to close: a task's last run ended
14368        // `Blocked` with the review budget spent, `crate::conduct` chose
14369        // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
14370        // evidence), and without this check `attempt` would go on treating
14371        // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
14372        // review loop iterates zero times over an already-spent budget, so
14373        // the resumed run settles right back to `Blocked` having asked nobody
14374        // anything, and `Requeue`'s promised fresh competition never happens.
14375        let mut exhausted = RunState::new(
14376            PathBuf::from("/repo"),
14377            "main".to_owned(),
14378            "abc1234def".to_owned(),
14379            "add retries".to_owned(),
14380            Config::default(),
14381        );
14382        exhausted.status = RunStatus::Blocked;
14383        exhausted.config.graph.review_rounds = 1;
14384        exhausted.reviews = vec![review_round(1)];
14385
14386        assert_eq!(
14387            unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
14388            None,
14389            "an exhausted `Blocked` run must not be offered as resumable"
14390        );
14391
14392        // A `Blocked` run with rounds still unused is genuinely worth
14393        // resuming, and must still be found.
14394        let mut has_budget_left = RunState::new(
14395            PathBuf::from("/repo"),
14396            "main".to_owned(),
14397            "abc1234def".to_owned(),
14398            "add retries".to_owned(),
14399            Config::default(),
14400        );
14401        has_budget_left.status = RunStatus::Blocked;
14402        has_budget_left.config.graph.review_rounds = 3;
14403        has_budget_left.reviews = vec![review_round(1)];
14404
14405        assert_eq!(
14406            unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
14407                Ok(has_budget_left.clone())
14408            }),
14409            Some(has_budget_left.id.clone())
14410        );
14411    }
14412
14413    #[test]
14414    fn unfinished_run_resumes_a_run_whose_task_head_publication_is_pending() {
14415        let mut run = RunState::new(
14416            PathBuf::from("/repo"),
14417            "main".to_owned(),
14418            "abc1234def".to_owned(),
14419            "add retries".to_owned(),
14420            Config::default(),
14421        );
14422        run.status = RunStatus::Blocked;
14423        run.config.graph.review_rounds = 1;
14424        run.reviews = vec![review_round(1)];
14425        run.pr_publication_pending = true;
14426        assert_eq!(
14427            unfinished_run_with(&[run.id.clone()], "t", |_| Ok(run.clone())),
14428            Some(run.id.clone()),
14429            "a spent review budget must not turn a failed publication into a re-competition"
14430        );
14431    }
14432
14433    #[test]
14434    fn retained_attempt_bound_survives_changed_bases_releases_and_duplicate_history() {
14435        let mut task = Task::new(
14436            "recover work".into(),
14437            "recover work".into(),
14438            PathBuf::from("/repo"),
14439            crate::queue::Source::Human,
14440        );
14441        let mut history = std::collections::BTreeMap::new();
14442        for index in 0..8 {
14443            let mut run = run_state(RunStatus::Blocked);
14444            run.id = format!("20260101-000000-{index:04}");
14445            run.base_commit = format!("upstream-{index}");
14446            // Seven empty newer attempts must not erase the old recovery owner.
14447            if index > 0 {
14448                run.candidates.clear();
14449            }
14450            task.runs.extend([run.id.clone(), run.id.clone()]);
14451            history.insert(run.id.clone(), run);
14452            task.requeue();
14453        }
14454        let check = |task: &Task, starter: &Starter, limit| {
14455            retained_attempt_hold(task, starter, limit, |id| Ok(history[id].clone()))
14456        };
14457        assert!(
14458            check(&task, &Starter::Start, 8)
14459                .unwrap()
14460                .contains("8 unretired")
14461        );
14462        assert!(check(&task, &Starter::Start, 9).is_none());
14463        assert!(check(&task, &Starter::Review("existing".into()), 8).is_some());
14464        task.release_operator("owner", None);
14465        assert_eq!(task.attempts, 0);
14466        let restored: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14467        assert!(check(&restored, &Starter::Start, 8).is_some());
14468        assert!(check(&restored, &Starter::Resume(task.runs[0].clone()), 8).is_none());
14469        assert!(check(&restored, &Starter::Start, 0).is_none());
14470    }
14471
14472    #[test]
14473    fn retained_attempt_bound_includes_failed_startups_without_execution_history() {
14474        let tmp = tempfile::tempdir().unwrap();
14475        let mut task = Task::new(
14476            "recover selected PR".into(),
14477            "preserve implementation".into(),
14478            tmp.path().join("repo"),
14479            crate::queue::Source::Human,
14480        );
14481        let mut failed = run_state(RunStatus::Failed);
14482        failed.id = "20260101-000000-fail".into();
14483        failed.candidates.clear();
14484        failed.prep_complete = Some(false);
14485        failed.config.graph.worktree_root = Some(tmp.path().join("worktrees"));
14486        failed.startup = Some(crate::run::Startup {
14487            kind: "pr-recovery".into(),
14488            branch: Some("selected-public-head".into()),
14489            stage: "worktree-setup".into(),
14490            complete: false,
14491            failure: Some("setup modified a tracked file and failed".into()),
14492        });
14493        // Setup may fail before a candidate is recorded; its dirty worktree
14494        // still needs protection and consumes the independent retained bound.
14495        let worktree = failed.worktree_root().join("under-review");
14496        std::fs::create_dir_all(&worktree).unwrap();
14497        let retained_edit = worktree.join("implementation");
14498        std::fs::write(&retained_edit, "retained setup edit").unwrap();
14499        task.record_startup_failure(crate::run::StartupFailure {
14500            run: failed.id.clone(),
14501            stage: "worktree-setup".into(),
14502        });
14503        let task: Task = serde_json::from_slice(&serde_json::to_vec(&task).unwrap()).unwrap();
14504        assert!(task.runs.is_empty() && task.passes.is_empty());
14505        assert_eq!(task.attempts, 0);
14506        let starter = Starter::Review("selected-public-head".into());
14507        assert!(
14508            retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone()))
14509                .unwrap()
14510                .contains("1 unretired")
14511        );
14512        assert!(retained_attempt_hold(&task, &starter, 2, |_| Ok(failed.clone())).is_none());
14513        assert!(
14514            retained_attempt_hold(&task, &starter, 2, |_| anyhow::bail!("unreadable"))
14515                .unwrap()
14516                .contains("Cannot verify")
14517        );
14518        // Older or mixed writers can link the same reservation in both lists.
14519        let mut mixed = task.clone();
14520        mixed.runs.push(failed.id.clone());
14521        mixed
14522            .startup_failures
14523            .push(task.startup_failures[0].clone());
14524        assert!(retained_attempt_hold(&mixed, &starter, 2, |_| Ok(failed.clone())).is_none());
14525        failed.retired_to = Some("verified-recovery-owner".into());
14526        assert!(retained_attempt_hold(&task, &starter, 1, |_| Ok(failed.clone())).is_none());
14527        assert!(
14528            retained_attempt_hold(&task, &Starter::Resume(failed.id.clone()), 1, |_| {
14529                panic!("resuming the existing owner must not allocate a new attempt")
14530            })
14531            .is_none()
14532        );
14533        assert_eq!(
14534            std::fs::read_to_string(retained_edit).unwrap(),
14535            "retained setup edit"
14536        );
14537        assert!(task.runs.is_empty() && task.passes.is_empty());
14538        assert_eq!(task.attempts, 0);
14539    }
14540
14541    #[test]
14542    fn retained_attempt_bound_requires_verified_retirement_not_completion_labels() {
14543        let mut task = Task::new(
14544            "recover work".into(),
14545            "recover work".into(),
14546            PathBuf::from("/repo"),
14547            crate::queue::Source::Human,
14548        );
14549        let mut run = run_state(RunStatus::Superseded);
14550        run.candidates.clear();
14551        task.runs.push(run.id.clone());
14552        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_some());
14553        run.retired_to = Some("authority".into());
14554        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14555        run.retired_to = None;
14556        run.released_to = Some("authority".into());
14557        assert!(retained_attempt_hold(&task, &Starter::Start, 1, |_| Ok(run.clone())).is_none());
14558        assert!(
14559            retained_attempt_hold(&task, &Starter::Start, 8, |_| anyhow::bail!("unreadable"))
14560                .unwrap()
14561                .contains("Cannot verify")
14562        );
14563        // Resuming an existing owner needs no new inventory or worktree budget.
14564        assert!(
14565            retained_attempt_hold(&task, &Starter::Resume(run.id), 1, |_| {
14566                panic!("resume must not load historical attempts")
14567            })
14568            .is_none()
14569        );
14570    }
14571
14572    #[test]
14573    fn retired_resume_requires_a_valid_same_repository_authority() {
14574        let mut source = run_state(RunStatus::Blocked);
14575        let mut empty = run_state(RunStatus::Blocked);
14576        empty.retired_to = Some(source.id.clone());
14577        let runs = vec![source.id.clone(), empty.id.clone()];
14578        let resolve = |source: &RunState, empty: &RunState| {
14579            unfinished_run_with(&runs, "fixture", |id| {
14580                if id == source.id {
14581                    Ok(source.clone())
14582                } else if id == empty.id {
14583                    Ok(empty.clone())
14584                } else {
14585                    bail!("unreadable authority")
14586                }
14587            })
14588        };
14589        assert_eq!(resolve(&source, &empty), Some(source.id.clone()));
14590        assert_eq!(
14591            choose_starter(None, false, resolve(&source, &empty).as_deref()),
14592            Starter::Resume(source.id.clone())
14593        );
14594        source.retired_to = Some(empty.id.clone());
14595        assert!(
14596            resolve(&source, &empty).is_none(),
14597            "cycles do not revive obsolete runs"
14598        );
14599        source.retired_to = None;
14600        source.repo = PathBuf::from("/another-repository");
14601        assert!(resolve(&source, &empty).is_none());
14602        source.repo = empty.repo.clone();
14603        source.released_to = Some("later".into());
14604        assert!(resolve(&source, &empty).is_none());
14605        empty.retired_to = Some("unlisted-run".into());
14606        assert!(resolve(&source, &empty).is_none());
14607    }
14608
14609    #[test]
14610    fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
14611        // A task whose history holds an *older* run that still looks
14612        // resumable (say, a competition `Runner::review` was started
14613        // alongside after that older run went `Stalled`) and a *newest* run
14614        // that is `Blocked` with its review budget spent. `Recovery::Requeue`
14615        // on this task must mean a fresh competition — falling back to the
14616        // stale, superseded `Stalled` run instead would resurrect history
14617        // nothing asked to revisit and silently defeat the requeue.
14618        let mut older_stalled = RunState::new(
14619            PathBuf::from("/repo"),
14620            "main".to_owned(),
14621            "abc1234def".to_owned(),
14622            "add retries".to_owned(),
14623            Config::default(),
14624        );
14625        older_stalled.status = RunStatus::Stalled;
14626
14627        let mut newest_exhausted = RunState::new(
14628            PathBuf::from("/repo"),
14629            "main".to_owned(),
14630            "abc1234def".to_owned(),
14631            "add retries".to_owned(),
14632            Config::default(),
14633        );
14634        newest_exhausted.status = RunStatus::Blocked;
14635        newest_exhausted.config.graph.review_rounds = 1;
14636        newest_exhausted.reviews = vec![review_round(1)];
14637
14638        assert_eq!(
14639            unfinished_run_with(
14640                &[older_stalled.id.clone(), newest_exhausted.id.clone()],
14641                "t",
14642                |_| Ok(newest_exhausted.clone())
14643            ),
14644            None,
14645            "the newest run is exhausted, so nothing here is worth resuming - \
14646             least of all the older, already-superseded run"
14647        );
14648    }
14649
14650    #[test]
14651    fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
14652        assert_eq!(
14653            unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
14654                Err(anyhow::anyhow!("fixture is absent"))
14655            }),
14656            None
14657        );
14658    }
14659
14660    fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
14661        let mut q = ask::Question::new(
14662            run.to_owned(),
14663            "implement".to_owned(),
14664            "impl-A".to_owned(),
14665            "continue?".to_owned(),
14666            String::new(),
14667            vec!["resume で続行する".to_owned(), "other".to_owned()],
14668        );
14669        q.actions.insert("resume で続行する".to_owned(), action);
14670        q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
14671            .unwrap();
14672        q
14673    }
14674
14675    fn held_task_with(run: &str) -> Task {
14676        let mut t = task();
14677        t.runs = vec![run.to_owned()];
14678        t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
14679        t
14680    }
14681
14682    fn resume_action(run: &str) -> ask::ChoiceAction {
14683        ask::ChoiceAction::Resume { run: run.into() }
14684    }
14685
14686    #[test]
14687    fn explicitly_resumed_older_run_remains_the_release_and_question_target() {
14688        let home = crate::run::test_home();
14689        for parked in [false, true] {
14690            let mut t = task();
14691            t.start("A".into());
14692            t.start("B".into());
14693            assert_eq!(t.runs, vec!["A", "B"]);
14694            t.start("A".into());
14695            let mut resumed = run_state(RunStatus::Blocked);
14696            resumed.id = "A".into();
14697            resumed.parked = parked;
14698            resumed.driver_exited = true;
14699            t.hold_machine(Some("resumed run stopped".into()));
14700            let q = action_question("A", resume_action("A"));
14701            assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
14702            assert_eq!(
14703                decide_action(&home, &t, &q, &PHRASES_EN, |id| {
14704                    assert_eq!(id, "A");
14705                    Ok(resumed.clone())
14706                }),
14707                ActionDecision::Resume("A".into())
14708            );
14709            assert_eq!(
14710                action_standing(&t, &action_question("B", resume_action("B"))),
14711                ActionStanding::Stale
14712            );
14713            t.release_operator("cli", None);
14714            let unfinished = unfinished_run_with(&t.runs, t.short(), |id| {
14715                assert_eq!(id, "A");
14716                Ok(resumed.clone())
14717            });
14718            assert_eq!(
14719                choose_starter(None, false, unfinished.as_deref()),
14720                Starter::Resume("A".into())
14721            );
14722            assert_eq!(t.runs, vec!["B", "A"]);
14723        }
14724    }
14725
14726    #[test]
14727    fn merge_repair_dispatch_refuses_obsolete_bindings_and_unsupported_owners() {
14728        let home = crate::run::test_home();
14729        let mut state = crate::land::tests::repair_state(true, true);
14730        state.status = RunStatus::Landing;
14731        state.parked = true;
14732        state.driver_exited = true;
14733        let mut q = ask::Question::new(
14734            state.id.clone(),
14735            land::APPROVAL_NODE.into(),
14736            "land".into(),
14737            "Merge?".into(),
14738            String::new(),
14739            vec![land::APPROVE.into(), land::HOLD.into()],
14740        );
14741        q.id = state.id.clone();
14742        state.land_approval = Some(crate::run::LandApproval {
14743            question: q.id.clone(),
14744            head: "current-head".into(),
14745        });
14746        assert!(land::upgrade_repair_choice(&mut q, &state));
14747        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14748        let mut task = held_task_with(&state.id);
14749        task.status = TaskStatus::Parked;
14750        assert_eq!(
14751            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14752            ActionDecision::Resume(state.id.clone())
14753        );
14754        q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
14755        q.answered_at = Some("2026-01-01T00:00:20Z".parse().unwrap());
14756        task.operator_decided_at = Some("2026-01-01T00:00:10Z".parse().unwrap());
14757        assert_eq!(
14758            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(state.clone())),
14759            ActionDecision::Resume(state.id.clone()),
14760            "a repair answer newer than the manual hold resumes the existing owner"
14761        );
14762        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14763        for answered_at in [q.answered_at, None] {
14764            let mut older = q.clone();
14765            older.answered_at = answered_at;
14766            let refused = decide_action(&home, &task, &older, &PHRASES_EN, |_| {
14767                panic!("a later manual hold must prevent dispatch")
14768            });
14769            let ActionDecision::Refuse(reason) = refused else {
14770                panic!("expected an actionable refusal, got {refused:?}");
14771            };
14772            assert!(reason.contains("later operator decision"));
14773            assert!(reason.contains(&format!("magi task release {}", task.id)));
14774        }
14775        task.operator_decided_at = None;
14776        let mut superseded = state.clone();
14777        superseded.land_approval.as_mut().unwrap().question = "fresh-decision".into();
14778        assert_eq!(
14779            decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(superseded)),
14780            ActionDecision::Stale
14781        );
14782        for case in 1..4 {
14783            let mut changed = state.clone();
14784            match case {
14785                1 => changed.status = RunStatus::Blocked,
14786                2 => changed.released_to = Some("new-owner".into()),
14787                _ => changed.land_approval.as_mut().unwrap().head.clear(),
14788            }
14789            assert!(matches!(
14790                decide_action(&home, &task, &q, &PHRASES_EN, |_| Ok(changed)),
14791                ActionDecision::Refuse(_)
14792            ));
14793        }
14794        assert!(matches!(
14795            decide_action(&home, &task, &q, &PHRASES_EN, |_| anyhow::bail!(
14796                "missing owner"
14797            )),
14798            ActionDecision::Refuse(_)
14799        ));
14800        task.runs.push("replacement".into());
14801        task.operator_decided_at = Some("2026-01-01T00:00:30Z".parse().unwrap());
14802        assert_eq!(
14803            decide_action(&home, &task, &q, &PHRASES_EN, |_| panic!(
14804                "old owner must not load"
14805            )),
14806            ActionDecision::Stale
14807        );
14808    }
14809
14810    #[test]
14811    fn merge_repair_dispatch_obeys_capacity_and_quota_while_hold_stays_decision_only() {
14812        let mut state = crate::land::tests::repair_state(true, true);
14813        state.status = RunStatus::Landing;
14814        state.parked = true;
14815        state.driver_exited = true;
14816        let mut q = ask::Question::new(
14817            state.id.clone(),
14818            land::APPROVAL_NODE.into(),
14819            "land".into(),
14820            "Merge?".into(),
14821            String::new(),
14822            vec![land::APPROVE.into(), land::HOLD.into()],
14823        );
14824        q.id = state.id.clone();
14825        state.land_approval = Some(crate::run::LandApproval {
14826            question: q.id.clone(),
14827            head: "current-head".into(),
14828        });
14829        state.save().unwrap();
14830        land::upgrade_repair_choice(&mut q, &state);
14831        q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
14832        Questions::open().put(&mut q).unwrap();
14833        let tmp = tempfile::tempdir().unwrap();
14834        let queue = Queue::at(tmp.path().join("queue"));
14835        let mut task = held_task_with(&state.id);
14836        task.status = TaskStatus::Parked;
14837        queue.put(&mut task).unwrap();
14838        let empty = Arc::new(tokio::sync::Semaphore::new(0));
14839        let free = Arc::new(tokio::sync::Semaphore::new(1));
14840        assert!(matches!(
14841            claim_dispatch(&queue, &task, false, &empty, &free),
14842            Err(SkipReason::OrdinaryCapacity)
14843        ));
14844        assert!(matches!(
14845            claim_dispatch(&queue, &task, true, &free, &free),
14846            Err(SkipReason::CoolingDown)
14847        ));
14848        let claim = claim_dispatch(&queue, &task, false, &free, &free).unwrap();
14849        assert!(claim.permit.is_some());
14850        assert!(matches!(
14851            claim_dispatch(&queue, &task, false, &free, &free),
14852            Err(SkipReason::ClaimUnavailable)
14853        ));
14854        drop(claim);
14855        Questions::open()
14856            .update(&q.id, |q| {
14857                q.answer = Some(ask::Answer::Choice(land::HOLD.into()));
14858                Ok(())
14859            })
14860            .unwrap();
14861        let claim = claim_dispatch(&queue, &task, true, &empty, &empty).unwrap();
14862        assert!(claim.permit.is_none());
14863        assert!(RunState::load(&state.id).unwrap().merge_repairs.is_empty());
14864    }
14865
14866    #[test]
14867    fn decide_action_resumes_only_the_latest_resumable_run() {
14868        let home = crate::run::test_home();
14869        let t = held_task_with("r1");
14870        let q = action_question("r1", resume_action("r1"));
14871        let load = |s: RunState| move |_: &str| Ok(s);
14872        assert_eq!(
14873            decide_action(
14874                &home,
14875                &t,
14876                &q,
14877                &PHRASES_EN,
14878                load(run_state(RunStatus::Blocked))
14879            ),
14880            ActionDecision::Resume("r1".into())
14881        );
14882        // Not the latest run of the task.
14883        let q_other = action_question("r1", resume_action("r0"));
14884        assert!(matches!(
14885            decide_action(
14886                &home,
14887                &t,
14888                &q_other,
14889                &PHRASES_EN,
14890                load(run_state(RunStatus::Blocked))
14891            ),
14892            ActionDecision::Refuse(_)
14893        ));
14894        // A finished run cannot make progress.
14895        assert!(matches!(
14896            decide_action(
14897                &home,
14898                &t,
14899                &q,
14900                &PHRASES_EN,
14901                load(run_state(RunStatus::Ready))
14902            ),
14903            ActionDecision::Refuse(_)
14904        ));
14905        // A released one either.
14906        let mut released = run_state(RunStatus::Blocked);
14907        released.released_to = Some("elsewhere".into());
14908        assert!(matches!(
14909            decide_action(&home, &t, &q, &PHRASES_EN, load(released)),
14910            ActionDecision::Refuse(_)
14911        ));
14912        // Unreadable state is a refusal, never a fresh competition.
14913        assert!(matches!(
14914            decide_action(&home, &t, &q, &PHRASES_EN, |_: &str| bail!("gone")),
14915            ActionDecision::Refuse(_)
14916        ));
14917    }
14918
14919    #[test]
14920    fn decide_action_ignores_a_question_about_an_earlier_run() {
14921        let home = crate::run::test_home();
14922        let mut t = held_task_with("r1");
14923        t.runs.push("r2".to_owned());
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::Done),
14930                &PHRASES_EN,
14931                never
14932            ),
14933            ActionDecision::Stale
14934        );
14935    }
14936
14937    #[test]
14938    fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
14939        let home = crate::run::test_home();
14940        let mut t = held_task_with("r1");
14941        let never = |_: &str| -> Result<RunState> { bail!("not read") };
14942        assert_eq!(
14943            decide_action(
14944                &home,
14945                &t,
14946                &action_question("r1", ask::ChoiceAction::Requeue),
14947                &PHRASES_EN,
14948                never
14949            ),
14950            ActionDecision::Requeue
14951        );
14952        let done_q = action_question("r1", ask::ChoiceAction::Done);
14953        assert_eq!(
14954            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14955            ActionDecision::Done
14956        );
14957        t.mark_action_applied(&done_q.id);
14958        assert_eq!(
14959            decide_action(&home, &t, &done_q, &PHRASES_EN, never),
14960            ActionDecision::Skip
14961        );
14962
14963        // A plain answer (no action for that label) does nothing.
14964        let mut plain = action_question("r1", ask::ChoiceAction::Done);
14965        plain.actions.clear();
14966        assert_eq!(
14967            decide_action(&home, &held_task_with("r1"), &plain, &PHRASES_EN, never),
14968            ActionDecision::Skip
14969        );
14970        // A running task is left alone.
14971        let mut running = held_task_with("r1");
14972        running.status = TaskStatus::Running;
14973        assert_eq!(
14974            decide_action(
14975                &home,
14976                &running,
14977                &action_question("r1", ask::ChoiceAction::Done),
14978                &PHRASES_EN,
14979                never
14980            ),
14981            ActionDecision::Skip
14982        );
14983    }
14984
14985    #[test]
14986    fn merge_repair_rejected_after_manual_hold_keeps_the_conductor_guard() {
14987        crate::run::pin_test_home();
14988        for legacy in [false, true] {
14989            let dir = tempfile::tempdir().unwrap();
14990            let queue = Queue::at(dir.path().join("queue"));
14991            let questions = Questions::at(dir.path().join("questions"));
14992            let run = "20260101-000000-hold";
14993            let mut task = held_task_with(run);
14994            task.status = TaskStatus::Parked;
14995            let mut q = ask::Question::new(
14996                run.into(),
14997                land::APPROVAL_NODE.into(),
14998                "land".into(),
14999                "Repair?".into(),
15000                String::new(),
15001                vec![land::REPAIR.into()],
15002            );
15003            q.actions.insert(land::REPAIR.into(), resume_action(run));
15004            q.answer(ask::Answer::Choice(land::REPAIR.into())).unwrap();
15005            // Deterministically order the answer before the actual manual hold.
15006            q.asked_at = "2026-01-01T00:00:00Z".parse().unwrap();
15007            q.answered_at = Some("2026-01-01T00:00:01Z".parse().unwrap());
15008            questions.put(&mut q).unwrap();
15009            task.hold_manual(Some("Keep this PR paused".into()));
15010            if legacy {
15011                task.hold_source = None;
15012            }
15013            queue.put(&mut task).unwrap();
15014
15015            apply_task_choice_actions(&queue, &questions, dir.path());
15016            let after = queue.get(&task.id).unwrap();
15017            assert!(after.operator_held());
15018            assert_eq!(after.hold_source, task.hold_source);
15019            assert_eq!(after.operator_decided_at, task.operator_decided_at);
15020            assert_eq!(after.runs, task.runs);
15021            assert_eq!(after.instruction, task.instruction);
15022            assert!(after.resume_override.is_none());
15023            assert!(after.action_applied(&q.id));
15024            let reason = after.hold_reason.as_deref().unwrap();
15025            assert!(reason.starts_with("Keep this PR paused"));
15026            assert!(reason.contains("later operator decision"));
15027            assert!(reason.contains(&format!("magi task release {}", task.id)));
15028
15029            for recovery in [
15030                crate::conduct::Recovery::Review,
15031                crate::conduct::Recovery::Requeue,
15032            ] {
15033                crate::conduct::apply(
15034                    &queue,
15035                    &questions,
15036                    &crate::conduct::Verdict {
15037                        decisions: vec![crate::conduct::Decision {
15038                            id: task.id.clone(),
15039                            recovery: Some(recovery),
15040                            ..Default::default()
15041                        }],
15042                    },
15043                )
15044                .unwrap();
15045            }
15046            // Reconciliation is idempotent, and automatic recovery cannot
15047            // reopen this owner after it observes the rejected repair answer.
15048            apply_task_choice_actions(&queue, &questions, dir.path());
15049            let still_held = queue.get(&task.id).unwrap();
15050            assert!(still_held.operator_held());
15051            assert_eq!(still_held.hold_reason, after.hold_reason);
15052            assert_eq!(still_held.runs, task.runs);
15053            assert!(still_held.review_branch.is_none());
15054            assert!(!still_held.fresh_start);
15055            assert!(queue.next_runnable().is_none());
15056        }
15057    }
15058
15059    #[test]
15060    fn conductor_driver_choices_apply_from_both_queued_and_held_tasks() {
15061        for held in [false, true] {
15062            for retry in [false, true] {
15063                let dir = tempfile::tempdir().unwrap();
15064                let queue = Queue::at(dir.path().join("queue"));
15065                let questions = Questions::at(dir.path().join("questions"));
15066                let home = dir.path().join("home");
15067                let mut t = task();
15068                if held {
15069                    t.hold_machine(Some("driver state unknown".into()));
15070                }
15071                queue.put(&mut t).unwrap();
15072                let verdict = serde_json::from_value(serde_json::json!({
15073                    "decisions": [{
15074                        "id": t.id,
15075                        "question": "Driver state unknown; retry the checks or hold?",
15076                        "choices": ["daemon: recheck and retry", "daemon: hold the task"],
15077                        "actions": {
15078                            "daemon: recheck and retry": {"do": "requeue"},
15079                            "daemon: hold the task": {"do": "hold"}
15080                        }
15081                    }]
15082                }))
15083                .unwrap();
15084                crate::conduct::apply(&queue, &questions, &verdict).unwrap();
15085                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
15086                let mut q = questions.list().pop().unwrap();
15087                let choice = if retry {
15088                    "daemon: recheck and retry"
15089                } else {
15090                    "daemon: hold the task"
15091                };
15092                assert_eq!(q.actions.len(), 2);
15093                q.answer(ask::Answer::Choice(choice.into())).unwrap();
15094                questions.put(&mut q).unwrap();
15095
15096                // A Web answer does not remove the deputy's fresh lease.
15097                questions.beat(&q.id, ask::WaiterKind::Deputy);
15098                for _ in 0..2 {
15099                    resolve_blockers(&queue, &questions);
15100                    apply_task_choice_actions(&queue, &questions, &home);
15101                    let waiting = queue.get(&t.id).unwrap();
15102                    assert_eq!(waiting.status, TaskStatus::Blocked);
15103                    assert_eq!(waiting.blocked_by, [q.id.clone()]);
15104                    assert!(waiting.answers.is_empty());
15105                    assert!(!waiting.action_applied(&q.id));
15106                    assert!(runnable(&queue).is_empty());
15107                    let free = Arc::new(tokio::sync::Semaphore::new(1));
15108                    assert!(claim_dispatch(&queue, &t, false, &free, &free).is_err());
15109                }
15110                std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
15111
15112                // Releasing the blocker and applying the operation share one save.
15113                resolve_blockers(&queue, &questions);
15114                assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Blocked);
15115                apply_task_choice_actions(&queue, &questions, &home);
15116                let after = queue.get(&t.id).unwrap();
15117                assert_eq!(
15118                    after.status,
15119                    if retry {
15120                        TaskStatus::Queued
15121                    } else {
15122                        TaskStatus::Held
15123                    }
15124                );
15125                assert!(after.action_applied(&q.id));
15126                assert_eq!(after.operator_held(), !retry);
15127                assert_eq!(after.answers.len(), 1);
15128
15129                // A later operator decision must not replay this answer.
15130                let mut changed = after;
15131                if retry {
15132                    changed.hold_manual(Some("later hold".into()));
15133                } else {
15134                    changed.release_operator("test", None);
15135                }
15136                let expected = changed.status;
15137                queue.put(&mut changed).unwrap();
15138                apply_task_choice_actions(&queue, &questions, &home);
15139                assert_eq!(queue.get(&t.id).unwrap().status, expected);
15140            }
15141        }
15142    }
15143
15144    #[test]
15145    fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
15146        let dir = tempfile::tempdir().unwrap();
15147        let queue = Queue::at(dir.path().join("queue"));
15148        let questions = Questions::at(dir.path().join("questions"));
15149        let home = dir.path().join("home");
15150        let mut state = run_state(RunStatus::Blocked);
15151        state.id = "20260101-000000-act1".to_owned();
15152        state.save_under(&home).unwrap();
15153
15154        let mut t = held_task_with(&state.id);
15155        queue.put(&mut t).unwrap();
15156        let mut q = action_question(&state.id, resume_action(&state.id));
15157        questions.put(&mut q).unwrap();
15158
15159        apply_task_choice_actions(&queue, &questions, &home);
15160        let after = queue.get(&t.id).unwrap();
15161        assert_eq!(after.status, TaskStatus::Queued);
15162        assert!(!after.fresh_start);
15163        assert!(after.action_applied(&q.id));
15164        let pin = after.resume_override.clone().unwrap();
15165        assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
15166        assert!(pin.forced);
15167
15168        // Held again later: the same answer does not release it a second time.
15169        let mut again = queue.get(&t.id).unwrap();
15170        again.hold_machine(Some("later".into()));
15171        queue.put(&mut again).unwrap();
15172        apply_task_choice_actions(&queue, &questions, &home);
15173        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15174    }
15175
15176    #[test]
15177    fn done_choice_cannot_discard_unfinished_work_or_record_success_receipts() {
15178        let dir = tempfile::tempdir().unwrap();
15179        let home = dir.path();
15180        let queue = Queue::at(home.join("queue"));
15181        let questions = Questions::at(home.join("questions"));
15182        let mut state = run_state(RunStatus::Blocked);
15183        state.save_under(home).unwrap();
15184        let mut task = held_task_with(&state.id);
15185        queue.put(&mut task).unwrap();
15186        let mut question = action_question(&state.id, ask::ChoiceAction::Done);
15187        questions.put(&mut question).unwrap();
15188
15189        apply_task_choice_actions(&queue, &questions, home);
15190
15191        let after = queue.get(&task.id).unwrap();
15192        assert_eq!(after.status, TaskStatus::Held);
15193        assert!(after.hold_reason.as_deref().unwrap().contains("--discard"));
15194        assert_eq!(after.runs, task.runs);
15195        assert!(after.completion_history.is_empty());
15196        assert!(!after.decision_effects.contains_key(&question.id));
15197        assert_eq!(
15198            RunState::load_under(&state.id, home).unwrap().status,
15199            RunStatus::Blocked
15200        );
15201    }
15202
15203    #[test]
15204    fn a_delivered_answer_is_still_acted_on_exactly_once() {
15205        let dir = tempfile::tempdir().unwrap();
15206        let queue = Queue::at(dir.path().join("queue"));
15207        let questions = Questions::at(dir.path().join("questions"));
15208        let home = dir.path().join("home");
15209        let mut state = run_state(RunStatus::Blocked);
15210        state.id = "20260101-000000-act2".to_owned();
15211        state.save_under(&home).unwrap();
15212
15213        let mut t = held_task_with(&state.id);
15214        queue.put(&mut t).unwrap();
15215        let mut q = action_question(&state.id, resume_action(&state.id));
15216        q.answer_delivered = true;
15217        questions.put(&mut q).unwrap();
15218
15219        // Delivered, and the agent then died: the task is still held, so the
15220        // chosen action applies.
15221        apply_task_choice_actions(&queue, &questions, &home);
15222        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15223        assert!(queue.get(&t.id).unwrap().action_applied(&q.id));
15224
15225        // Held again: the same answer does nothing a second time.
15226        let mut again = queue.get(&t.id).unwrap();
15227        again.hold_machine(Some("later".into()));
15228        queue.put(&mut again).unwrap();
15229        apply_task_choice_actions(&queue, &questions, &home);
15230        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15231    }
15232
15233    #[test]
15234    fn a_fresh_asker_defers_the_action_until_it_goes_quiet() {
15235        let dir = tempfile::tempdir().unwrap();
15236        let queue = Queue::at(dir.path().join("queue"));
15237        let questions = Questions::at(dir.path().join("questions"));
15238        let home = dir.path().join("home");
15239        let mut state = run_state(RunStatus::Blocked);
15240        state.id = "20260101-000000-act3".to_owned();
15241        state.save_under(&home).unwrap();
15242        let mut t = held_task_with(&state.id);
15243        queue.put(&mut t).unwrap();
15244        let mut q = action_question(&state.id, ask::ChoiceAction::Requeue);
15245        questions.put(&mut q).unwrap();
15246
15247        questions.beat(&q.id, crate::ask::WaiterKind::Asker);
15248        apply_task_choice_actions(&queue, &questions, &home);
15249        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15250
15251        std::fs::remove_file(questions.root().join(format!("{}.lease", q.id))).unwrap();
15252        apply_task_choice_actions(&queue, &questions, &home);
15253        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
15254    }
15255
15256    #[test]
15257    fn action_standing_tells_the_reasons_apart() {
15258        let mut t = held_task_with("r1");
15259        let q = action_question("r1", ask::ChoiceAction::Requeue);
15260        assert_eq!(action_standing(&t, &q), ActionStanding::Pending);
15261        let mut plain = q.clone();
15262        plain.actions.clear();
15263        assert_eq!(action_standing(&t, &plain), ActionStanding::NoAction);
15264
15265        // Applied wins over everything, even a running task.
15266        t.mark_action_applied(&q.id);
15267        assert_eq!(action_standing(&t, &q), ActionStanding::Applied);
15268
15269        // A newer attempt running: the old question is Stale, not Busy.
15270        let mut t = held_task_with("r1");
15271        t.start("r2".to_owned());
15272        assert_eq!(action_standing(&t, &q), ActionStanding::Stale);
15273        // The same question about the latest run just waits.
15274        let q2 = action_question("r2", ask::ChoiceAction::Requeue);
15275        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15276        t.status = TaskStatus::Blocked;
15277        assert_eq!(action_standing(&t, &q2), ActionStanding::Busy);
15278
15279        // A conductor question is keyed by the task, never stale.
15280        let mut c = action_question("r0", ask::ChoiceAction::Requeue);
15281        c.node = crate::conduct::NODE.to_owned();
15282        assert_eq!(action_standing(&t, &c), ActionStanding::Busy);
15283        assert!(!ActionStanding::Busy.daemon_owns());
15284    }
15285
15286    #[test]
15287    fn a_running_task_waits_and_a_dead_asker_with_a_cwd_is_still_actioned() {
15288        let dir = tempfile::tempdir().unwrap();
15289        let queue = Queue::at(dir.path().join("queue"));
15290        let questions = Questions::at(dir.path().join("questions"));
15291        let home = dir.path().join("home");
15292        // Execution finished before task settlement; Done is not a discard.
15293        let mut state = run_state(RunStatus::Ready);
15294        state.id = "20260101-000000-act4".to_owned();
15295        state.save_under(&home).unwrap();
15296        let mut t = held_task_with(&state.id);
15297        t.status = TaskStatus::Running;
15298        queue.put(&mut t).unwrap();
15299        let mut q = action_question(&state.id, ask::ChoiceAction::Done);
15300        q.cwd = Some(dir.path().display().to_string());
15301        questions.put(&mut q).unwrap();
15302
15303        // While the task runs the daemon will not act, so the waiter still
15304        // delivers the word to the dead asker's seat ...
15305        let running = queue.get(&t.id).unwrap();
15306        assert_eq!(action_standing(&running, &q), ActionStanding::Busy);
15307        assert!(matches!(
15308            crate::waiter::decide_owned(&q, None, false, 86_400, Timestamp::now(), false),
15309            crate::waiter::Action::Deliver(_)
15310        ));
15311        // ... and the daemon waits while the task runs, then applies once.
15312        apply_task_choice_actions(&queue, &questions, &home);
15313        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
15314        let mut back = queue.get(&t.id).unwrap();
15315        back.hold_machine(Some("later".into()));
15316        queue.put(&mut back).unwrap();
15317        apply_task_choice_actions(&queue, &questions, &home);
15318        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Done);
15319        let mut again = queue.get(&t.id).unwrap();
15320        again.hold_machine(Some("again".into()));
15321        queue.put(&mut again).unwrap();
15322        apply_task_choice_actions(&queue, &questions, &home);
15323        assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
15324    }
15325
15326    #[test]
15327    fn stale_heartbeat_pointing_to_terminal_worker_does_not_block_resume_while_unproven_claims_stay_protected()
15328     {
15329        let dir = tempfile::tempdir().unwrap();
15330        let home = dir.path();
15331        let queue = Queue::at(home.join("queue"));
15332        let mut state = run_state(RunStatus::Blocked);
15333        state.id = "20261125-084544-669a".to_owned();
15334        state.driver_exited = true;
15335        state.driver_pid = None;
15336        state.driver_started_at = None;
15337        state.save_under(home).unwrap();
15338
15339        let mut t = held_task_with(&state.id);
15340        queue.put(&mut t).unwrap();
15341
15342        // Simulate a task worker that finished and was archived to results/,
15343        // while daemon.json still has a fresh heartbeat referencing that worker.
15344        let worker_id = "fc769e65-0000-4000-8000-000000000001";
15345        let retained_dir = home.join("workers").join("results").join(worker_id);
15346        std::fs::create_dir_all(&retained_dir).unwrap();
15347        let finished_job = crate::worker::Job {
15348            id: worker_id.to_owned(),
15349            sequence: 1,
15350            kind: "task".to_owned(),
15351            key: format!("task:{}", t.id),
15352            payload: serde_json::json!({
15353                "queue": home.join("queue"),
15354                "task": t.id,
15355                "opts": Opts::default(),
15356                "standalone": false,
15357            }),
15358            generation: "a".repeat(64),
15359            version: Some("0.260.0".to_owned()),
15360            status: crate::worker::Status::Finished,
15361            result: Some("completed".to_owned()),
15362            pid: Some(37456),
15363            created_at: 1,
15364            finished_at: Some(2),
15365        };
15366        std::fs::write(
15367            retained_dir.join("job.json"),
15368            serde_json::to_vec(&finished_job).unwrap(),
15369        )
15370        .unwrap();
15371
15372        let now = Timestamp::now();
15373        let mut status = Status::new();
15374        status.updated_at = now;
15375        status.current = vec![Current {
15376            worker: Some(worker_id.to_owned()),
15377            task: t.id.clone(),
15378            run: state.id.clone(),
15379        }];
15380        write_status_to(&home.join("daemon.json"), &status).unwrap();
15381
15382        assert!(
15383            claim_for_run(home, &state.id, now).is_none(),
15384            "a fresh heartbeat pointing to a confirmed terminal worker must not claim the run"
15385        );
15386        assert!(crate::resume::validate(home, &state.id).is_ok());
15387
15388        // Legacy heartbeat without worker id remains protected.
15389        status.current = vec![Current {
15390            worker: None,
15391            task: t.id.clone(),
15392            run: state.id.clone(),
15393        }];
15394        write_status_to(&home.join("daemon.json"), &status).unwrap();
15395        let legacy_err = crate::resume::validate(home, &state.id)
15396            .unwrap_err()
15397            .to_string();
15398        assert!(
15399            legacy_err.starts_with("run already has a live driver: daemon heartbeat claim"),
15400            "{legacy_err}"
15401        );
15402        assert!(legacy_err.contains("worker=none"), "{legacy_err}");
15403
15404        // Heartbeat naming a missing/unreadable worker record remains protected.
15405        let missing_id = "fc769e65-0000-4000-8000-000000000002";
15406        status.current = vec![Current {
15407            worker: Some(missing_id.to_owned()),
15408            task: t.id.clone(),
15409            run: state.id.clone(),
15410        }];
15411        write_status_to(&home.join("daemon.json"), &status).unwrap();
15412        let missing_err = crate::resume::validate(home, &state.id)
15413            .unwrap_err()
15414            .to_string();
15415        assert!(
15416            missing_err.starts_with("run already has a live driver: daemon heartbeat claim"),
15417            "{missing_err}"
15418        );
15419        assert!(missing_err.contains(missing_id), "{missing_err}");
15420        assert!(missing_err.contains("status=unknown"), "{missing_err}");
15421
15422        // Heartbeat naming a Running (non-terminal) worker whose lease is not held
15423        // still remains protected conservatively until fenced to a terminal status.
15424        let running_id = "fc769e65-0000-4000-8000-000000000003";
15425        let running_dir = home.join("workers").join("jobs").join(running_id);
15426        std::fs::create_dir_all(&running_dir).unwrap();
15427        let running_job = crate::worker::Job {
15428            id: running_id.to_owned(),
15429            status: crate::worker::Status::Running,
15430            pid: Some(42424),
15431            finished_at: None,
15432            result: None,
15433            ..finished_job
15434        };
15435        std::fs::write(
15436            running_dir.join("job.json"),
15437            serde_json::to_vec(&running_job).unwrap(),
15438        )
15439        .unwrap();
15440        std::fs::write(running_dir.join("live.lock"), b"").unwrap();
15441        status.current = vec![Current {
15442            worker: Some(running_id.to_owned()),
15443            task: t.id.clone(),
15444            run: state.id.clone(),
15445        }];
15446        write_status_to(&home.join("daemon.json"), &status).unwrap();
15447        let running_err = crate::resume::validate(home, &state.id)
15448            .unwrap_err()
15449            .to_string();
15450        assert!(
15451            running_err.starts_with("run already has a live driver: daemon heartbeat claim"),
15452            "{running_err}"
15453        );
15454        assert!(running_err.contains(running_id), "{running_err}");
15455        assert!(running_err.contains("pid=42424"), "{running_err}");
15456        assert!(running_err.contains("status=running"), "{running_err}");
15457    }
15458
15459    #[test]
15460    fn resume_validate_refusals_include_concrete_evidence_for_every_live_path() {
15461        let dir = tempfile::tempdir().unwrap();
15462        let home = dir.path();
15463        let queue = Queue::at(home.join("queue"));
15464        let mut state = run_state(RunStatus::Blocked);
15465        state.id = "20261125-090000-evid".to_owned();
15466        state.driver_exited = true;
15467        state.save_under(home).unwrap();
15468        let mut t = held_task_with(&state.id);
15469        queue.put(&mut t).unwrap();
15470
15471        // 1. Live task worker holding live.lock.
15472        let payload = serde_json::json!({
15473            "queue": home.join("queue"),
15474            "task": t.id,
15475            "opts": Opts::default(),
15476            "standalone": false,
15477        });
15478        let (job, lease) =
15479            crate::worker::running_fixture(home, &format!("task:{}", t.id), payload).unwrap();
15480        let worker_err = crate::resume::validate(home, &state.id)
15481            .unwrap_err()
15482            .to_string();
15483        assert!(
15484            worker_err.starts_with("run already has a live driver: worker claim"),
15485            "{worker_err}"
15486        );
15487        assert!(worker_err.contains(&job.id), "{worker_err}");
15488        assert!(
15489            worker_err.contains(&format!("pid={}", std::process::id())),
15490            "{worker_err}"
15491        );
15492        assert!(worker_err.contains("status=running"), "{worker_err}");
15493        assert!(worker_err.contains("live.lock held"), "{worker_err}");
15494        drop(lease);
15495        std::fs::remove_dir_all(home.join("workers").join("jobs").join(&job.id)).unwrap();
15496
15497        // 2. Unfenced Starting worker reservation.
15498        let starting_id = "fc769e65-0000-4000-8000-000000000010";
15499        let starting_dir = home.join("workers").join("jobs").join(starting_id);
15500        std::fs::create_dir_all(&starting_dir).unwrap();
15501        let starting_job = crate::worker::Job {
15502            id: starting_id.to_owned(),
15503            sequence: 2,
15504            kind: "task".to_owned(),
15505            key: format!("task:{}", t.id),
15506            payload: serde_json::json!({
15507                "queue": home.join("queue"),
15508                "task": t.id,
15509                "opts": Opts::default(),
15510                "standalone": false,
15511            }),
15512            generation: "a".repeat(64),
15513            version: None,
15514            status: crate::worker::Status::Starting,
15515            result: None,
15516            pid: None,
15517            created_at: 1,
15518            finished_at: None,
15519        };
15520        std::fs::write(
15521            starting_dir.join("job.json"),
15522            serde_json::to_vec(&starting_job).unwrap(),
15523        )
15524        .unwrap();
15525        let starting_err = crate::resume::validate(home, &state.id)
15526            .unwrap_err()
15527            .to_string();
15528        assert!(
15529            starting_err.starts_with("run already has a live driver: worker claim"),
15530            "{starting_err}"
15531        );
15532        assert!(starting_err.contains(starting_id), "{starting_err}");
15533        assert!(starting_err.contains("status=starting"), "{starting_err}");
15534        assert!(
15535            starting_err.contains("unfenced starting reservation"),
15536            "{starting_err}"
15537        );
15538        std::fs::remove_dir_all(&starting_dir).unwrap();
15539
15540        // 3. Unrelated corrupt worker triggers conservative protection with distinct wording.
15541        let corrupt_id = "bad00000-0000-4000-8000-000000000099";
15542        let corrupt_dir = home.join("workers").join("jobs").join(corrupt_id);
15543        std::fs::create_dir_all(&corrupt_dir).unwrap();
15544        std::fs::write(corrupt_dir.join("job.json"), b"{not valid json").unwrap();
15545        let store_err = crate::resume::validate(home, &state.id)
15546            .unwrap_err()
15547            .to_string();
15548        assert!(
15549            store_err.starts_with(
15550                "run already has a live driver: worker store observation failed (conservative protection):"
15551            ),
15552            "{store_err}"
15553        );
15554        assert!(store_err.contains(corrupt_id), "{store_err}");
15555        std::fs::remove_dir_all(&corrupt_dir).unwrap();
15556
15557        // 4. Held execution lease (driver.lock path).
15558        state.driver_exited = false;
15559        state.driver_claimed = Some(false);
15560        state.driver_pid = None;
15561        state.driver_started_at = None;
15562        state.save_under(home).unwrap();
15563        let exec_lease = crate::driver::maintenance(home, &state.id).unwrap();
15564        let lease_err = crate::resume::validate(home, &state.id)
15565            .unwrap_err()
15566            .to_string();
15567        let lock_path = home.join("runs").join(&state.id).join("driver.lock");
15568        assert!(
15569            lease_err.starts_with("run already has a live driver: execution lease held"),
15570            "{lease_err}"
15571        );
15572        assert!(
15573            lease_err.contains(&lock_path.display().to_string()),
15574            "{lease_err}"
15575        );
15576        drop(exec_lease);
15577
15578        // 5. Live process identity (pid + identity).
15579        let pid = std::process::id();
15580        let identity = crate::proc::process_started_at(pid).expect("current process identity");
15581        state.driver_claimed = None;
15582        state.driver_pid = Some(pid);
15583        state.driver_started_at = Some(identity.clone());
15584        state.save_under(home).unwrap();
15585        let pid_err = crate::resume::validate(home, &state.id)
15586            .unwrap_err()
15587            .to_string();
15588        assert!(
15589            pid_err.starts_with("run already has a live driver: live driver process"),
15590            "{pid_err}"
15591        );
15592        assert!(pid_err.contains(&format!("pid={pid}")), "{pid_err}");
15593        assert!(
15594            pid_err.contains(&format!("identity={identity}")),
15595            "{pid_err}"
15596        );
15597
15598        // decide_action uses the exact same refusal format for process identity too.
15599        let question = action_question(&state.id, resume_action(&state.id));
15600        let decision = decide_action(home, &t, &question, &PHRASES_EN, |id| {
15601            RunState::load_under(id, home)
15602        });
15603        assert_eq!(decision, ActionDecision::Refuse(pid_err));
15604    }
15605}