magi/daemon.rs
1//! The unattended loop: take the next task, run the graph, record what
2//! happened, take the next one.
3//!
4//! This is what turns magi from a command a human types into something an
5//! agent can hand work to. [`crate::queue`] is the mailbox; this module is the
6//! thing that empties it. Nothing here decides *how* a task is implemented —
7//! that is [`crate::graph`] — it only decides which task runs next, and what a
8//! finished run means for the task that produced it.
9//!
10//! # One run at a time, on purpose
11//!
12//! There is no `--jobs` flag and there will not be one. A single run is
13//! already internally parallel: candidates implement concurrently and judges
14//! rank concurrently, so the machine is not idle while one task is in flight.
15//! The real constraint is not CPU but the agent CLIs' quota, and two graphs at
16//! once doubles the burn rate on exactly the resource whose exhaustion produces
17//! [`RunStatus::Stalled`]. Serialising the loop is what keeps a full backlog
18//! from converting the whole day's quota into a pile of untrustworthy verdicts.
19//!
20//! # A crash is legible, and the loop notices on its own
21//!
22//! The task is written as [`crate::queue::TaskStatus::Running`], with its run
23//! id, *before* the graph starts, and is only rewritten once the run reaches a
24//! terminal status. A daemon killed mid-run therefore leaves the task
25//! `Running` and pointing at the run that was in flight. The alternative —
26//! reverting the task to `Queued` on the way out — would hide the abandoned
27//! run and re-spend its quota on the next poll.
28//!
29//! A task left `Running` forever is not the point, though:
30//! [`crate::queue::TaskStatus::runnable`] never offers it again, so a daemon
31//! that died mid-run would otherwise strand its task for good.
32//! [`reclaim_orphaned_running`] runs on every poll and settles exactly the
33//! tasks no live process is actually driving — proven by [`Queue::claim`]
34//! succeeding rather than by a staleness guess — against whatever their last
35//! run actually became, through the same [`settle`] a live finish uses. A run
36//! that genuinely cannot be read still holds its task for a human; the run's
37//! own report explains how far it got.
38//!
39//! # Retries are bounded
40//!
41//! Every attempt at a task consumes one of [`Opts::max_attempts`], after which
42//! the task is [`crate::queue::TaskStatus::Held`] for a human. The one
43//! exception is a run that ended `Stalled`: the panel collapsed because the
44//! agent CLIs hit their quota, which is a fact about the machine and not about
45//! the task, so it must not spend an attempt. Without that exception a quota
46//! outage would quietly hold the entire backlog, and the operator would come
47//! back to a reset quota and nothing left that the loop is willing to run.
48
49use std::path::{Path, PathBuf};
50use std::sync::Arc;
51use std::sync::atomic::{AtomicBool, Ordering};
52use std::sync::{Mutex, MutexGuard};
53use std::time::Duration;
54
55use anyhow::{Context, Result, bail};
56use jiff::Timestamp;
57use serde::{Deserialize, Serialize};
58use tokio::sync::Notify;
59
60use crate::ask::{self, Questions};
61use crate::clean;
62use crate::conduct::Conductor;
63use crate::config::{Config, MergeMode};
64use crate::graph::Runner;
65use crate::land;
66use crate::notices::{self, Link, Notice};
67use crate::queue::{Queue, Task, TaskStatus};
68use crate::run::{Liveness, QuotaLoss, RunState, RunStatus};
69use crate::triage;
70
71/// On-disk format for [`Status`]. Bumped when a field's meaning changes.
72pub const SCHEMA: u32 = 1;
73
74/// How often the status file is refreshed. A reader treats a status file older
75/// than [`STALE_SECS`] as "no daemon", so the heartbeat has to be brisk enough
76/// that a busy daemon is never mistaken for a dead one.
77pub const HEARTBEAT: Duration = Duration::from_secs(5);
78
79/// How old a heartbeat may be before a reader calls the daemon dead. Six
80/// missed beats: long enough to survive a slow filesystem, short enough that
81/// a crashed daemon is not still reported as running a task.
82///
83/// The single threshold every reader shares — the web UI's `/api/health` and
84/// `magi doctor` both call [`Reading::running`] rather than each comparing
85/// against their own copy of this number, so a crashed daemon cannot look
86/// alive on one screen and dead on another.
87pub const STALE_SECS: i64 = 30;
88
89/// Default queue poll interval.
90pub const POLL: Duration = Duration::from_secs(5);
91
92/// How old a claim has to be before startup sweeps it. Longer than any run
93/// this graph plausibly takes, so a sweep cannot pull a task out from under a
94/// daemon that is merely slow.
95pub const STALE_CLAIM: Duration = Duration::from_secs(6 * 60 * 60);
96
97/// How long a task may sit [`TaskStatus::Running`] with no live daemon's
98/// heartbeat naming it before [`crate::conduct`] is shown it as stalled.
99///
100/// [`reclaim_orphaned_running`] settles most crashes immediately, on every
101/// poll, by attempting the task's own claim: a dead pid is proof enough for
102/// [`sweep_stale_claims`] to drop the lock the same tick, and the very next
103/// claim attempt succeeds. But a lock whose pid cannot be parsed at all — an
104/// empty or corrupt `.lock` file — falls back to [`STALE_CLAIM`]'s six-hour
105/// age instead, since there is nothing else to check (see
106/// [`sweep_stale_claims`]'s own doc). For as long as that lock survives, the
107/// claim keeps failing and `reclaim_orphaned_running` correctly leaves the
108/// task `running` — see
109/// `stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet` for
110/// exactly this ordering. `stalled_tasks` is what surfaces that task to the
111/// conductor well before the mechanical six-hour sweep would, and thirty
112/// minutes is comfortably below `STALE_CLAIM` while still being generous
113/// enough that a task merely late to publish its first [`HEARTBEAT`] is
114/// never mistaken for abandoned.
115pub const STALLED_RUNNING: Duration = Duration::from_secs(30 * 60);
116
117/// What the loop is working on, for the status file.
118#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(default)]
120pub struct Current {
121 /// Task id being run.
122 pub task: String,
123 /// Run id the task produced.
124 pub run: String,
125}
126
127/// The daemon's liveness, published to `<home>/daemon.json`.
128///
129/// This is the only interface between the loop and the web UI, which is why it
130/// carries `updated_at` as well as `started_at`: a reader cannot tell a
131/// running daemon from a `SIGKILL`ed one by the file's existence alone, but it
132/// can compare the heartbeat against the clock.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134pub struct Status {
135 /// On-disk format version.
136 pub schema: u32,
137 /// Process id, so a human can find or kill the daemon.
138 pub pid: u32,
139 /// When this process started.
140 pub started_at: Timestamp,
141 /// Last heartbeat.
142 pub updated_at: Timestamp,
143 /// True when the queue has nothing runnable.
144 pub idle: bool,
145 /// Every task and run currently in flight. More than one entry means the
146 /// loop is driving more than one run at once — see
147 /// [`crate::config::Daemon::max_concurrent_runs`]. Empty, not absent, when
148 /// nothing is running, so a reader never has to treat "no field" and "an
149 /// empty list" as two different kinds of idle.
150 pub current: Vec<Current>,
151 /// Tasks that reached a terminal status in this process.
152 pub completed: usize,
153 /// Queue polls since start, so a wedged loop shows up as a frozen count.
154 pub polls: u64,
155}
156
157impl Status {
158 /// A fresh, idle status for this process.
159 #[must_use]
160 pub fn new() -> Self {
161 let now = Timestamp::now();
162 Self {
163 schema: SCHEMA,
164 pid: std::process::id(),
165 started_at: now,
166 updated_at: now,
167 idle: true,
168 current: Vec::new(),
169 completed: 0,
170 polls: 0,
171 }
172 }
173}
174
175impl Default for Status {
176 fn default() -> Self {
177 Self::new()
178 }
179}
180
181/// How the loop should behave.
182#[derive(Debug, Clone)]
183pub struct Opts {
184 /// Repository used by tasks that name none.
185 pub repo: PathBuf,
186 /// Explicit `magi.toml`, instead of the discovered layer stack.
187 pub config: Option<PathBuf>,
188 /// Queue poll interval.
189 pub poll: Duration,
190 /// Attempts a task gets before it is held for a human.
191 pub max_attempts: usize,
192 /// Drain what is runnable now, then return, instead of waiting for more.
193 pub once: bool,
194 /// Merge mode override (`none`, `local`, `pr`); `None` keeps the config's.
195 pub merge: Option<String>,
196 /// Where the janitor's [`crate::clean::fold_orphaned_worktrees`] and
197 /// [`crate::git::worktree_prune`] look for and reclaim worktrees.
198 /// `None` resolves to [`crate::run::default_worktree_root`] - the
199 /// operator's real `~/wt/<repo>` - the same way a run with no
200 /// [`crate::config::Graph::worktree_root`] resolves its own. A caller
201 /// that does not own that directory (a test, an embedding that manages
202 /// worktrees itself) must set this, or every idle tick reclaims worktrees
203 /// out from under whoever actually does.
204 pub worktrees_root: Option<PathBuf>,
205}
206
207impl Default for Opts {
208 fn default() -> Self {
209 Self {
210 repo: PathBuf::from("."),
211 config: None,
212 poll: POLL,
213 max_attempts: 2,
214 once: false,
215 merge: None,
216 worktrees_root: None,
217 }
218 }
219}
220
221/// How many runs a plain `usize` from config may drive concurrently, floored
222/// at one. A `0` in a config file would otherwise stall the loop entirely -
223/// no runnable task could ever start - which is never what an operator who
224/// wrote `0` meant.
225fn max_concurrent(n: usize) -> usize {
226 n.max(1)
227}
228
229/// Where the status file lives.
230#[must_use]
231pub fn status_path() -> PathBuf {
232 crate::run::home().join("daemon.json")
233}
234
235/// Publish the status file for this process.
236pub fn write_status(status: &Status) -> Result<()> {
237 write_status_to(&status_path(), status)
238}
239
240/// Publish a status to an explicit path.
241///
242/// Written to a sibling `.tmp` and renamed, because the web UI reads this file
243/// on every health poll and must never see a half-written one.
244pub fn write_status_to(path: &Path, status: &Status) -> Result<()> {
245 if let Some(parent) = path.parent() {
246 std::fs::create_dir_all(parent).with_context(|| format!("create {}", parent.display()))?;
247 }
248 let body = serde_json::to_string_pretty(status).context("serialize daemon status")?;
249 let tmp = path.with_extension("json.tmp");
250 std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
251 std::fs::rename(&tmp, path).with_context(|| format!("replace {}", path.display()))?;
252 Ok(())
253}
254
255/// Delete the status file. Called on the way out so a clean exit reads as
256/// "no daemon" rather than as a daemon whose heartbeat merely stopped.
257pub fn clear_status() {
258 clear_status_at(&status_path());
259}
260
261/// Delete a status file at an explicit path, so the loop's teardown and
262/// [`clear_status`] cannot drift apart: the loop is handed the path it
263/// published to, and a test can watch a temp file disappear.
264fn clear_status_at(path: &Path) {
265 let _ = std::fs::remove_file(path);
266}
267
268/// A cooperative stop, shared with whoever asked the loop to run.
269///
270/// Cloning is how the request travels: [`serve_until`] keeps one handle, the
271/// Ctrl-C listener and the web UI keep others, and every clone points at the
272/// same flag. There is no channel because there is nothing to send — the only
273/// message is "stop", it is idempotent, and a flag cannot be missed by a
274/// receiver that was not listening yet.
275///
276/// The handle also answers the question the operator's screen asks next: a
277/// stop does not take effect until the run in flight has finished, so
278/// [`Stop::finishing`] reports "asked to stop, still working" rather than
279/// leaving a caller to infer it from a heartbeat and hope.
280#[derive(Debug, Clone, Default)]
281pub struct Stop {
282 /// Set once, never cleared: a stop is not something an operator takes back
283 /// half way through, and a clearable flag would let a start racing a stop
284 /// resurrect a loop that is already unwinding.
285 stopped: Arc<AtomicBool>,
286 /// How many runs are in flight, so `finishing` can distinguish a stop
287 /// that has landed from one that is waiting on `execute`. A count, not a
288 /// flag, because more than one run can be in flight at once - see
289 /// [`crate::config::Daemon::max_concurrent_runs`] - and the last one to
290 /// finish is the one that should turn "finishing" off.
291 busy: Arc<std::sync::atomic::AtomicUsize>,
292 /// Wakes the idle wait. Without this a stop would not be seen until the
293 /// poll interval elapsed, and an operator tapping stop on a phone would
294 /// watch a button do nothing for five seconds.
295 wake: Arc<Notify>,
296 /// Handed to the run in flight, so a stop can also mean "park at the next
297 /// node boundary" instead of "finish the whole competition first".
298 pause: crate::graph::Pause,
299}
300
301impl Stop {
302 /// A stop nobody has asked for yet.
303 #[must_use]
304 pub fn new() -> Self {
305 Self::default()
306 }
307
308 /// Ask the loop to stop. Idempotent, and safe to call before the loop
309 /// starts: the flag is checked before the first poll.
310 pub fn stop(&self) {
311 self.stopped.store(true, Ordering::SeqCst);
312 // `notify_one` rather than `notify_waiters` because the loop may not be
313 // parked yet: this stores a permit, so a wait that registers a moment
314 // later returns at once instead of sleeping out the whole interval.
315 self.wake.notify_one();
316 }
317
318 /// Has a stop been asked for?
319 #[must_use]
320 pub fn stopped(&self) -> bool {
321 self.stopped.load(Ordering::SeqCst)
322 }
323
324 /// Has a stop been asked for that has not taken effect yet, because a run
325 /// is still in flight?
326 ///
327 /// This is the state a screen has to be able to show. A stop never abandons
328 /// a run — see [`serve_until`] — so between the tap and the loop's return
329 /// there is a window of tens of minutes in which "running" and "stopped"
330 /// are both misleading answers.
331 #[must_use]
332 pub fn finishing(&self) -> bool {
333 self.stopped() && self.busy_now()
334 }
335
336 /// Ask the loop to stop *and* the run in flight to park at its next node
337 /// boundary.
338 ///
339 /// The plain [`Stop::stop`] never abandons a run, which is right when the
340 /// operator only wants the queue to drain: a competition is tens of
341 /// minutes and its worktrees are paid for. But an operator who wants to
342 /// replace the binary cannot wait out a run that has an hour left, and
343 /// killing the process loses whatever the seats in flight had not written.
344 /// Parking costs at most the node in progress and leaves the run
345 /// resumable.
346 pub fn park(&self) {
347 self.pause.park();
348 self.stop();
349 }
350
351 /// Has a park been asked for?
352 #[must_use]
353 pub fn parking(&self) -> bool {
354 self.pause.parked()
355 }
356
357 /// The pause handle to give a runner.
358 #[must_use]
359 pub fn pause(&self) -> crate::graph::Pause {
360 self.pause.clone()
361 }
362
363 /// Is any run in flight right now?
364 ///
365 /// `finishing` answers "a stop is waiting on a run", which is false until
366 /// someone asks to stop. An upgrade needs the plain question, because it
367 /// is about to be the one asking.
368 #[must_use]
369 pub fn busy_now(&self) -> bool {
370 self.busy.load(Ordering::SeqCst) > 0
371 }
372
373 /// Mark one more run as in flight, for [`Stop::finishing`].
374 fn enter(&self) {
375 self.busy.fetch_add(1, Ordering::SeqCst);
376 }
377
378 /// Mark one run as finished. The last one out is what makes
379 /// [`Stop::busy_now`] false again.
380 fn exit(&self) {
381 self.busy.fetch_sub(1, Ordering::SeqCst);
382 }
383
384 /// Wait out one poll interval, returning early once a stop is asked for.
385 async fn idle(&self, poll: Duration) {
386 tokio::select! {
387 () = tokio::time::sleep(poll) => {}
388 () = self.wake.notified() => {}
389 }
390 }
391}
392
393/// The daemon's published state, read permissively.
394///
395/// This mirrors [`Status`], but is a separate declaration on purpose: every
396/// field defaults, so a status file from an older or newer magi still yields
397/// a usable reading — one this build has never heard of — instead of a parse
398/// error that hides the daemon entirely.
399#[derive(Debug, Clone, Default, Deserialize)]
400#[serde(default)]
401pub struct Reading {
402 /// Format version the daemon claims.
403 pub schema: u32,
404 /// Daemon process id, for an operator who wants to stop it.
405 pub pid: Option<u32>,
406 /// When that process started.
407 pub started_at: Option<Timestamp>,
408 /// Last heartbeat. Absent means the file is unusable, hence not running.
409 pub updated_at: Option<Timestamp>,
410 /// True when the queue had nothing runnable at the last poll.
411 pub idle: bool,
412 /// What the daemon is working on. Empty means idle; more than one entry
413 /// means more than one run is in flight at once.
414 ///
415 /// `deserialize_with` rather than the plain derive: a daemon started
416 /// before this field became a list is still out there writing the old
417 /// shape — a single `{"task":...,"run":...}` object, or its absence —
418 /// on every heartbeat until it is restarted, and a live process reading
419 /// that file during the rollout must still see it as running rather than
420 /// as absent. A bare type change here would fail the whole struct's
421 /// deserialization on a type mismatch, defeating the permissiveness this
422 /// type exists for.
423 #[serde(deserialize_with = "de_current")]
424 pub current: Vec<Current>,
425 /// Tasks this daemon process has finished.
426 pub completed: u64,
427 /// Queue polls this daemon process has made.
428 pub polls: u64,
429}
430
431/// Accept the old single-`Current`-or-absent shape as well as the current
432/// list, so a reader never has to know which build wrote the file.
433fn de_current<'de, D>(deserializer: D) -> std::result::Result<Vec<Current>, D::Error>
434where
435 D: serde::Deserializer<'de>,
436{
437 #[derive(Deserialize)]
438 #[serde(untagged)]
439 enum Shape {
440 Many(Vec<Current>),
441 One(Current),
442 }
443 Ok(
444 Option::<Shape>::deserialize(deserializer)?.map_or_else(Vec::new, |shape| match shape {
445 Shape::Many(v) => v,
446 Shape::One(c) => vec![c],
447 }),
448 )
449}
450
451impl Reading {
452 /// Seconds since the last heartbeat, or `None` when there has never been
453 /// one.
454 #[must_use]
455 pub fn age_secs(&self, now: Timestamp) -> Option<i64> {
456 self.updated_at
457 .map(|at| (now.as_second() - at.as_second()).max(0))
458 }
459
460 /// Whether the loop counts as running: a heartbeat no older than
461 /// [`STALE_SECS`]. The alternative is a reader that claims a task is in
462 /// progress hours after the daemon that owned it was killed.
463 #[must_use]
464 pub fn running(&self, now: Timestamp) -> bool {
465 self.age_secs(now).is_some_and(|secs| secs <= STALE_SECS)
466 }
467}
468
469/// Read `<home>/daemon.json` permissively, or `None` when there is nothing
470/// usable there.
471///
472/// Missing, half-written and unparseable all collapse to `None`, because the
473/// only question a reader asks is whether a daemon is alive, and a file it
474/// cannot read is not evidence that one is.
475#[must_use]
476pub fn read_status(home: &Path) -> Option<Reading> {
477 let body = std::fs::read_to_string(home.join("daemon.json")).ok()?;
478 serde_json::from_str(&body).ok()
479}
480
481/// Every run a live daemon is working on right now.
482///
483/// One definition of liveness, because deleting a task and deleting a run are
484/// both gated on it from both the CLI and the web UI - four callers that must
485/// never disagree about whether the same thing is in flight. A stale heartbeat
486/// reads as "no daemon": that is [`Reading::running`]'s judgement, and a task
487/// left at `running` or a run left at `implementing` by a killed daemon is a
488/// leftover record rather than work in progress. More than one entry once
489/// [`crate::config::Daemon::max_concurrent_runs`] is more than one - a caller
490/// after "the one thing in flight" wants [`is_working_on`] or
491/// [`is_working_on_task`], not this directly.
492#[must_use]
493pub fn current_work(home: &Path, now: Timestamp) -> Vec<Current> {
494 read_status(home)
495 .filter(|reading| reading.running(now))
496 .map(|reading| reading.current)
497 .unwrap_or_default()
498}
499
500/// Whether a live daemon is working on this run at this moment.
501#[must_use]
502pub fn is_working_on(home: &Path, run: &str, now: Timestamp) -> bool {
503 current_work(home, now).iter().any(|c| c.run == run)
504}
505
506/// Whether a live daemon is working on a run whose short id is this one.
507///
508/// For a worktree that has no run record to compare against at all -
509/// [`crate::clean::fold_orphaned_worktrees`]'s whole reason to exist - a full
510/// id is not available to hand to [`is_working_on`]. The short id is: a run's
511/// worktree bay is named after it (see [`crate::run::RunState::worktree_root`]),
512/// and it is exactly the gap between the daemon claiming a task and
513/// `RunState::new` saving the first `run.json` that this exists to protect -
514/// a run genuinely in flight but invisible to a scan of `runs/`.
515#[must_use]
516pub fn is_working_on_short(home: &Path, short: &str, now: Timestamp) -> bool {
517 current_work(home, now)
518 .iter()
519 .any(|c| crate::run::short_of(&c.run) == short)
520}
521
522/// Whether a live daemon is working on this task at this moment.
523#[must_use]
524pub fn is_working_on_task(home: &Path, task: &str, now: Timestamp) -> bool {
525 current_work(home, now).iter().any(|c| c.task == task)
526}
527
528/// Remove claim files whose owner is provably dead, or that have simply
529/// outlived `older_than`, and return the task ids swept.
530///
531/// A daemon killed with `SIGKILL` never runs [`crate::queue::Claim`]'s
532/// destructor, and the orphaned `.lock` file would make its task permanently
533/// unclaimable — the backlog would stop for good at exactly the task that was
534/// in flight when the machine went down.
535///
536/// The pid recorded in the lock is the authority whenever it can be read at
537/// all; age is only a fallback for when it cannot be.
538///
539/// - **A parseable pid wins outright.** [`crate::proc::pid_alive`] decides,
540/// full stop — dead sweeps the lock immediately, regardless of age; alive
541/// protects it, regardless of age. This is what lets a lock be reclaimed in
542/// seconds instead of waiting out [`STALE_CLAIM`]: a lock made 33 minutes
543/// before this daemon even started, next to a `queued` task, no longer has
544/// to sit for six hours before anything notices its owner is gone.
545/// - **A pid that cannot be parsed at all** — an empty or corrupt lock file —
546/// falls back to `older_than`, since there is nothing else to check.
547///
548/// Age must never override a *positive* liveness confirmation. `sweep`
549/// [`poll`]s concurrently with every attempt this daemon itself has spawned —
550/// see [`InFlightGuard`] — not only between them the way a single sequential
551/// loop once did, so a run that legitimately runs longer than `older_than`
552/// (a multi-round review, a long land wait carried across several resumed
553/// attempts) still has this very process's own live pid sitting in its own
554/// lock file on every later sweep. Deciding by age alone in that case would
555/// delete this daemon's own still-valid claim on its own in-flight task,
556/// which [`reclaim_orphaned_running`] would then read as abandoned and hand
557/// to a second attempt — two `Runner`s writing the same `run.json` and the
558/// same worktree at once. `pid_alive` answering "alive" for anything it
559/// cannot determine (a live process, a pid this build cannot check, one
560/// under another account) is exactly what keeps that path from ever
561/// firing on a guess.
562///
563/// [`STALE_CLAIM`] itself stays large: a helper program missing or its
564/// output unreadable must not be license to guess, and the risk of an
565/// unparseable lock outliving a genuinely dead owner is bounded by an order
566/// of magnitude above any plausible run rather than by a positive check.
567///
568/// Runs on every poll, not only at startup — a daemon up for days must keep
569/// noticing a lock some other, now-dead, daemon left behind just as readily
570/// as one it trips over on the way up.
571pub fn sweep_stale_claims(queue: &Queue, older_than: Duration) -> Vec<String> {
572 sweep_stale_claims_with(queue, older_than, crate::proc::pid_alive)
573}
574
575/// [`sweep_stale_claims`] with its process-query boundary supplied by the
576/// caller. This keeps the lock policy testable where process listing is
577/// unavailable, while production still uses the platform query above.
578fn sweep_stale_claims_with<F>(queue: &Queue, older_than: Duration, pid_alive: F) -> Vec<String>
579where
580 F: Fn(u32) -> bool,
581{
582 let this_process = std::process::id();
583 let mut swept: Vec<String> = std::fs::read_dir(queue.root())
584 .into_iter()
585 .flatten()
586 .flatten()
587 .map(|e| e.path())
588 .filter(|p| p.extension().is_some_and(|x| x == "lock"))
589 .filter(|p| {
590 match std::fs::read_to_string(p)
591 .ok()
592 .and_then(|body| body.trim().parse::<u32>().ok())
593 {
594 // This process wrote it and is asking the question right
595 // now, so it is definitionally still alive - settled without
596 // spawning a helper process at all.
597 Some(pid) if pid == this_process => false,
598 Some(pid) => !pid_alive(pid),
599 None => p
600 .metadata()
601 .and_then(|m| m.modified())
602 .and_then(|t| t.elapsed().map_err(std::io::Error::other))
603 .is_ok_and(|age| age >= older_than),
604 }
605 })
606 .filter(|p| std::fs::remove_file(p).is_ok())
607 .filter_map(|p| {
608 p.file_stem()
609 .and_then(|s| s.to_str())
610 .map(std::borrow::ToOwned::to_owned)
611 })
612 .collect();
613 swept.sort_unstable();
614 swept
615}
616
617/// Is `task` stalled: [`TaskStatus::Running`], past [`STALLED_RUNNING`], with
618/// no live daemon's heartbeat naming it? Deterministic — no model call, and
619/// the exact test [`stalled_tasks`] uses to decide what `crate::conduct` is
620/// shown.
621fn is_stalled(task: &Task, home: &Path, now: Timestamp) -> bool {
622 task.status == TaskStatus::Running
623 && (now.as_second() - task.updated_at.as_second()) >= STALLED_RUNNING.as_secs() as i64
624 && !is_working_on_task(home, &task.id, now)
625}
626
627/// Every task [`is_stalled`] right now — "止まったタスク" in
628/// `crate::conduct`'s vocabulary.
629fn stalled_tasks(queue: &Queue, home: &Path, now: Timestamp) -> Vec<Task> {
630 queue
631 .list()
632 .into_iter()
633 .filter(|t| is_stalled(t, home, now))
634 .collect()
635}
636
637/// Runnable tasks a dependency can still be set on — "runnable なタスク" in
638/// `crate::conduct`'s vocabulary. Deliberately `Queued` only, not
639/// `Failed`-and-so-also-runnable: a task that already attempted and lost
640/// belongs in [`finished_tasks`], where the question is a recovery, not a
641/// dependency.
642fn queued_tasks(queue: &Queue) -> Vec<Task> {
643 queue
644 .list()
645 .into_iter()
646 .filter(|t| t.status == TaskStatus::Queued)
647 .collect()
648}
649
650/// `Failed`/`Held` tasks nobody has decided a recovery for yet — "終わった
651/// タスク" in `crate::conduct`'s vocabulary.
652fn finished_tasks(queue: &Queue) -> Vec<Task> {
653 queue
654 .list()
655 .into_iter()
656 .filter(|t| matches!(t.status, TaskStatus::Failed | TaskStatus::Held))
657 .collect()
658}
659
660/// Deterministically resolve `Task::blocked_by`: a dependency task that
661/// reached `Done`, or a question that was answered, is removed — no model
662/// involved, on every poll. An answered question's content is copied onto
663/// the task ([`Task::record_answer`]) before its id is dropped, so it
664/// reaches the next `crate::conduct` prompt and the next run's instruction
665/// (see [`instruction_for`]) rather than only clearing the block.
666///
667/// A `blocked_by` id that names neither an existing task nor an existing
668/// question - `magi task rm` (or an operator by hand) deleted it while this
669/// task was still waiting - is caught before any of that: it can never
670/// become `Done` or `Answered`, so the ordinary loop below would otherwise
671/// leave the task `blocked` forever with nothing to notice. Such a task is
672/// quarantined to a machine hold instead ([`crate::queue::missing_blocker_hold_reason`]),
673/// which puts it in front of `crate::triage::run_once`'s own walk the next
674/// time it runs - see that module's doc for why the choice is "ask a human",
675/// never "assume the missing dependency was satisfied and unblock anyway".
676fn resolve_blockers(queue: &Queue, questions: &Questions) {
677 for listed in queue.list() {
678 if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
679 continue;
680 }
681 let Ok(_claim) = queue.claim(&listed.id) else {
682 continue;
683 };
684 let Ok(mut task) = queue.get(&listed.id) else {
685 continue;
686 };
687 if task.status != TaskStatus::Blocked {
688 continue;
689 }
690 let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
691 if !missing.is_empty() {
692 task.hold_machine(Some(crate::queue::missing_blocker_hold_reason(
693 &task.blocked_by,
694 &missing,
695 )));
696 record(queue, &mut task);
697 continue;
698 }
699 let mut changed = false;
700 for id in task.blocked_by.clone() {
701 if let Ok(dep) = queue.get(&id) {
702 if dep.status == TaskStatus::Done {
703 task.unblock(&id);
704 changed = true;
705 }
706 continue;
707 }
708 if let Ok(q) = questions.get(&id)
709 && q.status == ask::QuestionStatus::Answered
710 {
711 let answer = match &q.answer {
712 Some(ask::Answer::Choice(c) | ask::Answer::Text(c)) => c.clone(),
713 None => String::new(),
714 };
715 task.record_answer(q.summary.clone(), answer);
716 task.unblock(&id);
717 changed = true;
718 }
719 }
720 if changed {
721 record(queue, &mut task);
722 }
723 }
724}
725
726/// What [`decide_action`] concluded about one answered question.
727#[derive(Debug, Clone, PartialEq, Eq)]
728enum ActionDecision {
729 /// Nothing to do now (no action, already applied, or the task is busy).
730 Skip,
731 /// Continue the named run instead of competing again.
732 Resume(String),
733 /// Requeue as a fresh competition.
734 Requeue,
735 /// Close the task as done.
736 Done,
737 /// The question is about an earlier attempt than the task's latest; it
738 /// is recorded as handled and changes nothing.
739 Stale,
740 /// The action cannot be carried out; hold the task and say why. Never
741 /// falls back to something else, because the operator chose this one.
742 Refuse(String),
743}
744
745/// Decide what the choice answered on `q` means for `task`. Pure: `load`
746/// reads a run's state, as with [`unfinished_run_with`].
747///
748/// `Resume` only fires on the task's *latest* run, and only while that run
749/// could actually make progress ([`RunStatus::resumable`], not released, review
750/// budget left); an answer naming anything else is refused rather than
751/// reinterpreted as a fresh competition.
752fn decide_action<F>(task: &Task, q: &ask::Question, load: F) -> ActionDecision
753where
754 F: FnOnce(&str) -> Result<RunState>,
755{
756 let Some(action) = q.chosen_action() else {
757 return ActionDecision::Skip;
758 };
759 if task.action_applied(&q.id)
760 || matches!(
761 task.status,
762 TaskStatus::Running | TaskStatus::Blocked | TaskStatus::Done
763 )
764 {
765 return ActionDecision::Skip;
766 }
767 // A question about an earlier attempt must not act on a newer one. A
768 // conductor question is keyed by the task id, not a run, so it is exempt.
769 if q.node != crate::conduct::NODE && task.runs.last() != Some(&q.run) {
770 return ActionDecision::Stale;
771 }
772 match action {
773 ask::ChoiceAction::Requeue => ActionDecision::Requeue,
774 ask::ChoiceAction::Done => ActionDecision::Done,
775 ask::ChoiceAction::Resume { run } => {
776 if task.runs.last() != Some(run) {
777 return ActionDecision::Refuse(format!(
778 "question {} asked to resume run {}, which is not this task's latest run",
779 q.short(),
780 ask::short_id(run)
781 ));
782 }
783 match load(run) {
784 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
785 ActionDecision::Resume(run.clone())
786 }
787 Ok(_) => ActionDecision::Refuse(format!(
788 "question {} asked to resume run {}, which cannot make progress",
789 q.short(),
790 ask::short_id(run)
791 )),
792 Err(e) => ActionDecision::Refuse(format!(
793 "question {} asked to resume run {}, which could not be read: {e:#}",
794 q.short(),
795 ask::short_id(run)
796 )),
797 }
798 }
799 }
800}
801
802/// The task an answered question speaks for: the one whose runs include the
803/// question's run, or - for a conductor question, filed under the task's own
804/// id - the task with that id.
805fn task_of_question<'a>(tasks: &'a [Task], q: &ask::Question) -> Option<&'a Task> {
806 if q.node == crate::conduct::NODE {
807 return tasks.iter().find(|t| t.id == q.run);
808 }
809 tasks.iter().find(|t| t.runs.contains(&q.run))
810}
811
812/// Carry out the [`ask::ChoiceAction`] attached to each answered choice, once.
813///
814/// Runs on every poll before the conductor looks at the queue. The task is
815/// re-read under its claim, so a task somebody completed or held by hand in
816/// the meantime is judged on what it is now. `Resume` releases the task and
817/// records a pinned [`crate::queue::OperatorResume`], which `crate::conduct`
818/// honours (no re-hold, no requeue) until the task runs and [`attempt`]'s
819/// ordinary `unfinished_run` logic resumes that same run.
820fn apply_choice_actions(queue: &Queue, questions: &Questions, home: &Path) {
821 let tasks = queue.list();
822 for q in questions.list() {
823 if q.chosen_action().is_none() {
824 continue;
825 }
826 let Some(listed) = task_of_question(&tasks, &q) else {
827 continue;
828 };
829 if listed.action_applied(&q.id) {
830 continue;
831 }
832 let Ok(_claim) = queue.claim(&listed.id) else {
833 continue;
834 };
835 let Ok(mut task) = queue.get(&listed.id) else {
836 continue;
837 };
838 let decision = decide_action(&task, &q, |id| RunState::load_under(id, home));
839 let ran = matches!(
840 decision,
841 ActionDecision::Resume(_) | ActionDecision::Requeue | ActionDecision::Done
842 );
843 if ran {
844 // Whoever delivers the answer first owns it: the waiter resuming
845 // the asking seat, or this. A delivery in flight keeps a fresh
846 // lease, and the flag is taken atomically *before* the task is
847 // touched, so the two can never both act on one answer.
848 if questions
849 .read_lease(&q.id)
850 .is_some_and(|l| l.fresh(Timestamp::now()))
851 {
852 continue;
853 }
854 let taken = questions.update(&q.id, |r| {
855 let free = !r.answer_delivered;
856 r.answer_delivered = true;
857 Ok(free)
858 });
859 if !matches!(taken, Ok((_, true))) {
860 continue;
861 }
862 }
863 match decision {
864 ActionDecision::Skip => continue,
865 ActionDecision::Resume(run) => {
866 task.release();
867 task.resume_override = Some(crate::queue::OperatorResume {
868 question_id: q.id.clone(),
869 at: Timestamp::now(),
870 conductor_rehold: None,
871 forced: true,
872 pinned_run: Some(run),
873 });
874 }
875 ActionDecision::Stale => {}
876 ActionDecision::Requeue => task.requeue(),
877 ActionDecision::Done => {
878 task.succeed();
879 supersede_prior_runs(&task, home);
880 }
881 ActionDecision::Refuse(why) => {
882 task.hold_machine(Some(why));
883 notices::raise(
884 Notice::warn(
885 &format!("action:{}", q.id),
886 "An answer asked the daemon to resume a run that cannot be resumed; the task stays held.",
887 )
888 .link(Link::Task {
889 id: task.id.clone(),
890 }),
891 );
892 }
893 }
894 task.mark_action_applied(&q.id);
895 record(queue, &mut task);
896 }
897}
898
899/// Retire an unanswered conductor question after its task no longer refers to
900/// it. Conductor questions use the task id in `Question::run`, so run-based
901/// cleanup cannot observe a manual release or completion.
902///
903/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
904/// own question also carries a `run`, and a run id that happens to collide
905/// with some task's id is not this loop's business — only a conductor
906/// question actually uses the task id that way. One `Questions::list()` scan
907/// is taken up front and matched against the in-memory task set, rather than
908/// calling `Questions::open_for` (a full disk scan on its own) once per task.
909fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
910 let tasks = queue.list();
911 let by_id: std::collections::BTreeMap<&str, &Task> =
912 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
913 let referenced: std::collections::BTreeSet<&str> = tasks
914 .iter()
915 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
916 .collect();
917
918 for mut question in questions.list() {
919 if !question.status.open() || question.node != crate::conduct::NODE {
920 continue;
921 }
922 // Keep questions a task still names, including when the reference
923 // moved to a dependent task.
924 if referenced.contains(question.id.as_str()) {
925 continue;
926 }
927 let Some(task) = by_id.get(question.run.as_str()) else {
928 continue;
929 };
930 question.abandon(format!(
931 "task {} no longer waits for this answer",
932 task.short()
933 ));
934 if let Err(e) = questions.put(&mut question) {
935 tracing::warn!(
936 "could not retire question {} for task {}: {e:#}",
937 question.short(),
938 task.short()
939 );
940 }
941 }
942}
943
944/// What a finished run tells the queue about the task it came from.
945///
946/// A struct rather than a fourth and fifth boolean argument: the two flags
947/// answer different questions about the same run, and a call site passing
948/// `(…, true, false)` is one transposition away from refunding attempts
949/// forever.
950#[derive(Debug, Clone, Copy)]
951pub struct Verdict {
952 /// Where the graph stopped.
953 pub status: RunStatus,
954 /// The run opened a pull request.
955 pub left_pr: bool,
956 /// At least one seat was lost to a rate limit.
957 pub quota_hit: bool,
958 /// The run parked at a node boundary because it was asked to.
959 pub parked: bool,
960 /// The run never produced a single candidate a judge could look at.
961 ///
962 /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
963 /// still have another candidate worth judging, in which case the loss was
964 /// not the reason nothing came of the run. This is `true` only when the
965 /// implement wave ended with nothing viable at all.
966 pub no_viable_candidates: bool,
967}
968
969/// Record a finished run against the task it came from.
970///
971/// Kept pure and separate from the loop because this mapping *is* the retry
972/// policy, and a policy that can only be exercised by spawning a graph is a
973/// policy nobody checks. The table:
974///
975/// | run status | task becomes | attempt spent |
976/// |---------------------------------------|---------------------|---------------|
977/// | parked at a boundary | `Failed` (requeued) | **no** |
978/// | `Merged`, `Ready` | `Done` | yes |
979/// | `Stalled`, quota hit | `Failed` (requeued) | **no** |
980/// | `Failed`, quota hit, no viable cand. | `Failed` (requeued) | **no** |
981/// | `Stalled`, no quota | `Failed`, or `Held` | yes |
982/// | `Blocked` with a PR | `Held` | yes |
983/// | `Blocked`, `Failed` otherwise | `Failed`, or `Held` | yes |
984/// | `VerifiedNoop` | `Held` | yes |
985/// | anything non-terminal | `Failed`, or `Held` | yes |
986///
987/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
988/// deliberately: every candidate agreeing there is nothing to write is not a
989/// machine fact about a rate limit, it is an unverified claim about the
990/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
991/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
992/// claim could be wrong (a misread instruction, a stale check), and closing
993/// the task automatically on an implementer's say-so would be the exact
994/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
995/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
996/// above, which settles through the same [`Task::handed_off`]: `Held` is not
997/// `Failed`-and-requeued, so nothing retries this task on the same unverified
998/// claim regardless of whether the one already-spent attempt is refunded, and
999/// [`Task::release`] resets the count to zero anyway the moment a human looks
1000/// at the evidence and lets it run again.
1001///
1002/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
1003/// twice, together. A quorum lost to rate limits is a property of the machine
1004/// and not of the task, so the attempt is refunded and a reset quota picks
1005/// the work up where it stopped — and that is just as true when every
1006/// implement seat lost the same race and `after_implement` bails with nothing
1007/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
1008/// machine fact. The `no_viable_candidates` guard is what keeps that row
1009/// narrow: a `Failed` run that produced a real candidate which then lost for
1010/// some other reason still spends the attempt, exactly like the quorum lost
1011/// to judges that answered with the wrong shape is ordinary flakiness, and
1012/// refunding *that* takes the bound off the retry loop entirely: run e633
1013/// stalled with `quota: []` after two judges wrote unusable JSON, was
1014/// refunded, and the next attempt paid for a fresh hour-long implement wave
1015/// before it could fail the same way. `max_attempts` exists precisely so
1016/// that cannot repeat forever.
1017///
1018/// A non-terminal status means `execute` returned while the graph was still
1019/// mid-flight, which is a bug rather than a verdict; it is treated as a
1020/// failure so that a task cannot loop on it either.
1021///
1022/// `left_pr` splits the `Blocked` row, and it is the difference between a run
1023/// that failed and a run that finished into a gate. See [`Task::handed_off`].
1024pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
1025 // A parked run is the operator's own doing, and its work is intact on
1026 // disk. The task goes back in line with its attempt refunded so the next
1027 // loop resumes the same run - which `one_task` prefers over competing
1028 // again - and so that swapping the binary a few times cannot exhaust a
1029 // budget meant for agents that actually misbehaved.
1030 if verdict.parked {
1031 task.stall(detail);
1032 return;
1033 }
1034 match verdict.status {
1035 RunStatus::Merged | RunStatus::Ready => task.succeed(),
1036 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
1037 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
1038 task.stall(detail)
1039 }
1040 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
1041 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
1042 RunStatus::Blocked => task.fail(detail, max_attempts),
1043 RunStatus::VerifiedNoop => task.handed_off(detail),
1044 other => task.fail(
1045 format!(
1046 "the graph stopped at `{}` without reaching a terminal status: {detail}",
1047 label(other)
1048 ),
1049 max_attempts,
1050 ),
1051 }
1052}
1053
1054/// Rewrite this task's now-moot earlier attempts — [`Task::superseded_attempts`]
1055/// — from `Blocked`/`Stalled` to [`RunStatus::Superseded`], once the task
1056/// itself has actually finished *and* its own last attempt is provably why:
1057/// this loads that run and requires `Merged`/`Ready` before touching
1058/// anything earlier in `runs`, since `Task::succeed` can also be called
1059/// directly on a task whose last attempt never landed at all.
1060///
1061/// Called right after whatever call set `task.status` to
1062/// [`TaskStatus::Done`] — this module's own `settle`'s callers below and
1063/// `reclaim`'s, but also every other place a task can be closed by hand
1064/// without the loop ever settling it itself: `magi task done`
1065/// (`main::TaskCmd::Done`) and `POST /api/queue/{id}/done`
1066/// (`web::queue_done`). Closing a task by hand — after confirming a manual
1067/// GitHub merge, say, exactly the workflow this repository's own
1068/// "Landing a run's winner by hand" documents — is just as much "this task's
1069/// story is over" as a daemon-driven `Merged`/`Ready` is, and skipping it
1070/// there would leave every earlier attempt stuck at `Blocked`/`Stalled`
1071/// forever, which is the exact backlog this status exists to clear. `pub`
1072/// for those two out-of-module callers; everything else about this stays
1073/// internal bookkeeping.
1074///
1075/// A run something is still actually driving is left alone: a
1076/// task cannot be `Done` while one of its *own* attempts is still in flight,
1077/// so a live one at this point can only be an unrelated process — a manual
1078/// `--resume` of this old, now-moot run — and rewriting under it would just
1079/// be undone (back to `Blocked`/`Stalled`, or worse) the next time that
1080/// process itself saves. This is the same `daemon_claims` + [`RunState::liveness`]
1081/// pair `run_report`/`run_detail` use for the same question elsewhere:
1082/// `is_working_on` alone only ever proves a *daemon* claim, not a `magi run
1083/// --resume` invoked by hand outside it, which `liveness` also checks via
1084/// the run's own recorded `driver_pid`. Anything not `Blocked` or `Stalled`
1085/// (already terminal in some other way, or itself mid-run) is left untouched
1086/// too.
1087///
1088/// Best-effort, like the rest of this module's bookkeeping: a load or save
1089/// failure here is a `tracing::warn`, not a failed settle, and the next time
1090/// this same task's completion is recorded — or a daemon restart replays
1091/// `reclaim_orphaned_running` — is another chance to catch up. There is no
1092/// separate reconciliation pass; if that gap ever matters in practice, one
1093/// can be added then.
1094///
1095/// `home` is a parameter, not the process-global [`crate::run::home`], for
1096/// the same reason [`RunState::save_under`] takes one: `web::queue_done`
1097/// calls this with `ui.home`, which is `crate::run::home()` in a real
1098/// process but a fixture's own directory under test — falling through to
1099/// the global there would read and write through whichever home some other
1100/// test in the same binary happened to pin into that `OnceLock` first, not
1101/// the run this call actually means.
1102pub fn supersede_prior_runs(task: &Task, home: &Path) {
1103 let now = Timestamp::now();
1104 // `Task::superseded_attempts` cannot tell a loop-driven `Done` (always
1105 // right behind a `Merged`/`Ready` verdict) from one set directly by
1106 // `magi task done`/its web equivalent/the conductor on a task whose last
1107 // recorded attempt never actually landed - that requires reading the
1108 // run itself, which is exactly what this does before trusting anything
1109 // in `runs` is safe to relabel.
1110 let last_run_succeeded = task
1111 .runs
1112 .last()
1113 .and_then(|id| RunState::load_under(id, home).ok())
1114 .is_some_and(|s| matches!(s.status, RunStatus::Merged | RunStatus::Ready));
1115 for id in task.superseded_attempts(last_run_succeeded) {
1116 let mut state = match RunState::load_under(id, home) {
1117 Ok(s) => s,
1118 Err(e) => {
1119 tracing::warn!("could not load run {id} to mark it superseded: {e:#}");
1120 continue;
1121 }
1122 };
1123 if !matches!(state.status, RunStatus::Blocked | RunStatus::Stalled) {
1124 continue;
1125 }
1126 let daemon_claims = is_working_on(home, id, now);
1127 if state.liveness(daemon_claims) == Liveness::Live {
1128 continue;
1129 }
1130 state.status = RunStatus::Superseded;
1131 if let Err(e) = state.save_under(home) {
1132 tracing::warn!("could not mark run {id} superseded: {e:#}");
1133 }
1134 }
1135}
1136
1137/// Catch up every `Done` task [`supersede_prior_runs`] could not fully
1138/// finish the moment it was called, because one of its earlier attempts was
1139/// still live then - a `magi run --resume` invoked by hand on an old run,
1140/// most likely.
1141///
1142/// That skip is correct at the time (rewriting under a run something is
1143/// still actively saving would just be undone), but a task only ever
1144/// reaches `Done` once, so without this nothing would ever look at it
1145/// again: if that manual process later ends anywhere other than
1146/// `Merged`/`Ready` - abandoned, or landed as another `Blocked` - the
1147/// skipped attempt would sit at `Blocked`/`Stalled` forever, exactly the
1148/// backlog this status exists to clear. Called on the same idle-only
1149/// cadence as [`janitor`], next to it rather than folded into it: this
1150/// walks `queue` and `janitor` never otherwise needs one.
1151///
1152/// Simply re-running [`supersede_prior_runs`] over every `Done` task with
1153/// more than one attempt, every pass: each call is a handful of local file
1154/// reads bounded by that task's own attempt count, the same order of cost
1155/// [`clean::fold_due`] already pays scanning every run on disk on the same
1156/// cadence, and a task already fully resolved costs one failed liveness
1157/// check turned no-op the moment its lingering attempt is no longer live.
1158fn resweep_superseded_attempts(queue: &Queue, home: &Path) {
1159 for task in queue.list() {
1160 if task.status != TaskStatus::Done || task.runs.len() < 2 {
1161 continue;
1162 }
1163 supersede_prior_runs(&task, home);
1164 }
1165}
1166
1167/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
1168/// task ends up held.
1169///
1170/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
1171/// dead daemon never got back to) share this, so the two cannot drift into
1172/// disagreeing about which held tasks get a diagnostic.
1173fn settle_and_diagnose(
1174 task: &mut Task,
1175 verdict: Verdict,
1176 detail: &str,
1177 max_attempts: usize,
1178 state: &RunState,
1179) {
1180 settle(task, verdict, detail, max_attempts);
1181 if task.status == TaskStatus::Held {
1182 task.diagnostic = diagnostic(state);
1183 note_open_question(task, &state.id);
1184 }
1185}
1186
1187/// If `task` is held with a `magi ask` question still open on `run`, name the
1188/// question in [`Task::hold_reason`] rather than leaving the hold reading
1189/// only [`describe`]'s run summary.
1190///
1191/// This is the shape task 20260928-191407-05fd left underspecified: an
1192/// implementer settled a verified no-op and filed a question for the
1193/// operator, and the hold that followed said nothing about the question
1194/// waiting on them. Appended, not substituted - [`crate::triage`] parses the
1195/// existing text ([`is_disk_hold`](crate::triage), the answered-question
1196/// marker) and must keep seeing it unchanged.
1197///
1198/// Best-effort: an unreadable question store must not stop a run from
1199/// settling, so this is a no-op rather than a propagated error when
1200/// [`crate::run::try_home`] has nothing to offer or the store is empty.
1201fn note_open_question(task: &mut Task, run: &str) {
1202 let Some(home) = crate::run::try_home() else {
1203 return;
1204 };
1205 let open = Questions::at(home.join("questions")).open_for(run);
1206 let Some(q) = open.first() else {
1207 return;
1208 };
1209 let base = task.hold_reason.clone().unwrap_or_default();
1210 task.hold_reason = Some(format!(
1211 "{base} - waiting for operator answer to question {}",
1212 q.short()
1213 ));
1214}
1215
1216/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
1217/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
1218/// by some other means entirely, like a manual `magi run` resume that
1219/// finishes the graph outside the queue's bookkeeping.
1220///
1221/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
1222/// `settle` is separate from `attempt`: a task recovered this way must land
1223/// exactly where a live daemon would have put it — the same policy table,
1224/// not a second one that quietly drifts from it — and that is only checkable
1225/// without spawning a real run.
1226fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
1227 match last_run {
1228 Some(state) => {
1229 let verdict = Verdict {
1230 status: state.status,
1231 left_pr: state.pr.is_some(),
1232 quota_hit: !state.quota.is_empty(),
1233 parked: state.parked,
1234 no_viable_candidates: state.viable().is_empty(),
1235 };
1236 let detail = format!(
1237 "recovered a `running` task whose daemon never recorded the outcome: {}",
1238 describe(&state)
1239 );
1240 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
1241 }
1242 None => {
1243 let why = "task was `running` with no live daemon and no readable \
1244 run to recover; held for a human to check what happened";
1245 task.last_error = Some(why.to_owned());
1246 // The phone shows `hold_reason`, so a task held by the machine
1247 // says why there too and not only in `last_error`.
1248 task.hold_machine(Some(why.to_owned()));
1249 }
1250 }
1251}
1252
1253/// Find every task left at `running` that no live process is actually
1254/// driving, and settle each one against whatever its last run became.
1255///
1256/// # Why a claim is proof, not a guess
1257///
1258/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
1259/// `running`, and the guard is held for the task's whole time in that status:
1260/// `attempt` does not return, and the loop does not move past the scope
1261/// holding the claim, until the run has settled. So a `running` task whose
1262/// lock is gone cannot have a live owner — this process or any other —
1263/// without needing a staleness threshold or a pid check the way
1264/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
1265/// task that never got as far as `running` at all. Taking the claim here is
1266/// the whole test: it either fails, because something really does hold it
1267/// and the task is left alone, or it succeeds, which is the proof — and it is
1268/// kept for the rest of the decision so nothing else can start a competing
1269/// run while this one is being written.
1270///
1271/// Called on every poll, not only at startup, for the reason
1272/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
1273/// keep noticing this, not only on the one morning it happened to restart.
1274fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
1275 let mut reclaimed = Vec::new();
1276 for listed in queue.list() {
1277 if listed.status != TaskStatus::Running {
1278 continue;
1279 }
1280 let Ok(_claim) = queue.claim(&listed.id) else {
1281 continue;
1282 };
1283 // Re-read under the claim: a release or an edit landed by a human
1284 // between the listing above and the claim just taken must not be
1285 // clobbered by a decision based on the stale copy.
1286 let Ok(mut task) = queue.get(&listed.id) else {
1287 continue;
1288 };
1289 if task.status != TaskStatus::Running {
1290 continue;
1291 }
1292 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
1293 // `execute` normally abandons a run's own open questions the moment
1294 // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
1295 // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
1296 // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
1297 // with the question still `open`, because the process died before
1298 // reaching that call. `reclaim` itself stays pure on purpose (see its
1299 // own doc), so the same cleanup runs here instead, against the run
1300 // this reclaim is already reading. `settle_run` costs nothing when
1301 // `execute` already got there first.
1302 if let Some(state) = &last_run
1303 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
1304 {
1305 tracing::warn!("abandon questions for {}: {e:#}", state.id);
1306 }
1307 reclaim(&mut task, last_run, max_attempts);
1308 if task.status == TaskStatus::Done {
1309 supersede_prior_runs(&task, &crate::run::home());
1310 }
1311 record(queue, &mut task);
1312 reclaimed.push(task.id.clone());
1313 }
1314 reclaimed
1315}
1316
1317/// Find every run whose `run.json` is provably dead — every seat it still
1318/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1319/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1320/// not merely "no daemon claims it" — and fail it, clearing the leftover
1321/// active seats so the run stops reading as `implementing` (or whichever
1322/// node) forever.
1323///
1324/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1325/// `running`, using whatever `run.json` already says — but nothing in that
1326/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1327/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1328/// never got back to sits exactly where it was left: `active` full of seats
1329/// nobody will ever answer for, `status` stuck on whatever node was in
1330/// flight. `magi show` already tells an operator this in prose (`no live
1331/// daemon claims this run right now`); this is what makes that fact durable
1332/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1333/// stay stuck once nothing is driving it.
1334///
1335/// Runs on every poll, not only at startup, for the reason
1336/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1337/// daemon up for days must keep noticing a run some other, now-dead, daemon
1338/// left behind just as readily as one it trips over on the way up.
1339///
1340/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1341/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1342/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1343/// `runs` directory instead: `home` here is a parameter precisely so a test
1344/// can point it away from the operator's real history (see [`drive`]'s own
1345/// doc), and a scan that fell through to the global home anyway would walk
1346/// whichever directory some *other* process or test pinned into that
1347/// `OnceLock` first — mutating runs this call was never handed.
1348fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1349 reclaim_abandoned_runs_with(
1350 home,
1351 now,
1352 crate::proc::pid_status,
1353 crate::proc::process_started_at,
1354 )
1355}
1356
1357/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1358/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1359/// for the identical reason: this sweep's real damage (wiping a run's active
1360/// seats and failing it) has to be provable against an injected answer in a
1361/// test, not just the real process table.
1362fn reclaim_abandoned_runs_with<F, G>(
1363 home: &Path,
1364 now: Timestamp,
1365 query: F,
1366 identity: G,
1367) -> Vec<String>
1368where
1369 F: Fn(u32) -> Option<bool>,
1370 G: Fn(u32) -> Option<String>,
1371{
1372 let mut abandoned = Vec::new();
1373 for entry in std::fs::read_dir(home.join("runs"))
1374 .into_iter()
1375 .flatten()
1376 .flatten()
1377 {
1378 let id = entry.file_name().to_string_lossy().into_owned();
1379 if !crate::run::is_run_id(&id) {
1380 continue;
1381 }
1382 // Unreadable is `clean::fold_due`'s problem, not this one's — see
1383 // that module's docs for why a run this cannot parse is left alone
1384 // rather than guessed at. A different schema number is not that: this
1385 // touches only `status` and `active`, never a field whose meaning a
1386 // schema bump changed, so an old record's values serve this exactly
1387 // as well as a current one's (see `clean::read_state`'s own doc for
1388 // the same reasoning applied to folding).
1389 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1390 continue;
1391 };
1392 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1393 continue;
1394 };
1395 if state.status.done() || !state.active_all_overrun(now) {
1396 continue;
1397 }
1398 // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1399 // it", which is also the normal, healthy shape of a manual `magi
1400 // run` / `magi review` sharing this same home — this scan walks
1401 // every run on disk, not only ones this daemon itself started. Such
1402 // a run's active seats can legitimately sit past their own timeout
1403 // for a little while (the CLI finishing up, its result still being
1404 // collected) without the process driving it having died. `liveness`
1405 // is what actually tells the two apart, by corroborating
1406 // `driver_pid` against the process it names — see its own doc. Only
1407 // its strongest, provable answer licenses wiping this run's active
1408 // seats and failing it out from under whatever is still running it.
1409 let daemon_claims = is_working_on(home, &id, now);
1410 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1411 continue;
1412 }
1413 state.abandon("daemon");
1414 if let Err(e) = state.save_under(home) {
1415 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1416 continue;
1417 }
1418 // This run never passes through `Runner::execute` again, so its end
1419 // is announced here.
1420 if let Some(notice) = notices::run_ended(&state) {
1421 notices::raise_in(home, notice);
1422 }
1423 // The seat that asked is gone for good now, exactly like any other
1424 // door `graph::Runner::settle_questions` closes the moment `status`
1425 // lands somewhere non-resumable - see that method's own doc. Nothing
1426 // else reaches this one before the next `janitor()` startup pass
1427 // (`clean::abandon_settled_questions`), and a daemon that stays up
1428 // for days must not leave an open question badging the operator
1429 // until it happens to restart.
1430 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1431 tracing::warn!("abandon questions for {id}: {e:#}");
1432 }
1433 abandoned.push(id);
1434 }
1435 abandoned
1436}
1437
1438/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1439///
1440/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1441/// sets, so there is one loop body rather than two that drift apart the first
1442/// time the retry policy changes on only one of them.
1443pub async fn serve(opts: Opts) -> Result<()> {
1444 serve_until(opts, Stop::new()).await
1445}
1446
1447/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1448///
1449/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1450/// mid-node leaves worktrees, branches and agent sessions behind, and every
1451/// agent call already paid for is lost; finishing the run costs the operator a
1452/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1453/// current `execute` runs to its terminal status, the task's outcome is
1454/// recorded, and only then does the loop return. That window is what
1455/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1456/// still has a second Ctrl-C, which the runtime turns into a process kill —
1457/// and the task left `Running` then tells the next daemon, and the next human,
1458/// where to look.
1459///
1460/// While the queue is empty the stop is honoured within one wakeup rather than
1461/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1462/// caller that taps stop does not sit through the remainder of a sleep.
1463pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1464 let signal = {
1465 let stop = stop.clone();
1466 tokio::spawn(async move {
1467 if tokio::signal::ctrl_c().await.is_ok() {
1468 stop.stop();
1469 tracing::info!("shutdown requested; a run in flight will be finished first");
1470 }
1471 })
1472 };
1473
1474 let worktrees_root = opts
1475 .worktrees_root
1476 .clone()
1477 .unwrap_or_else(crate::run::default_worktree_root);
1478 let outcome = drive(
1479 &opts,
1480 &Queue::open(),
1481 &status_path(),
1482 &crate::run::home(),
1483 &worktrees_root,
1484 &stop,
1485 )
1486 .await;
1487
1488 signal.abort();
1489 outcome
1490}
1491
1492/// The loop proper: setup, poll, teardown, with the queue and the status file
1493/// supplied rather than discovered.
1494///
1495/// All three of `home`, `worktrees_root` and the queue/status paths are
1496/// parameters rather than resolved here, for the same reason:
1497/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1498/// so a unit test that pinned it would fight every other test in the binary,
1499/// and a loop that resolved its own worktree bay could only be exercised
1500/// against the operator's real `~/wt/<repo>` - publishing over a live
1501/// daemon's status file, claiming tasks out of a live backlog, and, since
1502/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1503/// whatever the operator actually has on disk.
1504async fn drive(
1505 opts: &Opts,
1506 queue: &Queue,
1507 status_file: &Path,
1508 home: &Path,
1509 worktrees_root: &Path,
1510 stop: &Stop,
1511) -> Result<()> {
1512 // The status file is a *snapshot*, not a stream of events: a reader only
1513 // ever wants the latest values, and every tick rewrites the whole file
1514 // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1515 // while an mpsc channel would force the loop to re-send unchanged fields on
1516 // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1517 // for no gain. The lock is only ever held across a field assignment, never
1518 // across an await.
1519 let status = Arc::new(Mutex::new(Status::new()));
1520 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1521 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1522
1523 // Read once at startup, not per task: how many runs this loop drives at
1524 // once is a property of the machine running it, not of whichever
1525 // repository a given task happens to name - see
1526 // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1527 // fact in the same sense the agent roster is.
1528 let daemon_cfg = prepare(&opts.repo, opts)
1529 .map(|c| c.daemon)
1530 .unwrap_or_default();
1531 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1532
1533 // Something has to be waiting on every question for as long as it is open,
1534 // whether or not the agent's own `magi ask` survived. Its own task rather
1535 // than a step of the poll loop: the poll loop is busy for the whole of a
1536 // run, and an owner's reply must not queue behind one.
1537 let waiter = tokio::spawn(crate::waiter::run(
1538 crate::waiter::Waiter::new(
1539 crate::ask::Questions::at(home.join("questions")),
1540 home.to_path_buf(),
1541 prepare(&opts.repo, opts).ok(),
1542 ),
1543 stop.clone(),
1544 ));
1545
1546 tracing::info!(
1547 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1548 queue.root().display(),
1549 opts.poll.as_secs(),
1550 opts.max_attempts,
1551 concurrency,
1552 if daemon_cfg.pause_for_interrupts {
1553 ", interrupts enabled"
1554 } else {
1555 ""
1556 }
1557 );
1558
1559 // `--once` drains an already-idle queue without reaching the idle wait,
1560 // but must still perform the startup cleanup.
1561 janitor(&opts.repo, opts, home, worktrees_root).await;
1562 resweep_superseded_attempts(queue, home);
1563
1564 let outcome = poll(
1565 opts,
1566 queue,
1567 &status,
1568 home,
1569 worktrees_root,
1570 stop,
1571 DispatchLimits {
1572 max_concurrent: concurrency,
1573 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1574 },
1575 )
1576 .await;
1577
1578 beat.abort();
1579 waiter.abort();
1580 clear_status_at(status_file);
1581 outcome
1582}
1583
1584/// Refresh the status file on a fixed tick.
1585///
1586/// Separate from the loop because a run takes tens of minutes: a status file
1587/// written only between tasks would look stale for the whole of every run, and
1588/// a reader would report the daemon dead exactly while it was busiest.
1589async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1590 loop {
1591 tokio::time::sleep(HEARTBEAT).await;
1592 let snapshot = {
1593 let mut guard = lock(&status);
1594 guard.updated_at = Timestamp::now();
1595 guard.clone()
1596 };
1597 if let Err(e) = write_status_to(&path, &snapshot) {
1598 // A failed heartbeat must not take the daemon down: the loop is the
1599 // product, the status file is only the window onto it.
1600 tracing::warn!("could not refresh the daemon status file: {e:#}");
1601 }
1602 }
1603}
1604
1605/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1606/// if so, whether that wait is over.
1607#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1608enum LandResume {
1609 /// The task's last run is not parked on a land approval; schedule it
1610 /// like any other candidate.
1611 NotLanding,
1612 /// Parked in `land`, waiting on a question nobody has answered yet.
1613 /// Left alone: attempting it now would only re-observe the same pull
1614 /// request and park again, spending a `gh` call on a decision that has
1615 /// not changed since the last time this was checked.
1616 StillWaiting,
1617 /// Parked in `land`, and the question is settled - answered or
1618 /// abandoned. Resuming this is the one kind of candidate that must not
1619 /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
1620 Ready,
1621}
1622
1623/// Classify a runnable candidate by whether it is parked on a land-merge
1624/// approval. Read-only - no claim taken, nothing written - so it is cheap
1625/// enough to call on every candidate, every poll.
1626fn land_resume_state(task: &Task) -> LandResume {
1627 let Some(run_id) = task.runs.last() else {
1628 return LandResume::NotLanding;
1629 };
1630 let Ok(state) = RunState::load(run_id) else {
1631 return LandResume::NotLanding;
1632 };
1633 if state.status != RunStatus::Landing || !state.parked {
1634 return LandResume::NotLanding;
1635 }
1636 let store = ask::Questions::open();
1637 let waiting = store
1638 .list()
1639 .into_iter()
1640 .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1641 .max_by(|a, b| a.id.cmp(&b.id));
1642 let Some(mut q) = waiting else {
1643 return LandResume::Ready;
1644 };
1645 if !q.status.open() {
1646 return LandResume::Ready;
1647 }
1648 // `ask::ask_and_wait`'s own deadline is what used to retire a question
1649 // nobody ever answered; land's approval bypasses that wait entirely (see
1650 // `land::approval_gate`), so the same deadline has to be enforced here
1651 // instead, or `graph.answer_timeout` silently stops meaning anything for
1652 // a land approval and a run can sit `StillWaiting` forever with nobody
1653 // told to look at it.
1654 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1655 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1656 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1657 q.abandon(format!(
1658 "no answer within {}s of asking",
1659 timeout.as_secs().max(1)
1660 ));
1661 // If this can't be persisted, do not treat the wait as settled on a
1662 // guess: fall through and try again next poll.
1663 if store.put(&mut q).is_ok() {
1664 return LandResume::Ready;
1665 }
1666 }
1667 LandResume::StillWaiting
1668}
1669
1670/// How often the loop rechecks for new work while something it already
1671/// started is still running, rather than sleeping out the whole
1672/// [`Opts::poll`] interval.
1673///
1674/// Short on purpose: this is what lets a land-merge approval that comes back
1675/// while another task is mid-competition be noticed and resumed within a
1676/// fraction of a second, not within the next multi-second poll.
1677const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1678
1679/// How often [`poll`] rechecks the shared build cache against its cap at a
1680/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
1681/// waiting for the queue to run dry.
1682///
1683/// A queue that never empties means the `janitor` call at the bottom of this
1684/// loop's fully-idle branch can go unreached for as long as the backlog
1685/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
1686/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
1687/// 81.8 GiB an idle-only check let it reach before this existed, and it is
1688/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
1689/// backlog of short tasks does not pay for that walk on every poll.
1690const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
1691
1692/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1693/// in `Status::current` - on drop, so both are released even if the attempt
1694/// panics rather than returning.
1695///
1696/// A `Drop` impl rather than statements written after the `.await` it
1697/// guards: a panic unwinds straight past code placed "after" a call, and
1698/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1699/// that ruling a panic out there is not a bet this loop can make. Without
1700/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1701/// forever - the idle branch in [`poll`], and with it the janitor, would
1702/// never run again - and a ghost entry in `Status::current` naming a task
1703/// nothing is still working on.
1704struct InFlightGuard<'a> {
1705 status: &'a Arc<Mutex<Status>>,
1706 stop: &'a Stop,
1707 task_id: &'a str,
1708}
1709
1710impl Drop for InFlightGuard<'_> {
1711 fn drop(&mut self) {
1712 lock(self.status).current.retain(|c| c.task != self.task_id);
1713 self.stop.exit();
1714 }
1715}
1716
1717/// State of [`poll`]'s own interrupt-scheduling sequence - see
1718/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
1719/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
1720/// both kept free of `Task`'s non-identity fields on purpose: every decision
1721/// here turns only on task ids and which ones are in flight, so the "never
1722/// more than one run at once" and "exactly one resume" invariants can be
1723/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
1724/// queue - which is exactly the coverage this feature's first two attempts
1725/// were missing.
1726///
1727/// Deliberately in-memory only, not written to disk anywhere: a daemon
1728/// restart mid-sequence loses track of which run it had asked to park and
1729/// which task was meant to run first, and simply falls back to `Idle` -
1730/// see [`drive`]'s own setup. The parked run itself is not lost - it is
1731/// sitting in the queue exactly like any other resumable, interrupted task,
1732/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
1733/// just resumes on the ordinary priority order rather than guaranteed to go
1734/// first. Giving that guarantee a crash-proof memory would mean a new queue
1735/// field and a recovery ordering to go with it, which is exactly the
1736/// complexity this feature's constraints rule out for the one property that
1737/// actually matters: at most one run, ever, at once.
1738#[derive(Debug, Clone, PartialEq, Eq)]
1739enum Interrupt {
1740 /// No interrupt sequence in progress. Ordinary dispatch applies.
1741 Idle,
1742 /// `interrupt_task` is runnable and exactly one other run is in flight;
1743 /// `parked` names that one task's id. Dispatch is withheld from
1744 /// everyone, including `interrupt_task` itself, until it has left
1745 /// flight - only then is `interrupt_task` let through.
1746 ///
1747 /// `parked` is a `Vec` rather than a bare id for symmetry with
1748 /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
1749 /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
1750 /// when exactly one run is in flight, so it is guaranteed to hold
1751 /// exactly one entry in practice - see that branch's own doc for why
1752 /// more than one is deliberately never attempted.
1753 Parking {
1754 parked: Vec<String>,
1755 interrupt_task: String,
1756 },
1757 /// `interrupt_task` is dispatched and in flight alone. Dispatch is
1758 /// withheld from everyone until it leaves flight - merged, failed, held,
1759 /// it makes no difference - at which point the sequence moves to
1760 /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
1761 /// going straight to `Idle` would hand `parked` back to ordinary
1762 /// priority-order dispatch, where a higher-priority task filed in the
1763 /// meantime could start ahead of it.
1764 Running {
1765 parked: Vec<String>,
1766 interrupt_task: String,
1767 },
1768 /// `interrupt_task` left flight; `parked` still names the one run this
1769 /// sequence owes a resume. Dispatch is withheld from everyone except
1770 /// that task - see [`interrupt_gate`] - so the resume this feature
1771 /// promises is never raced by, or run alongside, an unrelated candidate.
1772 /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
1773 /// own doc on abandonment - the moment it is no longer runnable at all.
1774 Resuming { parked: Vec<String> },
1775}
1776
1777/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
1778/// and `runnable` are read-only snapshots of this tick's reality, and the
1779/// only side effect the caller still owes the world is asking whichever
1780/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
1781/// site.
1782///
1783/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
1784/// accepted rather than a narrower type because that is what [`poll`] already
1785/// has on hand from [`runnable`], and building a second, smaller list on
1786/// every tick just to satisfy this signature would cost more than it proves.
1787///
1788/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
1789/// back to a task they are waiting on no longer being [`runnable`] - held,
1790/// blocked, deleted, or finished by some other means entirely, all of which
1791/// an operator can do to a task sitting in the queue with no claim on it at
1792/// all, at any moment, interrupt sequence or not. Without this check the
1793/// sequence would wait forever for a dispatch that can never come, and
1794/// `interrupt_gate` would withhold every other task in the queue right along
1795/// with it - a single `magi task hold` on the wrong id turning into a
1796/// daemon that never dispatches anything again.
1797fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
1798 match state {
1799 Interrupt::Idle => {
1800 // Not just "something to interrupt": exactly one thing. More
1801 // than one run in flight only happens above the default
1802 // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
1803 // one resume, never run alongside anything else" only because
1804 // it is only ever seeded with exactly one id - see
1805 // `Interrupt::Resuming`'s own doc on why releasing more than one
1806 // parked id back to ordinary dispatch cannot be made safe
1807 // against that same setting's own extra concurrency slots.
1808 // Waiting here for the herd to settle to one is the
1809 // simplification this feature's own constraints ask for rather
1810 // than a second concurrency model to reconcile with the first.
1811 if in_flight.len() != 1 {
1812 return Interrupt::Idle;
1813 }
1814 match runnable.iter().find(|t| t.interrupt) {
1815 Some(t) => Interrupt::Parking {
1816 parked: in_flight.to_vec(),
1817 interrupt_task: t.id.clone(),
1818 },
1819 None => Interrupt::Idle,
1820 }
1821 }
1822 Interrupt::Parking {
1823 parked,
1824 interrupt_task,
1825 } => {
1826 if in_flight.iter().any(|id| parked.contains(id)) {
1827 // Still waiting for what was in flight to actually stop.
1828 Interrupt::Parking {
1829 parked,
1830 interrupt_task,
1831 }
1832 } else if in_flight.contains(&interrupt_task) {
1833 Interrupt::Running {
1834 parked,
1835 interrupt_task,
1836 }
1837 } else if runnable.iter().any(|t| t.id == interrupt_task) {
1838 // The parked run(s) are gone, but the interrupt task has not
1839 // been dispatched yet on this tick - `interrupt_gate` is
1840 // what lets it through next.
1841 Interrupt::Parking {
1842 parked,
1843 interrupt_task,
1844 }
1845 } else {
1846 // The interrupt task itself is no longer runnable - see this
1847 // function's own doc on abandonment. The parked run(s) still
1848 // get their guaranteed resume; there is simply no interrupt
1849 // to run ahead of them any longer.
1850 Interrupt::Resuming { parked }
1851 }
1852 }
1853 Interrupt::Running {
1854 parked,
1855 interrupt_task,
1856 } => {
1857 if in_flight.contains(&interrupt_task) {
1858 Interrupt::Running {
1859 parked,
1860 interrupt_task,
1861 }
1862 } else {
1863 // The interrupt task's own run reached a terminal status,
1864 // whichever one - this is the *only* trigger that moves the
1865 // sequence on, driven straight off the same in-flight
1866 // bookkeeping `poll` already reaps every tick, not a second,
1867 // independent poll of anything.
1868 Interrupt::Resuming { parked }
1869 }
1870 }
1871 Interrupt::Resuming { parked } => {
1872 if in_flight.iter().any(|id| parked.contains(id)) {
1873 // One of the parked runs has been dispatched - the resume
1874 // this sequence owed is fulfilled. Whatever else is left in
1875 // `parked` (ordinarily nothing, at the default concurrency
1876 // of one) rejoins ordinary priority-order dispatch, same as
1877 // any other runnable task.
1878 Interrupt::Idle
1879 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
1880 Interrupt::Resuming { parked }
1881 } else {
1882 // Abandonment (see this function's own doc): nothing left in
1883 // `parked` is even runnable any longer.
1884 Interrupt::Idle
1885 }
1886 }
1887 }
1888}
1889
1890/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
1891/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
1892/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
1893/// indistinguishable from any other runnable task - exactly the "off does
1894/// nothing" this feature promises.
1895fn advance_interrupt_tick(
1896 enabled: bool,
1897 state: Interrupt,
1898 in_flight: &[String],
1899 runnable: &[Task],
1900) -> Interrupt {
1901 if !enabled {
1902 return Interrupt::Idle;
1903 }
1904 advance_interrupt(state, in_flight, runnable)
1905}
1906
1907/// Which of this tick's runnable candidates the interrupt sequence actually
1908/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
1909/// each half is assertable on its own: this is the half that keeps a
1910/// competition and an interrupt from ever running at the same moment.
1911fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
1912 match state {
1913 Interrupt::Idle => candidates,
1914 Interrupt::Parking {
1915 parked,
1916 interrupt_task,
1917 } => {
1918 if in_flight.iter().any(|id| parked.contains(id)) {
1919 Vec::new()
1920 } else {
1921 candidates
1922 .into_iter()
1923 .filter(|t| &t.id == interrupt_task)
1924 .collect()
1925 }
1926 }
1927 Interrupt::Running { .. } => Vec::new(),
1928 // At most one: even if `parked` names more than one id (more than
1929 // one run was in flight when the sequence began, only possible
1930 // above the default `max_concurrent_runs = 1`), only the first match
1931 // is offered. Capping this to a single candidate - not merely to
1932 // `parked`'s own ids - is what makes "exactly one resume, never two
1933 // dispatched together" true regardless of how many ordinary slots
1934 // happen to be free this tick.
1935 Interrupt::Resuming { parked } => candidates
1936 .into_iter()
1937 .find(|t| parked.contains(&t.id))
1938 .into_iter()
1939 .collect(),
1940 }
1941}
1942
1943/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
1944/// bundled into one parameter so `poll`'s own signature stays readable -
1945/// see [`drive`]'s call site for where these are actually read.
1946struct DispatchLimits {
1947 /// How many *ordinary* candidates run at once. See
1948 /// [`crate::config::Daemon::max_concurrent_runs`].
1949 max_concurrent: usize,
1950 /// See [`crate::config::Daemon::pause_for_interrupts`].
1951 pause_for_interrupts: bool,
1952}
1953
1954/// Which semaphore, if any, dispatching a candidate should draw its permit
1955/// from.
1956///
1957/// Pure and separate from [`poll`]'s loop body for the same reason
1958/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
1959/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
1960/// exactly the policy this feature adds, and a policy only exercisable by
1961/// running the whole loop is a policy nobody checks.
1962#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1963enum PermitKind {
1964 /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
1965 /// Checked first - a task can be both a land resume and marked
1966 /// [`Task::urgent`], and the resume's own "must not queue behind
1967 /// anything" guarantee takes precedence.
1968 None,
1969 /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
1970 /// (never in addition to trying) the ordinary pool. This is what lets
1971 /// an urgent task dispatch while every ordinary slot is already checked
1972 /// out, and what stops a second urgent task from opening a third run: it
1973 /// waits on this same one-slot semaphore rather than falling through to
1974 /// the ordinary one.
1975 Urgent,
1976 /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
1977 /// above.
1978 Ordinary,
1979}
1980
1981/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
1982/// own boolean, already computed by the caller from [`land_resume_state`].
1983fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
1984 if priority {
1985 PermitKind::None
1986 } else if urgent {
1987 PermitKind::Urgent
1988 } else {
1989 PermitKind::Ordinary
1990 }
1991}
1992
1993/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1994/// teardown and cannot skip the teardown on an early return.
1995///
1996/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
1997/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
1998/// land approval that has since been answered is dispatched outside that
1999/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
2000/// the whole point of parking there is that it must not queue behind
2001/// whatever else the loop happens to be running, even at the default of one.
2002/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
2003/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
2004/// these exemptions is still subject to the interrupt gate below, urgent
2005/// included: a land-resume or urgent candidate is exactly as much "something
2006/// else running" as an ordinary one from the interrupt sequence's point of
2007/// view, and letting either slip through while a run is being parked, or
2008/// while the interrupt task itself has the floor, is precisely the second
2009/// run 75dd's own "at most one run, ever, at once" guarantee must never
2010/// allow - see [`Interrupt`]'s own doc.
2011async fn poll(
2012 opts: &Opts,
2013 queue: &Queue,
2014 status: &Arc<Mutex<Status>>,
2015 home: &Path,
2016 worktrees_root: &Path,
2017 stop: &Stop,
2018 limits: DispatchLimits,
2019) -> Result<()> {
2020 let DispatchLimits {
2021 max_concurrent,
2022 pause_for_interrupts,
2023 } = limits;
2024 // Only consulted by `once`, where a task that just failed is still
2025 // `runnable` and would otherwise be picked up again inside the same drain.
2026 // In the long-running mode a later poll retrying a failed task is the point,
2027 // and the attempt counter is what bounds it.
2028 let mut attempted: Vec<String> = Vec::new();
2029 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
2030 // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
2031 // entirely separate from `sem`: an urgent candidate must dispatch
2032 // alongside whatever `sem` already has checked out, never by waiting for
2033 // one of those ordinary slots to free up and never by growing
2034 // `max_concurrent_runs` itself. Sized at one, not unbounded - see
2035 // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
2036 // first on this same slot rather than opening a third run.
2037 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
2038 // A quota hit is a fact about the machine, not the task that happened to
2039 // surface it, and every other *ordinary* candidate is no less likely to
2040 // hit the same wall - see the warning below. A land-merge resume is
2041 // exempt: it is a human decision finishing, not a fresh competition, and
2042 // must not sit out a quota cooldown it did not cause.
2043 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
2044 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
2045 let mut conductor = Conductor::new();
2046 // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
2047 // a congested queue would otherwise starve of the fully-idle branch below.
2048 let mut cache_last_checked: Option<Timestamp> = None;
2049 // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
2050 let mut interrupt = Interrupt::Idle;
2051 // The `Pause` handed to each dispatched candidate's own `Runner` - see
2052 // `attempt`'s new parameter - kept here so the tick that decides to park
2053 // a run for an interrupt can reach that specific run's handle and no
2054 // other's. Pruned to whatever is still in flight at the top of every
2055 // tick, so a finished attempt's handle does not linger.
2056 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
2057 std::collections::HashMap::new();
2058
2059 while !stop.stopped() {
2060 lock(status).polls += 1;
2061
2062 // Reap whatever finished since the last tick without blocking on
2063 // anything still running. `InFlightGuard` already released the slot
2064 // even if the spawned attempt panicked; this only surfaces that it
2065 // happened, since a panic swallowed here otherwise leaves no trace.
2066 while let Some(result) = inflight.try_join_next() {
2067 if let Err(e) = result {
2068 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2069 notices::raise(Notice::error(
2070 "loop:attempt",
2071 "A queued attempt ended abnormally; check the task it was running.",
2072 ));
2073 }
2074 }
2075
2076 let swept = sweep_stale_claims(queue, STALE_CLAIM);
2077 if !swept.is_empty() {
2078 tracing::warn!(
2079 "swept {} stale claim(s) left behind by an earlier daemon: {}",
2080 swept.len(),
2081 swept.join(", ")
2082 );
2083 }
2084 // Capture stalled work before reclaiming it. A dead daemon's ordinary
2085 // lock is swept and reclaimed in this same poll, but the conductor
2086 // must still see that it was stranded rather than only its mechanical
2087 // terminal state.
2088 let now = Timestamp::now();
2089
2090 // No run this daemon spawned is mid-compile right now, whether or
2091 // not another candidate is about to start - see
2092 // `maybe_prune_cache_between_runs`'s own doc for why this cannot
2093 // wait for the queue to run dry.
2094 if !stop.busy_now() {
2095 maybe_prune_cache_between_runs(
2096 &opts.repo,
2097 opts,
2098 home,
2099 stop,
2100 &mut cache_last_checked,
2101 now,
2102 )
2103 .await;
2104 }
2105
2106 let stalled = stalled_tasks(queue, home, now);
2107 let stalled_ids: std::collections::BTreeSet<_> =
2108 stalled.iter().map(|task| task.id.clone()).collect();
2109 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
2110 if !reclaimed.is_empty() {
2111 tracing::warn!(
2112 "reclaimed {} task(s) left `running` by a daemon that never \
2113 recorded the outcome: {}",
2114 reclaimed.len(),
2115 reclaimed.join(", ")
2116 );
2117 }
2118 let abandoned_runs = reclaim_abandoned_runs(home, now);
2119 if !abandoned_runs.is_empty() {
2120 tracing::warn!(
2121 "failed {} run(s) left behind by a killed process, past every \
2122 active seat's own timeout: {}",
2123 abandoned_runs.len(),
2124 abandoned_runs.join(", ")
2125 );
2126 }
2127
2128 // `home`, not `ask::Questions::open()`'s own process-global default:
2129 // `poll` is handed its home explicitly precisely so a test can point
2130 // it elsewhere, the same reason `Queue::at` and the status file path
2131 // are parameters rather than resolved here - see `drive`'s own doc.
2132 let questions = Questions::at(home.join("questions"));
2133
2134 // Deterministic: no model, run before the conductor sees anything so
2135 // its input reflects the queue's current, already-resolved state.
2136 resolve_blockers(queue, &questions);
2137 apply_choice_actions(queue, &questions, home);
2138 reconcile_task_questions(queue, &questions);
2139
2140 // The conductor gets one look per cycle, right before the loop takes
2141 // its next task, and only when there is something new to look at -
2142 // see `Conductor::worth_a_look`'s own doc for why "stalled is
2143 // non-empty" is the wrong test. Checked before `prepare` so an
2144 // unchanged cycle never pays for a synchronous config load.
2145 let finished: Vec<Task> = finished_tasks(queue)
2146 .into_iter()
2147 .filter(|task| !stalled_ids.contains(&task.id))
2148 // A parked run is waiting for this loop, not for a decision: the
2149 // conductor must not get to hold it or requeue it (a requeue
2150 // sets `fresh_start` and re-competes) before `attempt` resumes.
2151 .filter(|task| !awaiting_resume_with(task, |id| RunState::load_under(id, home)))
2152 .collect();
2153 let queued = queued_tasks(queue);
2154 // An empty queue has nothing to arrange. In particular, do not let
2155 // the conductor's initial snapshot cause synchronous config I/O
2156 // between the caller's stop notification and the idle wait below.
2157 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
2158 && conductor.worth_a_look(queue, &stalled, &finished)
2159 {
2160 match prepare(&opts.repo, opts) {
2161 Ok(cfg) => {
2162 conductor
2163 .maybe_run(
2164 &cfg,
2165 &opts.repo,
2166 queue,
2167 &questions,
2168 home,
2169 &queued,
2170 &stalled,
2171 &finished,
2172 opts.max_attempts,
2173 )
2174 .await;
2175 }
2176 Err(e) => {
2177 tracing::warn!("conductor: no config: {e:#}");
2178 notices::raise(Notice::warn(
2179 "loop:no-config",
2180 "The loop could not read this repository's config, so held tasks are not being triaged.",
2181 ));
2182 }
2183 }
2184 }
2185
2186 let candidates: Vec<Task> = runnable(queue)
2187 .into_iter()
2188 .filter(|t| !opts.once || !attempted.contains(&t.id))
2189 .collect();
2190
2191 // A task id only stays a key here while its attempt is genuinely in
2192 // flight; `status.current` is the same liveness fact `InFlightGuard`
2193 // maintains for the phone's own status file, so this piggybacks on
2194 // it rather than tracking a second copy of the same thing.
2195 let in_flight: Vec<String> = lock(status)
2196 .current
2197 .iter()
2198 .map(|c| c.task.clone())
2199 .collect();
2200 interrupt_pauses.retain(|id, _| in_flight.contains(id));
2201
2202 interrupt =
2203 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
2204 if let Interrupt::Parking {
2205 parked,
2206 interrupt_task,
2207 } = &interrupt
2208 {
2209 let reason = format!(
2210 "task {} asked to run first",
2211 crate::run::short_of(interrupt_task)
2212 );
2213 for id in parked {
2214 if let Some(pause) = interrupt_pauses.get(id) {
2215 pause.park_because(reason.clone());
2216 }
2217 }
2218 }
2219 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
2220
2221 let cooling_down =
2222 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
2223
2224 let mut started_any = false;
2225 for candidate in candidates {
2226 if stop.stopped() {
2227 break;
2228 }
2229
2230 let resume = land_resume_state(&candidate);
2231 if resume == LandResume::StillWaiting {
2232 continue;
2233 }
2234 let priority = resume == LandResume::Ready;
2235
2236 if !priority && cooling_down {
2237 continue;
2238 }
2239 let permit = match permit_kind(priority, candidate.urgent) {
2240 PermitKind::None => None,
2241 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
2242 Ok(p) => Some(p),
2243 // The one urgent slot is already spoken for by another
2244 // `--urgent` task's run. Keep looking rather than falling
2245 // back to the ordinary pool - see `PermitKind::Urgent`'s
2246 // own doc - a later candidate might still be an ordinary
2247 // task with a free slot, or another priority resume.
2248 Err(_) => continue,
2249 },
2250 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
2251 Ok(p) => Some(p),
2252 // No ordinary slot free right now. A later candidate in
2253 // this same list might still be a priority resume or an
2254 // urgent task, so keep looking rather than stopping here.
2255 Err(_) => continue,
2256 },
2257 };
2258
2259 // A claim we cannot take means another daemon, or a human running
2260 // `magi run`, got there first. That is not the task's fault and
2261 // must not spend one of its attempts: move to the next candidate
2262 // rather than recording a failure.
2263 let Ok(claim) = queue.claim(&candidate.id) else {
2264 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
2265 continue;
2266 };
2267 // Re-read under the claim: the task on disk may have been held or
2268 // edited between the listing and the lock.
2269 let mut task = match queue.get(&candidate.id) {
2270 Ok(t) if t.status.runnable() => t,
2271 Ok(_) => continue,
2272 Err(e) => {
2273 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
2274 continue;
2275 }
2276 };
2277 let task_id = task.id.clone();
2278 attempted.push(task_id.clone());
2279 lock(status).idle = false;
2280 // A stop asked for from here on is "finishing", not "stopped": the
2281 // run gets to reach a terminal status before the loop returns.
2282 stop.enter();
2283 started_any = true;
2284
2285 // A fresh, unshared handle - never `stop.pause()` - so parking
2286 // this run for an interrupt cannot leak into any other run this
2287 // loop ever drives. See `Pause`'s own doc.
2288 let run_pause = crate::graph::Pause::new();
2289 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
2290
2291 let opts = opts.clone();
2292 let queue = queue.clone();
2293 let status = Arc::clone(status);
2294 let stop = stop.clone();
2295 let quota_cooldown_until = Arc::clone("a_cooldown_until);
2296 inflight.spawn(async move {
2297 // Held for the whole attempt: dropping either at the end of
2298 // this task is what releases the claim and, for an ordinary
2299 // candidate, frees its concurrency slot back to the loop.
2300 let _claim = claim;
2301 let _permit = permit;
2302 // See `InFlightGuard`: this must survive a panic inside `attempt`.
2303 let _inflight = InFlightGuard {
2304 status: &status,
2305 stop: &stop,
2306 task_id: &task_id,
2307 };
2308 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
2309 lock(&status).completed += 1;
2310 // A quota loss is a fact about the machine, not this task, and
2311 // the next ordinary candidate the loop offers is no less
2312 // likely to hit the same wall: without a cooldown here a
2313 // whole backlog can be run - and failed - in the seconds it
2314 // takes each attempt to notice the CLI is out of quota.
2315 let now = Timestamp::now();
2316 if let Some(until) = cooldown_until("a, now) {
2317 let wait = until.as_second() - now.as_second();
2318 *lock("a_cooldown_until) = Some(until);
2319 let hint = quota
2320 .iter()
2321 .find(|q| q.reset.is_some())
2322 .and_then(|q| q.reset.as_deref());
2323 match hint {
2324 Some(h) => tracing::warn!(
2325 "quota hit; waiting {wait}s before taking another ordinary task \
2326 (CLI reported reset: {h})"
2327 ),
2328 None => tracing::warn!(
2329 "quota hit; waiting {wait}s before taking another ordinary task \
2330 (no reset hint reported)"
2331 ),
2332 }
2333 }
2334 });
2335 }
2336
2337 if started_any {
2338 continue;
2339 }
2340
2341 if stop.busy_now() {
2342 // Something started on an earlier tick is still running. Recheck
2343 // soon rather than sleeping out the whole poll interval - a freed
2344 // slot, or a land approval answered mid-run, must not sit idle
2345 // for it.
2346 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2347 continue;
2348 }
2349
2350 // Truly idle: nothing new to start and nothing still running.
2351 lock(status).idle = true;
2352 if opts.once {
2353 // A one-shot drain must perform the same post-work cleanup as a
2354 // daemon that reached a normal idle interval. The startup pass
2355 // cannot see runs or cache files produced by this drain.
2356 janitor(&opts.repo, opts, home, worktrees_root).await;
2357 resweep_superseded_attempts(queue, home);
2358 triage_held(queue, home, opts).await;
2359 break;
2360 }
2361 stop.idle(opts.poll).await;
2362 if stop.stopped() {
2363 continue;
2364 }
2365 // Housekeeping only after a full quiet interval. Running it before
2366 // the first idle wait can block the executor while an operator's
2367 // stop request is waiting to be scheduled, defeating Stop's retained
2368 // wake permit. No run can start while this branch is active, so the
2369 // janitor still never races an in-flight compile.
2370 janitor(&opts.repo, opts, home, worktrees_root).await;
2371 resweep_superseded_attempts(queue, home);
2372 triage_held(queue, home, opts).await;
2373 }
2374
2375 // Never return while a run is still in flight, whichever way the loop
2376 // above exited: a stop only sets a flag - see `serve_until` - and
2377 // returning here while `inflight` still holds spawned work would abandon
2378 // it exactly as a mid-node kill would.
2379 while let Some(result) = inflight.join_next().await {
2380 if let Err(e) = result {
2381 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2382 notices::raise(Notice::error(
2383 "loop:attempt",
2384 "A queued attempt ended abnormally; check the task it was running.",
2385 ));
2386 }
2387 }
2388 Ok(())
2389}
2390
2391/// Run one claimed task to a terminal status and record the outcome.
2392///
2393/// Every transition is flushed to the queue as it happens, so the state on disk
2394/// is what actually occurred rather than what this process still intends to
2395/// write.
2396async fn attempt(
2397 opts: &Opts,
2398 queue: &Queue,
2399 status: &Arc<Mutex<Status>>,
2400 stop: &Stop,
2401 interrupt_pause: crate::graph::Pause,
2402 task: &mut Task,
2403) -> Vec<QuotaLoss> {
2404 let repo = repo_for(task, &opts.repo);
2405 tracing::info!(
2406 "task {} — {} (repo {})",
2407 task.short(),
2408 task.title,
2409 repo.display()
2410 );
2411
2412 let mut config = match prepare(&repo, opts) {
2413 Ok(c) => c,
2414 Err(e) => {
2415 // A setup failure spends an attempt even though no run was minted.
2416 // Without that, a task naming a repository that does not exist
2417 // would be retried at every poll for as long as the daemon lives.
2418 task.attempts += 1;
2419 task.fail(format!("config: {e:#}"), opts.max_attempts);
2420 record(queue, task);
2421 return Vec::new();
2422 }
2423 };
2424 apply_solo(&mut config, task);
2425
2426 // The free-space gate, checked *before* anything is minted: a task that
2427 // waits out a full disk costs nothing yet, and must not spend an attempt
2428 // or start a run the machine cannot finish. Held tasks stay in the list
2429 // for the human to see, and `magi task release` re-queues them when space
2430 // comes back - the same recovery as any other hold. A volume whose free
2431 // space cannot be measured closes the gate too: starting a run blind on a
2432 // disk that may be full is how the machine ends up with 6.7 GB free.
2433 if let Some(reason) = disk_gate(&repo, &config) {
2434 task.last_error = Some(reason.clone());
2435 task.hold_machine(Some(reason.clone()));
2436 record(queue, task);
2437 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2438 // Stable wording - the free-space figures live in the task's hold
2439 // reason, and changing numbers would relight the bell every poll.
2440 notices::raise(
2441 Notice::warn(
2442 &format!("disk:{}", repo.display()),
2443 "A task was held for want of free disk space; free some, then release it from the queue.",
2444 )
2445 .link(Link::Task {
2446 id: task.id.clone(),
2447 }),
2448 );
2449 return Vec::new();
2450 }
2451
2452 // A resumable run of this task is carried on, never re-competed. The
2453 // candidates are built and paid for, and a fresh competition races a
2454 // second implementation against them.
2455 //
2456 // Two runs paid for that lesson. Run 01c2 was blocked and the loop
2457 // started 3cbf on the same task a moment later, duplicating two and a
2458 // half hours of agent work. Then b25f stalled on a judge that timed out
2459 // and one that answered with no JSON - `quota: 0`, so nothing the machine
2460 // was to blame for - and 4043 started **one second** later, buying three
2461 // fresh implementations to reach the same panel. `RunStatus::resumable`
2462 // rather than `!done()` is what catches the second case: a stall is
2463 // terminal, and its cheap recovery re-asks only the absent seats.
2464 //
2465 // A load failure is warned about rather than silently read as "not
2466 // resumable": the alternative is exactly what let a schema mismatch on
2467 // run `eba2` fall through to a full re-competition with nobody told why.
2468 // `crate::conduct` is what actually offers a better answer than
2469 // `Runner::start` here (see `Recovery::Review`), once this task's next
2470 // failure shows it up as `held`/`failed` with the run state unreadable.
2471 let unfinished = (!task.fresh_start)
2472 .then(|| unfinished_run(&task.runs, task.short()))
2473 .flatten();
2474 // `crate::conduct` chose `Review` for this task on an earlier cycle: its
2475 // branch survived, and this reopens exactly that branch as a
2476 // review-only pass rather than resuming or competing again. Consumed
2477 // (cleared) here whichever way this goes, so it never outlives this one
2478 // attempt - see `queue::Task::review_branch`.
2479 let review_branch = task.review_branch.take();
2480 let branch_exists = match &review_branch {
2481 Some(branch) => crate::git::branch_exists(&repo, branch)
2482 .await
2483 .unwrap_or(false),
2484 None => false,
2485 };
2486 let starter = choose_starter(
2487 review_branch.as_deref(),
2488 branch_exists,
2489 unfinished.as_deref(),
2490 );
2491 let started = match &starter {
2492 Starter::Review(branch) => {
2493 tracing::info!(
2494 "task {} reopens `{branch}` as a review-only pass",
2495 task.short()
2496 );
2497 // Every earlier attempt is superseded by the one being minted
2498 // now, so a branch one of them still holds may be taken over.
2499 let takeover = crate::handover::Takeover {
2500 earlier: task.earlier_attempts().to_vec(),
2501 home: crate::run::home(),
2502 choice: take_divergence_answer(branch, &config.merge.remote, task),
2503 };
2504 Runner::review_taking_over(&repo, branch, config, Some(takeover)).await
2505 }
2506 Starter::Resume(id) => {
2507 tracing::info!("resuming run {id} rather than competing again");
2508 Runner::resume(id).map(|mut r| {
2509 if let Some(instruction) =
2510 prepare_instruction(&starter, Some(&r.state.instruction), task)
2511 {
2512 r.state.instruction = instruction;
2513 }
2514 r
2515 })
2516 }
2517 Starter::Start => {
2518 if let Some(branch) = &review_branch {
2519 tracing::warn!(
2520 "conductor chose review for task {} but branch `{branch}` no longer \
2521 exists; requeuing as a fresh competition instead",
2522 task.short()
2523 );
2524 }
2525 let instruction = prepare_instruction(&starter, None, task)
2526 .unwrap_or_else(|| task.instruction.clone());
2527 Runner::start(&repo, instruction, config).await
2528 }
2529 };
2530 let mut runner = match started {
2531 Ok(r) => r,
2532 // A branch an earlier attempt still holds and magi will not release
2533 // by itself is the operator's call, not a failed attempt: hold the
2534 // task with the reason, spend nothing, and say so on the bell.
2535 Err(e) if e.downcast_ref::<crate::handover::Refused>().is_some() => {
2536 let reason = format!("could not start the run: {e:#}");
2537 task.last_error = Some(reason.clone());
2538 task.hold_machine(Some(reason));
2539 record(queue, task);
2540 tracing::warn!(
2541 "holding {} for a branch it cannot take over: {e:#}",
2542 task.short()
2543 );
2544 // Stable wording; the specifics live in the task's hold reason.
2545 notices::raise(
2546 Notice::warn(
2547 &format!("handover:{}", task.id),
2548 "A task was held because an earlier attempt still has its branch checked out; see the task's hold reason, then release it from the queue.",
2549 )
2550 .link(Link::Task {
2551 id: task.id.clone(),
2552 }),
2553 );
2554 return Vec::new();
2555 }
2556 // A branch that differs between here and the remote in ways magi
2557 // cannot prove are the same change is a decision for the owner, not a
2558 // failed attempt: ask with both sides laid out, spend no attempt, and
2559 // let the answer requeue the task.
2560 Err(e) if e.downcast_ref::<crate::reconcile::Diverged>().is_some() => {
2561 let d = e
2562 .downcast_ref::<crate::reconcile::Diverged>()
2563 .expect("checked by the guard");
2564 let mut q = ask::Question::new(
2565 task.id.clone(),
2566 "review".to_owned(),
2567 "sync".to_owned(),
2568 d.summary(),
2569 d.detail(),
2570 d.choices(),
2571 );
2572 match Questions::open().put(&mut q) {
2573 Ok(()) => {
2574 task.last_error = Some(format!("{e:#}"));
2575 // Consumed above by `take`; the answer has to reach a review
2576 // of this same branch, so keep pointing the task at it.
2577 task.review_branch = Some(d.branch.clone());
2578 task.block(vec![q.id.clone()], Some(d.summary()));
2579 }
2580 Err(put) => {
2581 tracing::warn!("could not file the divergence question: {put:#}");
2582 task.attempts += 1;
2583 task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2584 }
2585 }
2586 record(queue, task);
2587 return Vec::new();
2588 }
2589 Err(e) => {
2590 // The answer was stale and nothing was applied: keep pointing at
2591 // the branch so the next attempt asks again against its new tips.
2592 // Nothing went wrong with the task, so no attempt is spent: a
2593 // budget one short of its limit must not hold it instead of
2594 // letting the question be asked again.
2595 if e.downcast_ref::<crate::reconcile::Stale>().is_some()
2596 && let Starter::Review(branch) = &starter
2597 {
2598 task.review_branch = Some(branch.clone());
2599 task.last_error = Some(format!("could not start the run: {e:#}"));
2600 task.status = crate::queue::TaskStatus::Failed;
2601 record(queue, task);
2602 return Vec::new();
2603 }
2604 task.attempts += 1;
2605 task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2606 record(queue, task);
2607 return Vec::new();
2608 }
2609 };
2610 // A stop that means "park" reaches the graph through this handle.
2611 runner.on_pause(stop.pause());
2612 // `poll`'s interrupt scheduler reaches this one run - and no other -
2613 // through this handle. See `Pause`'s own doc for why these are never
2614 // the same one.
2615 runner.watch_interrupt(interrupt_pause);
2616
2617 // `start` has minted the run, so the task can now point at it. Persisting
2618 // `Running` before `execute` is what makes a crash mid-run legible.
2619 let run = runner.state.id.clone();
2620 task.start(run.clone());
2621 record(queue, task);
2622 lock(status).current.push(Current {
2623 task: task.id.clone(),
2624 run,
2625 });
2626
2627 // `RunState::quota` is the run's whole history across every resume, so
2628 // only what this execution added may arm the cooldown or earn a refund.
2629 let quota_before = runner.state.quota.clone();
2630 let detail = match runner.execute().await {
2631 Ok(()) => describe(&runner.state),
2632 Err(e) => format!("{e:#}"),
2633 };
2634 let fresh = losses_this_attempt("a_before, &runner.state.quota);
2635 let verdict = Verdict {
2636 status: runner.state.status,
2637 // A run that opened a pull request handed its work over, whatever the
2638 // gate then decided about merging it.
2639 left_pr: runner.state.pr.is_some(),
2640 // Only a rate limit earns the task its attempt back - and only one
2641 // suffered now: a refund justified by a previous session's loss is
2642 // the same mistake as re-arming the cooldown from it. A stalled run
2643 // resumed without hitting quota again therefore spends its attempt,
2644 // like any other failure of the task's own.
2645 quota_hit: !fresh.is_empty(),
2646 // A run that parked was asked to stop; that is not a failure and must
2647 // not spend an attempt, or replacing the binary a few times would
2648 // exhaust a task's budget without an agent ever misbehaving.
2649 parked: runner.state.parked,
2650 // A quota loss that left nothing viable is the same machine fact as a
2651 // `Stalled` quota loss; see `settle`'s doc table.
2652 no_viable_candidates: runner.state.viable().is_empty(),
2653 };
2654 settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
2655 if task.status == TaskStatus::Done {
2656 supersede_prior_runs(task, &crate::run::home());
2657 }
2658 record(queue, task);
2659 tracing::info!(
2660 "task {} is {} after run {} ({})",
2661 task.short(),
2662 task.status.as_str(),
2663 runner.state.short(),
2664 label(runner.state.status)
2665 );
2666 fresh
2667}
2668
2669/// The quota losses `after` holds that `before` did not: what one execution
2670/// suffered, as opposed to the run's history.
2671///
2672/// Compared by value rather than by length or position because
2673/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
2674/// the vector can shrink and shift under a resume. A retried seat that hits
2675/// quota again is a `push` with a new `at`, so it shows up as new here.
2676/// `reclaim` deliberately keeps reading the whole history: after a crash there
2677/// is no attempt boundary to diff against.
2678fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
2679 after
2680 .iter()
2681 .filter(|q| !before.contains(q))
2682 .cloned()
2683 .collect()
2684}
2685
2686/// When the loop-wide quota cooldown should end, given this attempt's losses;
2687/// `None` when there were none. Reset-hint parsing and the cap live here.
2688fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
2689 if quota.is_empty() {
2690 return None;
2691 }
2692 let with_hint = quota.iter().find(|q| q.reset.is_some());
2693 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
2694 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
2695 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
2696 Some(
2697 now.checked_add(jiff::SignedDuration::from_secs(secs))
2698 .unwrap_or(Timestamp::MAX),
2699 )
2700}
2701
2702/// Cut this attempt's candidate count to one when the task asked to run
2703/// alone.
2704///
2705/// Pure and separate from [`attempt`] so the one thing this feature changes -
2706/// which `candidates` a `solo` task's run is built with - can be asserted
2707/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
2708/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
2709/// value from the caller's own copy, so a repository's `magi.toml` on disk is
2710/// never touched - only the `Config` this one attempt hands to `Runner::start`.
2711fn apply_solo(config: &mut Config, task: &Task) {
2712 if task.solo {
2713 config.graph.candidates = 1;
2714 }
2715}
2716
2717/// Load the config for a task's repository, with the merge override applied.
2718fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
2719 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
2720 if let Some(mode) = &opts.merge {
2721 config.merge.mode = merge_mode(mode)?;
2722 }
2723 Ok(config)
2724}
2725
2726/// Prune the shared build cache back under its cap at a safe boundary
2727/// between runs, so a queue that never empties - and so never reaches
2728/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
2729/// does not leave the cache to grow unchecked for as long as the backlog
2730/// lasts.
2731///
2732/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
2733/// same liveness fact the idle branch's own janitor call rests on - no run
2734/// this daemon spawned is still mid-compile - so pruning here races nothing.
2735/// The caller must not call this while a run is in flight; there is no
2736/// second `busy_now()` check inside this function, on purpose, because there
2737/// is nothing left to check that `busy_now()` has not already answered.
2738///
2739/// A stop that has already been asked for *is* checked here, for a different
2740/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
2741/// synchronously before it decides anything, so the poll loop cannot get back
2742/// to its own `stopped()` test until that walk is over — and a loop already
2743/// on its way out must not make the operator wait out housekeeping it is
2744/// about to stop needing. This is the same call the idle branch makes when it
2745/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
2746/// it matters more here: `busy_now()` is false throughout, so
2747/// [`Stop::finishing`] would report a stop as already landed while the walk
2748/// still held the loop. Nothing is lost by skipping — the cap is a standing
2749/// policy, and the next daemon's startup pass measures the same cache.
2750///
2751/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
2752/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
2753/// and the next has not yet claimed a task, which can be every few
2754/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
2755/// more than the growth it is guarding against.
2756async fn maybe_prune_cache_between_runs(
2757 repo: &Path,
2758 opts: &Opts,
2759 home: &Path,
2760 stop: &Stop,
2761 last_checked: &mut Option<Timestamp>,
2762 now: Timestamp,
2763) {
2764 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
2765 return;
2766 }
2767 *last_checked = Some(now);
2768 let cfg = match prepare(repo, opts) {
2769 Ok(cfg) => cfg,
2770 Err(e) => {
2771 tracing::warn!("cache check: no config: {e:#}");
2772 return;
2773 }
2774 };
2775 match clean::prune_cache_if_over_limit(&cfg, home) {
2776 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
2777 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
2778 pruned.files,
2779 pruned.freed
2780 ),
2781 Ok(_) => {}
2782 Err(e) => {
2783 tracing::warn!("housekeep: prune cache: {e:#}");
2784 notices::raise_in(
2785 home,
2786 Notice::warn(
2787 "housekeep:cache",
2788 "Pruning the shared build cache failed; disk usage may keep growing.",
2789 ),
2790 );
2791 }
2792 }
2793}
2794
2795/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
2796/// now, given when it last did (if ever). Pure, so the cadence is asserted
2797/// directly rather than by waiting out real minutes in a test.
2798fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
2799 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
2800}
2801
2802/// The disk janitor, with its housekeeping logged rather than fatal.
2803///
2804/// Called only at the loop's idle points, for the reason the caller documents:
2805/// a prune racing a live compile would delete files mid-build. The config is
2806/// re-read on every call because the repository that just ran may not be the
2807/// daemon's own default, and the cache directory is a repository fact.
2808///
2809/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
2810/// and [`crate::run::default_worktree_root`] read here, for the same reason
2811/// [`drive`] takes its queue and status file rather than resolving them: a
2812/// test driving the loop must not reach through to the operator's real home
2813/// or worktree bay just because the janitor runs on every idle tick.
2814/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
2815/// to get wrong silently - a test's `home` was already isolated, but nothing
2816/// exercised the parameter next to it, so a real worktree bay stayed wired in
2817/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
2818/// it for real, every test in this file that drives the loop at all started
2819/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
2820async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
2821 let cfg = match prepare(repo, opts) {
2822 Ok(cfg) => cfg,
2823 Err(e) => {
2824 tracing::warn!("housekeep: no config: {e:#}");
2825 return;
2826 }
2827 };
2828 // A run's own worktree lives under `config.graph.worktree_root` when the
2829 // repository sets one - the same precedence `RunState::worktree_root`
2830 // uses - and `worktrees_root` only stands in for the *default* an
2831 // unconfigured repository resolves to (see this function's own
2832 // parameter, or the test fixture wiring one to a fake path). Housekeeping
2833 // that always swept the default regardless of this override would never
2834 // see, and so never reclaim, a single worktree for a repository that
2835 // relocated them elsewhere.
2836 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
2837 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
2838 // Reported whenever there is anything to say, not only when `folded > 0`:
2839 // the incident this exists to prevent was 90 of 93 runs skipped and 0
2840 // folded, on every single pass, for months - a report gated on `folded`
2841 // would have stayed silent through every one of them.
2842 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
2843 let mut extra = Vec::new();
2844 if out.unreadable > 0 {
2845 extra.push(format!("{} unreadable", out.unreadable));
2846 }
2847 if out.orphaned_worktrees > 0 {
2848 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
2849 }
2850 let detail = if extra.is_empty() {
2851 String::new()
2852 } else {
2853 format!(" ({})", extra.join(", "))
2854 };
2855 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
2856 }
2857 if out.external_merges_recorded > 0 {
2858 tracing::info!(
2859 "housekeep: recorded {} run(s) as merged externally",
2860 out.external_merges_recorded
2861 );
2862 }
2863 if out.cache_files > 0 {
2864 tracing::info!(
2865 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
2866 out.cache_files,
2867 out.cache_freed
2868 );
2869 }
2870 if out.questions_abandoned > 0 {
2871 tracing::info!(
2872 "housekeep: abandoned {} question(s) left open by a finished run",
2873 out.questions_abandoned
2874 );
2875 }
2876}
2877
2878/// Run [`triage::run_once`] and log whatever it did, the same "only when
2879/// there is something to say" rule [`janitor`] follows for its own report.
2880///
2881/// Called at the same idle points as [`janitor`] - once per full poll
2882/// interval, never mid-attempt - for the same reason: it is not liveness
2883/// critical, and a task's own `hold_reason` string is the one thing this
2884/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
2885/// tick for no benefit.
2886async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
2887 let questions = Questions::at(home.join("questions"));
2888 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
2889 if report.is_empty() {
2890 return;
2891 }
2892 if !report.quarantined.is_empty() {
2893 tracing::info!(
2894 "triage: held {} blocked task(s) whose blocked-on task or \
2895 question no longer exists: {}",
2896 report.quarantined.len(),
2897 report.quarantined.join(", ")
2898 );
2899 }
2900 if !report.resumed.is_empty() {
2901 tracing::info!(
2902 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
2903 report.resumed.len(),
2904 report.resumed.join(", ")
2905 );
2906 }
2907 if !report.asked.is_empty() {
2908 tracing::info!(
2909 "triage: asked about {} held task(s): {}",
2910 report.asked.len(),
2911 report.asked.join(", ")
2912 );
2913 }
2914 if !report.answered.is_empty() {
2915 tracing::info!(
2916 "triage: applied {} operator answer(s): {}",
2917 report.answered.len(),
2918 report.answered.join(", ")
2919 );
2920 }
2921}
2922
2923/// The free-space gate: what stands between this task and a new run, if
2924/// anything. `Some(reason)` holds the task; `None` lets it start.
2925///
2926/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
2927/// the operator opted out. A measurement failure is a gate, not a pass: both
2928/// sides of "cannot tell" are served by not starting.
2929fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
2930 disk_gate_with(repo, config, crate::disk::free_bytes)
2931}
2932
2933/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
2934/// test can assert the exact wiring `attempt` runs - config's threshold in,
2935/// task-holding reason out - without asking the real machine's disk anything.
2936fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
2937 repo: &Path,
2938 config: &Config,
2939 free_bytes: F,
2940) -> Option<String> {
2941 let min = config.disk.min_free_bytes;
2942 if min == 0 {
2943 return None;
2944 }
2945 match free_bytes(repo) {
2946 Ok(free) => crate::disk::gate(free, min),
2947 Err(e) => Some(format!(
2948 "could not measure free space on {} ({e}); the disk gate refuses \
2949 to let a run start blind",
2950 repo.display()
2951 )),
2952 }
2953}
2954
2955/// How long to wait before offering another task when a run lost a seat to a
2956/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
2957/// could read, or carried nothing at all. Long enough that a quota outage
2958/// cannot burn through a whole backlog in the few seconds each doomed attempt
2959/// takes to fail; short enough that a quota which clears early is not left
2960/// idle for the fallback's sake.
2961const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
2962
2963/// Longest a parsed reset hint may push the wait out to. The hint comes from
2964/// the CLI's own words, not a contract, so a parsing slip that lands a day
2965/// away must not leave the loop asleep for a day.
2966const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
2967
2968/// How long [`poll`] should wait before offering the next task, after a run
2969/// lost at least one seat to a rate limit.
2970///
2971/// Pure and separate from the loop so the policy can be exercised without a
2972/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
2973/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
2974/// nothing to parse, or the parsed time has already passed; `cap` bounds how
2975/// far a parsed hint is trusted to push the wait out.
2976fn quota_wait(
2977 reset_at: Option<Timestamp>,
2978 now: Timestamp,
2979 fallback: Duration,
2980 cap: Duration,
2981) -> Duration {
2982 match reset_at {
2983 Some(at) if at > now => {
2984 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
2985 Duration::from_secs(secs).min(cap)
2986 }
2987 _ => fallback,
2988 }
2989}
2990
2991/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
2992///
2993/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
2994/// explains why parsing it exactly "would be a bug factory" — so this only
2995/// recognises the shapes actually observed in the wild, and returns `None`
2996/// for anything else rather than guess at a format nobody has seen.
2997///
2998/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
2999/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
3000/// said it, not from whenever this loop happens to read it: anchoring on `now`
3001/// would push the reset later on every read and would read an already-elapsed
3002/// reset as still in the future. (A long hint is still clamped by
3003/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
3004fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
3005 parse_reset_hint_zoned(text, now)
3006 .or_else(|| parse_reset_hint_dated(text))
3007 .or_else(|| parse_reset_hint_relative(text, recorded))
3008}
3009
3010/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
3011/// optional but at least one required, in that order. A bare number or any
3012/// unknown unit is refused.
3013fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
3014 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
3015 let mut rest = rest.trim();
3016 if rest.is_empty() {
3017 return None;
3018 }
3019 let mut total: i64 = 0;
3020 let mut matched = false;
3021 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
3022 if let Some((digits, tail)) = rest.split_once(unit)
3023 && !digits.is_empty()
3024 && digits.bytes().all(|b| b.is_ascii_digit())
3025 {
3026 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
3027 rest = tail;
3028 matched = true;
3029 }
3030 }
3031 if !rest.is_empty() || !matched {
3032 return None;
3033 }
3034 recorded
3035 .checked_add(jiff::SignedDuration::from_secs(total))
3036 .ok()
3037}
3038
3039/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
3040/// case-insensitive) into a 24-hour hour and minute. Shared by every
3041/// reset-hint shape below.
3042fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
3043 let clock = clock.trim().to_lowercase();
3044 let (digits, pm) = clock
3045 .strip_suffix("am")
3046 .map(|d| (d, false))
3047 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
3048 let (h, m) = digits.trim().split_once(':')?;
3049 let mut hour: i8 = h.trim().parse().ok()?;
3050 let minute: i8 = m.trim().parse().ok()?;
3051 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
3052 return None;
3053 }
3054 if pm && hour != 12 {
3055 hour += 12;
3056 } else if !pm && hour == 12 {
3057 hour = 0;
3058 }
3059 Some((hour, minute))
3060}
3061
3062/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
3063/// and a zone, never a date. A clock reading already past today is read as
3064/// tomorrow's: a CLI naming a same-day reset that has already gone by means
3065/// the window rolled over while nothing was watching.
3066fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
3067 let open = text.find('(')?;
3068 let close = text.rfind(')')?;
3069 if close <= open {
3070 return None;
3071 }
3072 let zone = text[open + 1..close].trim();
3073 let (hour, minute) = parse_12h_clock(&text[..open])?;
3074 let tz = jiff::tz::TimeZone::get(zone).ok()?;
3075 let candidate = now
3076 .to_zoned(tz)
3077 .with()
3078 .hour(hour)
3079 .minute(minute)
3080 .second(0)
3081 .millisecond(0)
3082 .microsecond(0)
3083 .nanosecond(0)
3084 .build()
3085 .ok()?;
3086 let mut at = candidate.timestamp();
3087 if at <= now {
3088 at += jiff::SignedDuration::from_hours(24);
3089 }
3090 Some(at)
3091}
3092
3093/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
3094/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
3095/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
3096/// "already past today" correction to make: the year already disambiguates
3097/// it. Scanned as a five-word window so it can be pulled out of the middle
3098/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
3099/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
3100/// any other timestamp with no zone attached.
3101fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
3102 let words: Vec<&str> = text.split_whitespace().collect();
3103 if words.len() < 5 {
3104 return None;
3105 }
3106 (0..=words.len() - 5)
3107 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
3108}
3109
3110/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
3111/// parenthesis right after the window is refused rather than ignored — it
3112/// reads as an explicit zone annotation on a shape that otherwise carries
3113/// none, and guessing UTC anyway would be exactly the silent misread this
3114/// module's parsing otherwise avoids.
3115fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
3116 if trailing.is_some_and(|next| next.starts_with('(')) {
3117 return None;
3118 }
3119 let month = month_number(window[0])?;
3120 let day_token = window[1].strip_suffix(',')?.to_lowercase();
3121 let day_digits = ["st", "nd", "rd", "th"]
3122 .iter()
3123 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
3124 let day: i8 = day_digits.parse().ok()?;
3125 let year_token = window[2];
3126 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
3127 return None;
3128 }
3129 let year: i16 = year_token.parse().ok()?;
3130 // The am/pm word carries the sentence's own trailing punctuation, e.g.
3131 // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
3132 // reusing the same 12-hour clock reader the bracketed shape uses.
3133 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
3134 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
3135 let date = jiff::civil::Date::new(year, month, day).ok()?;
3136 let candidate = date
3137 .at(hour, minute, 0, 0)
3138 .to_zoned(jiff::tz::TimeZone::UTC)
3139 .ok()?;
3140 Some(candidate.timestamp())
3141}
3142
3143/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
3144/// case-insensitively, into a 1-based month number.
3145fn month_number(name: &str) -> Option<i8> {
3146 const NAMES: [&str; 12] = [
3147 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
3148 ];
3149 let lower = name.to_lowercase();
3150 NAMES
3151 .iter()
3152 .position(|n| *n == lower.as_str())
3153 .map(|i| i as i8 + 1)
3154}
3155
3156/// Resuming a `Blocked` run that already spent every review round its own
3157/// config allowed cannot make progress: `graph::Runner`'s review loop walks
3158/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
3159/// reached `max_rounds`, so `execute` would settle straight back to
3160/// `Blocked` without asking anyone anything. Read-only against a state this
3161/// build never mutates — `src/graph.rs` stays untouched — but without this
3162/// check, [`unfinished_run`] would keep reporting such a run as still
3163/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
3164/// promise is a fresh competition when a design needs to change) would
3165/// silently resume the exhausted run instead, spending an attempt on a
3166/// cycle that cannot change anything.
3167fn exhausted_review_budget(state: &RunState) -> bool {
3168 state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
3169}
3170
3171/// This task's *most recent* run, if resuming it would actually make
3172/// progress. `short` is only for the warning's own message.
3173///
3174/// Only ever `runs.last()` — never a search back through older history.
3175/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
3176/// mint, oldest first, and every entry before the last one was already
3177/// superseded at the moment it was minted: the daemon only ever starts a new
3178/// run when the previous one was not worth resuming (unresumable, exhausted,
3179/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
3180/// opens a fresh review-only run alongside an older, already-failed
3181/// competition. Searching further back would let an old run that merely
3182/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
3183/// behind, say — get resumed instead of the fresh competition
3184/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
3185/// nothing asked to revisit.
3186///
3187/// Two runs paid for the "prefer resuming over restarting" half of this
3188/// lesson, which is why this still checks `runs.last()` rather than always
3189/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
3190/// task a moment later, duplicating two and a half hours of agent work. Then
3191/// b25f stalled on a judge that timed out and one that answered with no JSON
3192/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
3193/// **one second** later, buying three fresh implementations to reach the
3194/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
3195/// the second case: a stall is terminal, and its cheap recovery re-asks only
3196/// the absent seats. [`exhausted_review_budget`] is the other half: a run
3197/// that is technically `resumable()` but provably cannot progress must not
3198/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
3199/// no-op instead of the fresh competition it promises.
3200///
3201/// A load failure is warned about rather than silently read as "not
3202/// resumable": the alternative is exactly what let a schema mismatch on run
3203/// `eba2` fall through to a full re-competition with nobody told why.
3204/// `crate::conduct` is what actually offers a better answer than
3205/// `Runner::start` here (see `Recovery::Review`), once this task's next
3206/// failure shows it up as `held`/`failed` with the run state unreadable.
3207fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
3208 unfinished_run_with(runs, short, RunState::load)
3209}
3210
3211/// [`unfinished_run`] with an injected state reader. Tests provide their
3212/// fixtures directly rather than touching the process-global run home.
3213fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
3214where
3215 F: FnOnce(&str) -> Result<RunState>,
3216{
3217 let id = runs.last()?;
3218 match load(id) {
3219 Ok(s) if s.status.resumable() && !s.released() && !exhausted_review_budget(&s) => {
3220 Some(id.clone())
3221 }
3222 Ok(_) => None,
3223 Err(e) => {
3224 tracing::warn!("could not read run {id} for task {short}: {e:#}");
3225 None
3226 }
3227 }
3228}
3229
3230/// Is `task` a failed task whose last run was parked at a node boundary, so
3231/// that [`attempt`] will resume it on its own?
3232///
3233/// Mirrors [`unfinished_run_with`]'s own conditions (plus `parked`, and no
3234/// pending review choice, which [`choose_starter`] ranks first). Pure, with an
3235/// injected reader like its sibling. An unreadable run is not awaiting
3236/// anything: it keeps going to the conductor as before.
3237fn awaiting_resume_with<F>(task: &Task, load: F) -> bool
3238where
3239 F: FnOnce(&str) -> Result<RunState>,
3240{
3241 if task.status != TaskStatus::Failed || task.fresh_start || task.review_branch.is_some() {
3242 return false;
3243 }
3244 let Some(id) = task.runs.last() else {
3245 return false;
3246 };
3247 load(id).is_ok_and(|s| {
3248 s.parked && s.status.resumable() && !s.released() && !exhausted_review_budget(&s)
3249 })
3250}
3251
3252/// Which of the three ways [`attempt`] can mint or continue a run this task
3253/// should use.
3254#[derive(Debug, Clone, PartialEq, Eq)]
3255enum Starter {
3256 /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
3257 /// and that still exists.
3258 Review(String),
3259 /// `crate::graph::Runner::resume` on an unfinished run of this task.
3260 Resume(String),
3261 /// `crate::graph::Runner::start`: a fresh competition.
3262 Start,
3263}
3264
3265/// The owner's answer to this branch's divergence question, consumed from the
3266/// task so a later, different divergence asks again. The runner applies it
3267/// (see `Runner::review_taking_over`), after the earlier worktree is released.
3268fn take_divergence_answer(
3269 branch: &str,
3270 remote: &str,
3271 task: &mut Task,
3272) -> Option<crate::reconcile::Choice> {
3273 let summary = crate::reconcile::summary_for(branch, remote);
3274 let (idx, choice) = task.answers.iter().enumerate().rev().find_map(|(i, a)| {
3275 (a.question == summary)
3276 .then(|| crate::reconcile::Choice::from_answer(&a.answer))
3277 .flatten()
3278 .map(|c| (i, c))
3279 })?;
3280 task.answers.remove(idx);
3281 Some(choice)
3282}
3283
3284/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
3285/// this attempt should use. Pure, and separate from [`attempt`], so the
3286/// routing itself is assertable without spawning a real graph or a git
3287/// process: `attempt`'s own `crate::git::branch_exists` call has already
3288/// happened by the time this is called.
3289///
3290/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
3291/// whose branch is gone falls all the way through to [`Starter::Start`], not
3292/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
3293/// old (likely `Blocked`) run in the first place, and a branch that vanished
3294/// out from under that choice is not evidence resuming it would fare better.
3295fn choose_starter(
3296 review_branch: Option<&str>,
3297 branch_exists: bool,
3298 unfinished: Option<&str>,
3299) -> Starter {
3300 match review_branch {
3301 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
3302 Some(_) => Starter::Start,
3303 None => match unfinished {
3304 Some(id) => Starter::Resume(id.to_owned()),
3305 None => Starter::Start,
3306 },
3307 }
3308}
3309
3310/// Which repository a task runs in. A task that names none — the normal case
3311/// for one filed from a phone — runs in the daemon's own default.
3312fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
3313 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
3314 return fallback.to_path_buf();
3315 }
3316 task.repo.clone()
3317}
3318
3319/// The header [`append_answers`] appends operator answers under. Shared with
3320/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
3321/// rather than grown a new block on every resume.
3322const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
3323
3324/// Render the first `count` answers in the block appended to an instruction.
3325fn answers_block(task: &Task, count: usize) -> String {
3326 let mut s = ANSWERS_HEADER.to_owned();
3327 for a in &task.answers[..count] {
3328 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
3329 }
3330 s
3331}
3332
3333/// Append every answer `crate::conduct` has collected for `task` onto `base`,
3334/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
3335fn append_answers(base: &str, task: &Task) -> String {
3336 if task.answers.is_empty() {
3337 return base.to_owned();
3338 }
3339 let mut s = base.to_owned();
3340 s.push_str(&answers_block(task, task.answers.len()));
3341 s
3342}
3343
3344/// Drop the prior answer block only when it is exactly the suffix this task
3345/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
3346/// the task author is ordinary instruction text, not a block to remove.
3347fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
3348 for count in (1..=task.answers.len()).rev() {
3349 let block = answers_block(task, count);
3350 if let Some(base) = instruction.strip_suffix(&block) {
3351 return base;
3352 }
3353 }
3354 instruction
3355}
3356
3357/// The instruction handed to `Runner::start`: the task's own text, plus any
3358/// operator answers `crate::conduct` collected for it (see
3359/// [`Task::answers`]), so a decision the operator actually made reaches the
3360/// implementers rather than only clearing the block that was waiting on it.
3361///
3362/// Appended rather than merged into [`Task::instruction`] itself, so the
3363/// task's own record stays exactly what its author wrote.
3364fn instruction_for(task: &Task) -> String {
3365 append_answers(&task.instruction, task)
3366}
3367
3368/// The instruction a resumed run should carry on with: whatever it already
3369/// had, refreshed with the task's *current* operator answers.
3370///
3371/// A resumable run's own `RunState::instruction` predates any answer
3372/// `crate::conduct` collects after the run parks, so resuming it unchanged —
3373/// the behaviour before this function existed — silently drops the very
3374/// decision the operator made to unblock it. Re-stripping any block this
3375/// function appended on an earlier resume before re-appending the current
3376/// list (rather than blindly appending again) is what keeps a task resumed
3377/// three times over three answered questions from carrying the same answer
3378/// three times.
3379fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
3380 append_answers(strip_answers_block(old_instruction, task), task)
3381}
3382
3383/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
3384/// answers before handing it to `Runner` — the actual boundary between
3385/// [`choose_starter`]'s routing and the graph, factored out so it is
3386/// assertable without a real repository, git branch, or agent CLI.
3387///
3388/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
3389/// instruction from the reviewed branch's own commit log because there is no
3390/// task statement to speak of for hand-written work, and splicing operator
3391/// answers into that text would contradict the very message it sends
3392/// reviewers ("there is no task statement").
3393fn prepare_instruction(
3394 starter: &Starter,
3395 old_instruction: Option<&str>,
3396 task: &Task,
3397) -> Option<String> {
3398 match starter {
3399 Starter::Start => Some(instruction_for(task)),
3400 Starter::Resume(_) => Some(resumed_instruction(
3401 old_instruction.expect("a resumed run always has a prior instruction"),
3402 task,
3403 )),
3404 Starter::Review(_) => None,
3405 }
3406}
3407
3408/// Persist a transition. A queue write failure is logged rather than fatal: the
3409/// run already happened, and taking the daemon down would only add a lost
3410/// backlog to a full disk.
3411fn record(queue: &Queue, task: &mut Task) {
3412 if let Err(e) = queue.put(task) {
3413 tracing::error!("could not record task {}: {e:#}", task.short());
3414 notices::raise(Notice::error(
3415 "loop:record",
3416 "The loop could not save a task's state; check the disk.",
3417 ));
3418 }
3419}
3420
3421/// Every runnable task, in the order the loop should try them.
3422///
3423/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
3424/// tail exists so that a claim somebody else holds costs the loop the next
3425/// candidate rather than a whole poll interval of idleness.
3426fn runnable(queue: &Queue) -> Vec<Task> {
3427 let mut tasks: Vec<Task> = queue
3428 .list()
3429 .into_iter()
3430 .filter(|t| t.status.runnable())
3431 .collect();
3432 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
3433 tasks
3434}
3435
3436/// Why a run ended where it did, in one line, for [`Task::last_error`].
3437///
3438/// A stalled run names the seats the quota took out: "out of quota" is not
3439/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
3440/// agent to replace or which plan to top up.
3441///
3442/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
3443/// purpose: unlike `label`'s other callers (an internal log line, an
3444/// already-a-bug fallback message), this string becomes `Task::last_error`
3445/// verbatim, which the phone renders in the same alarm-styled box an
3446/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
3447/// `.err` styling. A bare `verified_noop` there would read exactly like the
3448/// failure this whole feature exists to tell apart from one.
3449fn describe(state: &RunState) -> String {
3450 let mut detail = if state.status == RunStatus::Stalled {
3451 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
3452 seats.sort_unstable();
3453 seats.dedup();
3454 if seats.is_empty() {
3455 "the judging panel lost its quorum".to_owned()
3456 } else {
3457 format!(
3458 "the judging panel lost its quorum; quota took out {}",
3459 seats.join(", ")
3460 )
3461 }
3462 } else {
3463 format!("run ended {}", state.status.display_label())
3464 };
3465 if let Some(last) = state.events.last() {
3466 detail.push_str(&format!(" ({}: {})", last.node, last.message));
3467 }
3468 detail.push_str(&format!(" [run {}]", state.id));
3469 detail
3470}
3471
3472/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
3473///
3474/// The task file lives in the backlog indefinitely; a diagnostic is an
3475/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
3476/// stay small regardless of how much a gate command or a candidate printed.
3477const DIAGNOSTIC_MAX: usize = 4_000;
3478
3479/// Tail kept from a single failing command's output inside a diagnostic.
3480/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
3481/// pointer for a human deciding whether to go read the full artifact by hand,
3482/// not a replacement for reading it.
3483const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
3484
3485/// Assemble a bounded diagnostic excerpt from a held task's own run, so
3486/// `magi task show` says more than the one-line reason in [`describe`].
3487///
3488/// The one-liner answers "where did the run stop"; this answers "what would a
3489/// human have found opening `artifacts/` by hand" — the point of the whole
3490/// feature is the case that one-liner actively misleads on: a run held as "no
3491/// candidate produced a change" can mean the implementer actually finished
3492/// the task (opened a PR, merged it, tagged a release) and only left a clean
3493/// local worktree behind, which reads as "nothing happened" unless someone
3494/// goes and reads what the agent actually said. `None` when the run carries
3495/// none of the three shapes this recognises — an ordinary run held for
3496/// something not diagnosable from `RunState` alone still explains itself
3497/// through `Task::last_error`.
3498fn diagnostic(state: &RunState) -> Option<String> {
3499 let mut parts: Vec<String> = Vec::new();
3500
3501 // Gate failure: which check(s), and the tail of what each printed.
3502 for o in state.gate.iter().filter(|o| !o.ok()) {
3503 parts.push(format!(
3504 "gate `{}` failed ({:?}):\n{}",
3505 o.command,
3506 o.code,
3507 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
3508 ));
3509 }
3510
3511 // The land loop gave up because the fixer declined while checks were
3512 // still red: the message already names them (see `land::run`).
3513 if let Some(last) = state
3514 .events
3515 .iter()
3516 .rev()
3517 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
3518 {
3519 parts.push(last.message.clone());
3520 }
3521
3522 // No viable candidate: every implementer's own final word, sanitized the
3523 // same way a judge would have read it, so a run that actually finished
3524 // the job does not read as an unexplained failure. A verified no-op is
3525 // called out ahead of its own summary and apart from an ordinary
3526 // failure's `why` — this is the one candidate shape whose diagnostic a
3527 // human is expected to actually judge, not just skim.
3528 if state.viable().is_empty() {
3529 for c in &state.candidates {
3530 if let Some(evidence) = &c.verified_noop {
3531 parts.push(format!(
3532 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
3533 c.label
3534 ));
3535 } else if !c.summary.trim().is_empty() {
3536 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
3537 } else if let Some(why) = &c.failed {
3538 parts.push(format!("candidate {}: {why}", c.label));
3539 }
3540 }
3541 }
3542
3543 if parts.is_empty() {
3544 return None;
3545 }
3546 // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
3547 // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
3548 // back slightly over. Leave it enough room to always land under the
3549 // limit.
3550 Some(crate::run::tail(
3551 &parts.join("\n\n"),
3552 DIAGNOSTIC_MAX.saturating_sub(100),
3553 ))
3554}
3555
3556/// Stable lower-case name for a run status, for an internal log line and the
3557/// "graph stopped without reaching a terminal status" bug message in
3558/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
3559/// doc for why that one reads [`RunStatus::display_label`] instead. One
3560/// definition of a status's name, on the type that owns it: this table used
3561/// to live here as a second copy, and a status renamed in one place would
3562/// have gone on reading correctly in the other.
3563fn label(status: RunStatus) -> &'static str {
3564 status.as_str()
3565}
3566
3567/// Parse a merge mode override.
3568fn merge_mode(mode: &str) -> Result<MergeMode> {
3569 match mode {
3570 "none" => Ok(MergeMode::None),
3571 "local" => Ok(MergeMode::Local),
3572 "pr" => Ok(MergeMode::Pr),
3573 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
3574 }
3575}
3576
3577/// Take the status lock, recovering from a poisoned one.
3578///
3579/// A panic elsewhere must not silently stop the heartbeat: the status is plain
3580/// data, and the worst a poisoned lock can hold is a stale timestamp.
3581fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
3582 mutex
3583 .lock()
3584 .unwrap_or_else(std::sync::PoisonError::into_inner)
3585}
3586
3587#[cfg(test)]
3588mod tests {
3589 use super::*;
3590 use crate::queue::{Source, TaskStatus};
3591 use crate::run::{Candidate, CommandOutcome};
3592 use pretty_assertions::assert_eq;
3593
3594 fn task() -> Task {
3595 Task::new(
3596 "add retries".to_owned(),
3597 "add retries".to_owned(),
3598 PathBuf::from("/repo"),
3599 Source::Human,
3600 )
3601 }
3602
3603 /// A runnable task marked to interrupt, with an id fixed for assertions
3604 /// rather than the random one [`Task::new`] mints.
3605 fn interrupt_task(id: &str) -> Task {
3606 let mut t = task();
3607 t.id = id.to_owned();
3608 t.interrupt = true;
3609 t
3610 }
3611
3612 /// An ordinary runnable task with an id fixed for assertions.
3613 fn task_with_id(id: &str) -> Task {
3614 let mut t = task();
3615 t.id = id.to_owned();
3616 t
3617 }
3618
3619 /// A runnable task marked `--urgent`, with an id fixed for assertions.
3620 fn urgent_task(id: &str) -> Task {
3621 let mut t = task();
3622 t.id = id.to_owned();
3623 t.urgent = true;
3624 t
3625 }
3626
3627 /// The land-resume exemption wins outright, whether or not the candidate
3628 /// also happens to be marked [`Task::urgent`]: a resume's own "must not
3629 /// queue behind anything" guarantee cannot be weaker just because the
3630 /// same task was also filed with `--urgent`.
3631 #[test]
3632 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
3633 assert_eq!(permit_kind(true, false), PermitKind::None);
3634 assert_eq!(permit_kind(true, true), PermitKind::None);
3635 }
3636
3637 /// The one property this whole feature exists for: `--urgent` draws from
3638 /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
3639 /// ordinary candidate draws from the ordinary pool exactly as before,
3640 /// untouched by the urgent slot's existence.
3641 #[test]
3642 fn permit_kind_separates_urgent_from_ordinary() {
3643 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
3644 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
3645 }
3646
3647 /// The exact wiring `attempt` runs before minting anything: a config's
3648 /// `min_free_bytes` in, a task-holding reason naming both numbers out.
3649 /// Free space is injected rather than asked of the real disk - the point
3650 /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
3651 /// is deterministic on every machine this test runs on, never dependent
3652 /// on how full the CI runner's own disk happens to be.
3653 #[test]
3654 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
3655 let cfg = Config::default();
3656 let repo = Path::new("/any/repo/path");
3657
3658 let reason =
3659 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
3660 assert!(reason.contains("1024"), "{reason}");
3661 assert!(
3662 reason.contains(&cfg.disk.min_free_bytes.to_string()),
3663 "{reason}"
3664 );
3665
3666 assert_eq!(
3667 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
3668 None,
3669 "exactly at the floor is open"
3670 );
3671 assert_eq!(
3672 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
3673 None,
3674 "comfortably above the floor is open"
3675 );
3676 }
3677
3678 #[test]
3679 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
3680 let mut cfg = Config::default();
3681 cfg.disk.min_free_bytes = 0;
3682 let repo = Path::new("/any/repo/path");
3683 assert_eq!(
3684 disk_gate_with(repo, &cfg, |_| Ok(0)),
3685 None,
3686 "a zero floor never measures at all"
3687 );
3688 }
3689
3690 #[test]
3691 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
3692 let cfg = Config::default();
3693 let repo = Path::new("/any/repo/path");
3694 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
3695 .expect("a measurement failure must close the gate, not open it");
3696 assert!(reason.contains("could not measure"), "{reason}");
3697 }
3698
3699 #[test]
3700 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
3701 let ordinary = task();
3702 let next = advance_interrupt(
3703 Interrupt::Idle,
3704 std::slice::from_ref(&ordinary.id),
3705 std::slice::from_ref(&ordinary),
3706 );
3707 assert_eq!(next, Interrupt::Idle);
3708 }
3709
3710 #[test]
3711 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
3712 // Nothing to interrupt - this is just an ordinary candidate, and the
3713 // loop's normal dispatch will pick it up like any other.
3714 let marked = interrupt_task("marked");
3715 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3716 assert_eq!(next, Interrupt::Idle);
3717 }
3718
3719 #[test]
3720 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
3721 let marked = interrupt_task("marked");
3722 let next = advance_interrupt(
3723 Interrupt::Idle,
3724 &["running".to_owned()],
3725 std::slice::from_ref(&marked),
3726 );
3727 assert_eq!(
3728 next,
3729 Interrupt::Parking {
3730 parked: vec!["running".to_owned()],
3731 interrupt_task: "marked".to_owned(),
3732 }
3733 );
3734 }
3735
3736 /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
3737 /// one run can be in flight when a task becomes runnable and marked.
3738 /// Parking all of them would mean `Resuming` later has more than one id
3739 /// to release back to ordinary dispatch, which cannot be made safe
3740 /// against that same setting's own extra concurrency slots letting two
3741 /// of them start together - see `advance_interrupt`'s own `Idle` branch.
3742 /// The simplification the task's own constraints ask for: do not begin
3743 /// a sequence at all until the herd settles back to exactly one.
3744 #[test]
3745 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
3746 let marked = interrupt_task("marked");
3747
3748 let two = advance_interrupt(
3749 Interrupt::Idle,
3750 &["a".to_owned(), "b".to_owned()],
3751 std::slice::from_ref(&marked),
3752 );
3753 assert_eq!(two, Interrupt::Idle);
3754
3755 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3756 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
3757 }
3758
3759 #[test]
3760 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
3761 let state = Interrupt::Parking {
3762 parked: vec!["running".to_owned()],
3763 interrupt_task: "marked".to_owned(),
3764 };
3765 // Still in flight: no change.
3766 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
3767 assert_eq!(still_going, state);
3768
3769 // Left flight, but the interrupt task has not been dispatched yet on
3770 // this tick - stays `Parking` so `interrupt_gate` can let it through,
3771 // as long as it is still runnable.
3772 let stopped_but_not_yet_dispatched =
3773 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
3774 assert_eq!(stopped_but_not_yet_dispatched, state);
3775
3776 // Left flight, and the interrupt task is now in flight itself.
3777 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
3778 assert_eq!(
3779 dispatched,
3780 Interrupt::Running {
3781 parked: vec!["running".to_owned()],
3782 interrupt_task: "marked".to_owned(),
3783 }
3784 );
3785 }
3786
3787 #[test]
3788 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
3789 let state = Interrupt::Running {
3790 parked: vec!["running".to_owned()],
3791 interrupt_task: "marked".to_owned(),
3792 };
3793 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
3794 assert_eq!(still_running, state);
3795
3796 // Whatever it ended as - merged, failed, held - is not this
3797 // function's concern: leaving flight is the only trigger, driven
3798 // straight off the same in-flight list `poll` already reaps. It does
3799 // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
3800 // why that would let an unrelated task start ahead of, or alongside,
3801 // the guaranteed resume.
3802 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
3803 assert_eq!(
3804 ended,
3805 Interrupt::Resuming {
3806 parked: vec!["running".to_owned()]
3807 }
3808 );
3809 }
3810
3811 #[test]
3812 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
3813 let state = Interrupt::Resuming {
3814 parked: vec!["running".to_owned()],
3815 };
3816 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
3817 assert_eq!(still_waiting, state);
3818
3819 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
3820 assert_eq!(dispatched, Interrupt::Idle);
3821 }
3822
3823 /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
3824 /// or otherwise moved on by an operator with no claim standing in the
3825 /// way - must not wedge the sequence (and so the whole loop's dispatch,
3826 /// via `interrupt_gate`) waiting forever for a dispatch that can never
3827 /// come. The parked run still gets its resume.
3828 #[test]
3829 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
3830 {
3831 let state = Interrupt::Parking {
3832 parked: vec!["running".to_owned()],
3833 interrupt_task: "marked".to_owned(),
3834 };
3835 // `marked` has been held/blocked/deleted since the sequence began:
3836 // it no longer appears in `runnable` at all.
3837 let next = advance_interrupt(state, &[], &[]);
3838 assert_eq!(
3839 next,
3840 Interrupt::Resuming {
3841 parked: vec!["running".to_owned()]
3842 },
3843 "abandoning the interrupt must not abandon the resume it owes"
3844 );
3845 }
3846
3847 /// The same abandonment, one step later: `Resuming` itself must not wait
3848 /// forever for a parked task that has since become unrunnable.
3849 #[test]
3850 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
3851 let state = Interrupt::Resuming {
3852 parked: vec!["running".to_owned()],
3853 };
3854 let next = advance_interrupt(state, &[], &[]);
3855 assert_eq!(
3856 next,
3857 Interrupt::Idle,
3858 "nothing is left to wait for; the loop must not stay wedged"
3859 );
3860 }
3861
3862 #[test]
3863 fn disabled_by_config_the_sequence_can_never_leave_idle() {
3864 let marked = interrupt_task("marked");
3865 let next = advance_interrupt_tick(
3866 false,
3867 Interrupt::Idle,
3868 &["running".to_owned()],
3869 std::slice::from_ref(&marked),
3870 );
3871 assert_eq!(
3872 next,
3873 Interrupt::Idle,
3874 "an unmarked, unconfigured daemon must behave exactly as before"
3875 );
3876 }
3877
3878 #[test]
3879 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
3880 let state = Interrupt::Parking {
3881 parked: vec!["running".to_owned()],
3882 interrupt_task: "marked".to_owned(),
3883 };
3884 let candidates = vec![interrupt_task("marked"), task()];
3885 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3886 assert!(
3887 allowed.is_empty(),
3888 "nothing may dispatch - not even the interrupt task itself - \
3889 until the parked run has actually stopped"
3890 );
3891 }
3892
3893 /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
3894 /// grow a special case for it: an urgent candidate that is not the
3895 /// interrupt task withholds exactly like an ordinary one for as long as
3896 /// the parked run it is racing has not actually left flight. A version
3897 /// of this feature once bypassed the gate for urgent candidates, on the
3898 /// theory that a genuinely separate concurrency lane could not collide
3899 /// with 75dd's own; it could, and did - the bypassed task dispatched
3900 /// alongside a run 75dd's own state machine had only *asked* to park,
3901 /// not yet confirmed gone, which is exactly the second run
3902 /// `Interrupt::Parking`'s own doc says must never happen. There is no
3903 /// tick during Parking/Running/Resuming where letting an extra
3904 /// candidate through is safe, urgent or not - the parked run may still
3905 /// be genuinely mid-call.
3906 #[test]
3907 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
3908 for state in [
3909 Interrupt::Parking {
3910 parked: vec!["running".to_owned()],
3911 interrupt_task: "marked".to_owned(),
3912 },
3913 Interrupt::Running {
3914 parked: vec!["running".to_owned()],
3915 interrupt_task: "marked".to_owned(),
3916 },
3917 Interrupt::Resuming {
3918 parked: vec!["running".to_owned()],
3919 },
3920 ] {
3921 let candidates = vec![
3922 interrupt_task("marked"),
3923 urgent_task("hot"),
3924 task_with_id("ordinary"),
3925 ];
3926 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3927 assert!(
3928 !allowed.iter().any(|t| t.id == "hot"),
3929 "an urgent candidate must wait out the same gate as anything \
3930 else while the run it would run alongside has not actually \
3931 left flight, for state {state:?}: {allowed:?}"
3932 );
3933 }
3934 }
3935
3936 /// The one case where marking a task `--urgent` and `interrupt` at once
3937 /// is not redundant: once the interrupt sequence's own guaranteed
3938 /// resume/dispatch actually admits the task, it is unaffected by also
3939 /// carrying `urgent` - `interrupt_gate` decides purely on identity,
3940 /// never on the urgent flag.
3941 #[test]
3942 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
3943 let state = Interrupt::Resuming {
3944 parked: vec!["hot".to_owned()],
3945 };
3946 let candidates = vec![urgent_task("hot"), task()];
3947 let allowed = interrupt_gate(&state, &[], candidates);
3948 assert_eq!(
3949 allowed.iter().filter(|t| t.id == "hot").count(),
3950 1,
3951 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
3952 );
3953 }
3954
3955 #[test]
3956 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
3957 let state = Interrupt::Parking {
3958 parked: vec!["running".to_owned()],
3959 interrupt_task: "marked".to_owned(),
3960 };
3961 let other = task();
3962 let candidates = vec![interrupt_task("marked"), other.clone()];
3963 let allowed = interrupt_gate(&state, &[], candidates);
3964 assert_eq!(allowed.len(), 1);
3965 assert_eq!(allowed[0].id, "marked");
3966 }
3967
3968 #[test]
3969 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
3970 let state = Interrupt::Running {
3971 parked: vec!["running".to_owned()],
3972 interrupt_task: "marked".to_owned(),
3973 };
3974 let candidates = vec![task(), task()];
3975 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
3976 assert!(allowed.is_empty());
3977 }
3978
3979 /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
3980 /// sequence began (only reachable above the default
3981 /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
3982 /// never both in the same tick, which is what "exactly one resume, no
3983 /// simultaneous run" actually requires structurally rather than by
3984 /// coincidence of how many ordinary slots happen to be free.
3985 #[test]
3986 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
3987 let state = Interrupt::Resuming {
3988 parked: vec!["a".to_owned(), "c".to_owned()],
3989 };
3990 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
3991 let allowed = interrupt_gate(&state, &[], candidates);
3992 assert_eq!(
3993 allowed.len(),
3994 1,
3995 "at most one candidate may be offered while resuming: {allowed:?}"
3996 );
3997 assert_eq!(allowed[0].id, "a");
3998 }
3999
4000 #[test]
4001 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
4002 let state = Interrupt::Resuming {
4003 parked: vec!["a".to_owned()],
4004 };
4005 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
4006 assert!(allowed.is_empty());
4007 }
4008
4009 /// The invariant the completion criteria ask for by name: across a whole
4010 /// simulated sequence, there is never a tick where the gate would let
4011 /// through both the parked run's resume and the interrupt task, and
4012 /// exactly one candidate resumes the instant the interrupt task's run
4013 /// ends - never zero, never more than one.
4014 #[test]
4015 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
4016 let running = task(); // id: whatever `Task::new` minted
4017 let marked = interrupt_task("marked");
4018
4019 let mut state = Interrupt::Idle;
4020 // Tick 1: `running` is in flight, `marked` becomes runnable.
4021 let in_flight = vec![running.id.clone()];
4022 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
4023 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
4024 assert!(gated.is_empty(), "still waiting on `running` to park");
4025
4026 // Tick 2: `running` parked and left flight; nothing dispatched yet.
4027 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
4028 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
4029 assert_eq!(
4030 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4031 vec!["marked"],
4032 "only the interrupt task may be offered to the dispatcher now"
4033 );
4034
4035 // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
4036 state = advance_interrupt_tick(
4037 true,
4038 state,
4039 &["marked".to_owned()],
4040 std::slice::from_ref(&running),
4041 );
4042 let gated = interrupt_gate(
4043 &state,
4044 &["marked".to_owned()],
4045 vec![marked.clone(), running.clone()],
4046 );
4047 assert!(
4048 gated.is_empty(),
4049 "the parked run must not be offered back while the interrupt \
4050 task is still running"
4051 );
4052
4053 // Tick 4: `marked`'s run reached a terminal status and left flight.
4054 // A higher-priority ordinary task `other` is also runnable now - it
4055 // must not be let through instead of, or alongside, `running`.
4056 let other = task_with_id("other");
4057 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
4058 assert_eq!(
4059 state,
4060 Interrupt::Resuming {
4061 parked: vec![running.id.clone()]
4062 }
4063 );
4064 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
4065 assert_eq!(
4066 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4067 vec![running.id.as_str()],
4068 "exactly the parked run resumes - not the unrelated task, even \
4069 though it was offered first"
4070 );
4071
4072 // Tick 5: `running` is now in flight (dispatched from tick 4's
4073 // gate). Only now does the sequence end and ordinary dispatch fully
4074 // resume.
4075 state = advance_interrupt_tick(
4076 true,
4077 state,
4078 std::slice::from_ref(&running.id),
4079 std::slice::from_ref(&other),
4080 );
4081 assert_eq!(state, Interrupt::Idle);
4082 let gated = interrupt_gate(
4083 &state,
4084 std::slice::from_ref(&running.id),
4085 vec![other.clone()],
4086 );
4087 assert_eq!(
4088 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
4089 vec![other.id.as_str()],
4090 "ordinary dispatch is unrestricted again"
4091 );
4092 }
4093
4094 #[test]
4095 fn every_run_status_settles_the_task_it_came_from() {
4096 // run status, resulting task status, attempts still standing after one
4097 let table = [
4098 (RunStatus::Merged, TaskStatus::Done, 1),
4099 (RunStatus::Ready, TaskStatus::Done, 1),
4100 (RunStatus::Stalled, TaskStatus::Failed, 0),
4101 (RunStatus::Blocked, TaskStatus::Failed, 1),
4102 (RunStatus::Failed, TaskStatus::Failed, 1),
4103 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
4104 (RunStatus::Prep, TaskStatus::Failed, 1),
4105 (RunStatus::Implementing, TaskStatus::Failed, 1),
4106 (RunStatus::Judging, TaskStatus::Failed, 1),
4107 (RunStatus::Deliberating, TaskStatus::Failed, 1),
4108 (RunStatus::Voting, TaskStatus::Failed, 1),
4109 (RunStatus::Reviewing, TaskStatus::Failed, 1),
4110 (RunStatus::Gating, TaskStatus::Failed, 1),
4111 ];
4112 for (run, want, attempts) in table {
4113 let mut t = task();
4114 t.start("20260902-000000-aaaa".to_owned());
4115 settle(
4116 &mut t,
4117 Verdict {
4118 status: run,
4119 left_pr: false,
4120 parked: false,
4121 quota_hit: matches!(run, RunStatus::Stalled),
4122 no_viable_candidates: false,
4123 },
4124 "why",
4125 2,
4126 );
4127 assert_eq!(t.status, want, "task status after {}", label(run));
4128 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
4129 }
4130 }
4131
4132 #[test]
4133 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
4134 let mut stalled = task();
4135 stalled.start("20260902-000000-aaaa".to_owned());
4136 settle(
4137 &mut stalled,
4138 Verdict {
4139 status: RunStatus::Stalled,
4140 left_pr: false,
4141 parked: false,
4142 quota_hit: true,
4143 no_viable_candidates: false,
4144 },
4145 "quota",
4146 1,
4147 );
4148 assert_eq!(stalled.attempts, 0);
4149 assert!(
4150 stalled.status.runnable(),
4151 "a machine problem must leave the task in line"
4152 );
4153
4154 let mut blocked = task();
4155 blocked.start("20260902-000000-aaaa".to_owned());
4156 settle(
4157 &mut blocked,
4158 Verdict {
4159 status: RunStatus::Blocked,
4160 left_pr: false,
4161 parked: false,
4162 quota_hit: false,
4163 no_viable_candidates: false,
4164 },
4165 "findings open",
4166 1,
4167 );
4168 assert_eq!(blocked.attempts, 1);
4169 assert_eq!(
4170 blocked.status,
4171 TaskStatus::Held,
4172 "the last attempt hands the task to a human"
4173 );
4174 }
4175
4176 #[test]
4177 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
4178 // Attempts to spare: without the pull request this task would go
4179 // straight back in line and run the whole competition again.
4180 let mut delivered = task();
4181 delivered.start("20260903-080619-01c2".to_owned());
4182 settle(
4183 &mut delivered,
4184 Verdict {
4185 status: RunStatus::Blocked,
4186 left_pr: true,
4187 parked: false,
4188 quota_hit: false,
4189 no_viable_candidates: false,
4190 },
4191 "no check status",
4192 4,
4193 );
4194 assert_eq!(
4195 delivered.status,
4196 TaskStatus::Held,
4197 "a pull request waiting on CI or a person is not a retryable failure"
4198 );
4199 assert!(
4200 !delivered.status.runnable(),
4201 "the loop must not pick this task up again"
4202 );
4203 assert_eq!(
4204 delivered.last_error.as_deref(),
4205 Some("no check status"),
4206 "the operator needs to be told what the gate was waiting for"
4207 );
4208
4209 // The same status without a pull request is a plain failure, and with
4210 // attempts left it is retried.
4211 let mut empty_handed = task();
4212 empty_handed.start("20260903-080619-01c2".to_owned());
4213 settle(
4214 &mut empty_handed,
4215 Verdict {
4216 status: RunStatus::Blocked,
4217 left_pr: false,
4218 parked: false,
4219 quota_hit: false,
4220 no_viable_candidates: false,
4221 },
4222 "findings open",
4223 4,
4224 );
4225 assert_eq!(empty_handed.status, TaskStatus::Failed);
4226 assert!(empty_handed.status.runnable());
4227 }
4228
4229 #[test]
4230 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
4231 // Every candidate agreed, with evidence, that nothing belonged in the
4232 // worktree. That is not a confirmed success to close automatically -
4233 // a human still has to check the claim - and it is not an ordinary
4234 // failure either, so this settles exactly like a pull request nobody
4235 // merged yet: `Held`, same as `Blocked` with a PR.
4236 let mut noop = task();
4237 noop.start("20260912-131304-391f".to_owned());
4238 settle(
4239 &mut noop,
4240 Verdict {
4241 status: RunStatus::VerifiedNoop,
4242 left_pr: false,
4243 parked: false,
4244 quota_hit: false,
4245 no_viable_candidates: true,
4246 },
4247 "candidate A: already fixed by b32cfc4, on main",
4248 4,
4249 );
4250 assert_eq!(
4251 noop.status,
4252 TaskStatus::Held,
4253 "an unverified claim is a request for a human, not a failure"
4254 );
4255 assert!(
4256 !noop.status.runnable(),
4257 "the loop must not requeue this on the same unverified claim"
4258 );
4259 // `Task::release` resets attempts to zero the moment a human looks at
4260 // the evidence and lets it run again, so it does not matter here
4261 // whether the one attempt already spent stays spent - what matters is
4262 // that nothing retries this task unattended in the meantime.
4263 assert_eq!(noop.attempts, 1);
4264 }
4265
4266 #[test]
4267 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
4268 // Parking is the operator asking for the process back - to replace the
4269 // binary, most of all. The run's work is intact on disk, so this is
4270 // not a failed attempt, and charging for it would mean a few upgrades
4271 // could exhaust a budget meant for agents that misbehaved.
4272 let mut parked = task();
4273 parked.start("20260903-183634-2d98".to_owned());
4274 settle(
4275 &mut parked,
4276 Verdict {
4277 status: RunStatus::Implementing,
4278 left_pr: false,
4279 quota_hit: false,
4280 parked: true,
4281 no_viable_candidates: false,
4282 },
4283 "parked after `implementing`",
4284 2,
4285 );
4286 assert_eq!(parked.attempts, 0, "a park is refunded");
4287 assert!(
4288 parked.status.runnable(),
4289 "and the task stays in line so the next loop resumes its run"
4290 );
4291 assert_eq!(
4292 parked.last_error.as_deref(),
4293 Some("parked after `implementing`"),
4294 "the card says where it stopped"
4295 );
4296
4297 // Without the park flag the same non-terminal status is what it always
4298 // was: `execute` returning mid-flight, which is a bug and spends an
4299 // attempt so a task cannot loop on it forever.
4300 let mut broken = task();
4301 broken.start("20260903-183634-2d98".to_owned());
4302 settle(
4303 &mut broken,
4304 Verdict {
4305 status: RunStatus::Implementing,
4306 left_pr: false,
4307 quota_hit: false,
4308 parked: false,
4309 no_viable_candidates: false,
4310 },
4311 "returned mid-flight",
4312 2,
4313 );
4314 assert_eq!(broken.attempts, 1);
4315 }
4316
4317 #[test]
4318 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
4319 // Run e633: quorum lost because two judges answered with the wrong
4320 // JSON shape, `quota: []`. Refunding that takes the bound off the
4321 // retry loop, and each retry pays for a fresh hour-long implement
4322 // wave before it can fail the same way.
4323 let mut flaky = task();
4324 flaky.start("20260903-123023-e633".to_owned());
4325 settle(
4326 &mut flaky,
4327 Verdict {
4328 status: RunStatus::Stalled,
4329 left_pr: false,
4330 parked: false,
4331 quota_hit: false,
4332 no_viable_candidates: false,
4333 },
4334 "verdict rests on 1 of 3 judges",
4335 2,
4336 );
4337 assert_eq!(
4338 flaky.attempts, 1,
4339 "flakiness spends an attempt, so `max_attempts` still bounds it"
4340 );
4341 assert!(flaky.status.runnable(), "and it is still worth retrying");
4342
4343 // The same status, lost to a rate limit, is the machine's fault.
4344 let mut limited = task();
4345 limited.start("20260903-123023-e633".to_owned());
4346 settle(
4347 &mut limited,
4348 Verdict {
4349 status: RunStatus::Stalled,
4350 left_pr: false,
4351 parked: false,
4352 quota_hit: true,
4353 no_viable_candidates: false,
4354 },
4355 "judge-2, judge-3 out of quota",
4356 2,
4357 );
4358 assert_eq!(limited.attempts, 0, "a quota window is refunded");
4359 assert!(limited.status.runnable());
4360
4361 // And the bound really binds: a task that keeps stalling on flakiness
4362 // reaches a human instead of running the roster forever.
4363 let mut worn = task();
4364 for _ in 0..2 {
4365 worn.release();
4366 }
4367 worn.start("20260903-123023-e633".to_owned());
4368 worn.attempts = 2;
4369 settle(
4370 &mut worn,
4371 Verdict {
4372 status: RunStatus::Stalled,
4373 left_pr: false,
4374 parked: false,
4375 quota_hit: false,
4376 no_viable_candidates: false,
4377 },
4378 "no quorum again",
4379 2,
4380 );
4381 assert_eq!(worn.status, TaskStatus::Held);
4382 assert!(!worn.status.runnable());
4383 }
4384
4385 #[test]
4386 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
4387 // The implement wave loses every seat to the same rate limit and
4388 // `after_implement` bails with nothing viable, which surfaces as
4389 // `Failed` rather than `Stalled`. That is the same machine fact the
4390 // `Stalled`-quota row already refunds, and must be refunded the same
4391 // way, or a quota outage quietly holds every task it touches instead
4392 // of leaving them in line for the reset.
4393 let mut wiped_out = task();
4394 wiped_out.start("20260907-025000-a1b2".to_owned());
4395 settle(
4396 &mut wiped_out,
4397 Verdict {
4398 status: RunStatus::Failed,
4399 left_pr: false,
4400 parked: false,
4401 quota_hit: true,
4402 no_viable_candidates: true,
4403 },
4404 "no candidate produced a change; nothing to judge",
4405 2,
4406 );
4407 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
4408 assert!(
4409 wiped_out.status.runnable(),
4410 "a machine problem must leave the task in line"
4411 );
4412
4413 // This is the exemption that must stay narrow: a candidate that did
4414 // produce a change, and then failed for some other reason, still
4415 // spends the attempt even though a seat elsewhere hit its quota.
4416 // Otherwise every ordinary failure that happens to share a run with
4417 // an unrelated rate limit would be refunded for free.
4418 let mut partial_progress = task();
4419 partial_progress.start("20260907-025500-c3d4".to_owned());
4420 settle(
4421 &mut partial_progress,
4422 Verdict {
4423 status: RunStatus::Failed,
4424 left_pr: false,
4425 parked: false,
4426 quota_hit: true,
4427 no_viable_candidates: false,
4428 },
4429 "gate failed on the winning candidate",
4430 2,
4431 );
4432 assert_eq!(
4433 partial_progress.attempts, 1,
4434 "a candidate that actually produced a change spends the attempt \
4435 even though some other seat hit its quota"
4436 );
4437 assert!(partial_progress.status.runnable());
4438 }
4439
4440 #[test]
4441 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
4442 // `reclaim` builds its own `Verdict` from a `RunState` it loads off
4443 // disk, and that construction must reach the same conclusion as the
4444 // one `attempt` builds from a live run, or a crash at exactly the
4445 // wrong moment gives a recovered task a different policy than one a
4446 // daemon finished settling itself.
4447 let mut t = task();
4448 t.start("20260907-025000-a1b2".to_owned());
4449 let mut state = run_state(RunStatus::Failed);
4450 state.quota.push(QuotaLoss {
4451 seat: "cand-a".to_owned(),
4452 node: "implement".to_owned(),
4453 at: Timestamp::now(),
4454 reset: None,
4455 });
4456 assert!(
4457 state.viable().is_empty(),
4458 "no candidate was added, so nothing is viable"
4459 );
4460 reclaim(&mut t, Some(state), 2);
4461 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
4462 assert!(t.status.runnable());
4463 }
4464
4465 #[test]
4466 fn a_held_task_is_never_offered_to_the_loop() {
4467 let dir = tempfile::tempdir().unwrap();
4468 let queue = Queue::at(dir.path().to_path_buf());
4469 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
4470 let mut t = task();
4471 t.id = format!("2026090{n}-000000-000{n}");
4472 t.priority = priority;
4473 queue.put(&mut t).unwrap();
4474 }
4475 let mut held = task();
4476 held.id = "20260909-000000-9999".to_owned();
4477 held.priority = 99;
4478 held.hold_machine(None);
4479 queue.put(&mut held).unwrap();
4480
4481 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
4482 assert_eq!(order.len(), 3);
4483 assert!(!order.contains(&held.id));
4484 assert_eq!(
4485 order.first().cloned(),
4486 queue.next_runnable().map(|t| t.id),
4487 "the loop's first candidate is exactly what the queue offers"
4488 );
4489 assert_eq!(
4490 order,
4491 vec![
4492 "20260902-000000-0002".to_owned(),
4493 "20260903-000000-0003".to_owned(),
4494 "20260901-000000-0001".to_owned(),
4495 ],
4496 "priority first, then oldest, so nothing starves"
4497 );
4498 }
4499
4500 #[test]
4501 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
4502 let dir = tempfile::tempdir().unwrap();
4503 let queue = Queue::at(dir.path().to_path_buf());
4504 let mut old = task();
4505 old.id = "20260101-000000-old0".to_owned();
4506 queue.put(&mut old).unwrap();
4507 let mut fresh = task();
4508 fresh.id = "20260101-000000-new0".to_owned();
4509 queue.put(&mut fresh).unwrap();
4510
4511 // No parseable pid at all, so age is the only signal there is to
4512 // check - unlike a real `Queue::claim`, which always names a real,
4513 // and therefore alive, pid this test cannot fake as dead.
4514 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
4515 std::thread::sleep(Duration::from_millis(60));
4516 let live = queue.claim(&fresh.id).unwrap();
4517
4518 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4519 assert_eq!(swept, vec![old.id.clone()]);
4520 assert!(
4521 queue.claim(&old.id).is_ok(),
4522 "an unparseable lock older than the threshold is swept"
4523 );
4524 assert!(
4525 queue.claim(&fresh.id).is_err(),
4526 "a live pid protects its lock regardless of age"
4527 );
4528 drop(live);
4529 }
4530
4531 #[test]
4532 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
4533 // The regression this guards: `sweep` now runs concurrently with
4534 // every attempt this daemon itself has spawned (see
4535 // `InFlightGuard`), not only between them the way a single
4536 // sequential loop once did. A run that legitimately outlives
4537 // `older_than` still has this very process's own live pid sitting in
4538 // its own lock file on every later sweep, and deciding by age alone
4539 // would delete that still-valid claim out from under the attempt
4540 // that holds it - which `reclaim_orphaned_running` would then read
4541 // as abandoned and hand to a second, competing attempt.
4542 let dir = tempfile::tempdir().unwrap();
4543 let queue = Queue::at(dir.path().to_path_buf());
4544 let mut t = task();
4545 t.id = "20260101-000000-live".to_owned();
4546 queue.put(&mut t).unwrap();
4547
4548 let claim = queue.claim(&t.id).unwrap();
4549 std::thread::sleep(Duration::from_millis(60));
4550
4551 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4552 assert!(
4553 swept.is_empty(),
4554 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
4555 );
4556 assert!(
4557 queue.claim(&t.id).is_err(),
4558 "the lock still protects its task"
4559 );
4560 drop(claim);
4561 }
4562
4563 /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
4564 /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
4565 fn injected_dead_pid() -> u32 {
4566 std::process::id().checked_add(1).unwrap_or(1)
4567 }
4568
4569 #[test]
4570 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
4571 let dir = tempfile::tempdir().unwrap();
4572 let queue = Queue::at(dir.path().to_path_buf());
4573 let mut t = task();
4574 t.id = "20260101-000000-dead".to_owned();
4575 queue.put(&mut t).unwrap();
4576 let dead_pid = injected_dead_pid();
4577
4578 // Written directly rather than through `Queue::claim`, which would
4579 // stamp this test process's own very much alive pid and defeat the
4580 // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
4581 // like moments after it died, not six hours later.
4582 std::fs::write(
4583 dir.path().join(format!("{}.lock", t.id)),
4584 dead_pid.to_string(),
4585 )
4586 .unwrap();
4587
4588 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4589 pid != dead_pid
4590 });
4591 assert_eq!(
4592 swept,
4593 vec![t.id.clone()],
4594 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
4595 );
4596 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
4597 }
4598
4599 #[test]
4600 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
4601 let dir = tempfile::tempdir().unwrap();
4602 let queue = Queue::at(dir.path().to_path_buf());
4603 let mut t = task();
4604 t.id = "20260101-000000-late".to_owned();
4605 queue.put(&mut t).unwrap();
4606 let dead_pid = injected_dead_pid();
4607
4608 // Tick one, standing in for the sweep `poll` already runs at
4609 // startup: nothing to find yet.
4610 assert!(
4611 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
4612 "nothing has claimed the task yet"
4613 );
4614
4615 // A second daemon claims the task and dies before it ever writes
4616 // `running`, well after this loop's own startup sweep already ran.
4617 std::fs::write(
4618 dir.path().join(format!("{}.lock", t.id)),
4619 dead_pid.to_string(),
4620 )
4621 .unwrap();
4622
4623 // Tick two, standing in for a poll long into this daemon's uptime:
4624 // the same function, called again, notices what only just appeared -
4625 // proving the sweep is not a one-shot startup check.
4626 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4627 pid != dead_pid
4628 });
4629 assert_eq!(swept, vec![t.id.clone()]);
4630 }
4631
4632 #[test]
4633 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
4634 // `reclaim_orphaned_running` looks up the task's last run, which
4635 // touches `run::home()`; the first call anywhere in this binary wins,
4636 // so this is a no-op if another test already pinned one, and either
4637 // way the run id below is never written under it.
4638 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4639 let dir = tempfile::tempdir().unwrap();
4640 let queue = Queue::at(dir.path().to_path_buf());
4641 let mut t = task();
4642 t.id = "20260101-000000-crsh".to_owned();
4643 t.status = TaskStatus::Running;
4644 t.attempts = 1;
4645 // No `run.json` behind this id: standing in for a run this test does
4646 // not need to make readable, since the point is the lock, not the
4647 // recovery table `reclaim` already has its own tests for.
4648 t.runs.push("20260904-000000-4043".to_owned());
4649 queue.put(&mut t).unwrap();
4650 let dead_pid = injected_dead_pid();
4651
4652 // The crashed daemon's own claim, naming a pid nothing on the
4653 // machine holds anymore.
4654 std::fs::write(
4655 dir.path().join(format!("{}.lock", t.id)),
4656 dead_pid.to_string(),
4657 )
4658 .unwrap();
4659
4660 // Before the lock is swept the task looks claimed, and
4661 // `reclaim_orphaned_running` must leave it alone - this is exactly
4662 // the bug: a `running` task stranded behind a dead daemon's lock,
4663 // invisible to the claim-as-proof check because the lock outlived
4664 // the process that wrote it.
4665 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
4666 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
4667
4668 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4669 pid != dead_pid
4670 });
4671 assert_eq!(swept, vec![t.id.clone()]);
4672
4673 let reclaimed = reclaim_orphaned_running(&queue, 2);
4674 assert_eq!(reclaimed, vec![t.id.clone()]);
4675 let after = queue.get(&t.id).unwrap();
4676 assert_eq!(
4677 after.status,
4678 TaskStatus::Held,
4679 "no run.json to recover from, so a human is asked"
4680 );
4681 assert_eq!(
4682 after.runs,
4683 vec!["20260904-000000-4043".to_owned()],
4684 "the crashed run's id is kept as evidence, not discarded"
4685 );
4686 }
4687
4688 #[test]
4689 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
4690 let dir = tempfile::tempdir().unwrap();
4691 let queue = Queue::at(dir.path().to_path_buf());
4692 let mut t = task();
4693 t.id = "20260101-000000-unknown".to_owned();
4694 queue.put(&mut t).unwrap();
4695 let dead_pid = injected_dead_pid();
4696 std::fs::write(
4697 dir.path().join(format!("{}.lock", t.id)),
4698 dead_pid.to_string(),
4699 )
4700 .unwrap();
4701
4702 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
4703 assert!(swept.is_empty(), "an unknown pid must keep its lock");
4704 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
4705 }
4706
4707 fn run_state(status: RunStatus) -> RunState {
4708 let mut state = RunState::new(
4709 PathBuf::from("/repo"),
4710 "main".to_owned(),
4711 "abc1234def".to_owned(),
4712 "add retries".to_owned(),
4713 Config::default(),
4714 );
4715 state.status = status;
4716 state
4717 }
4718
4719 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
4720 Candidate {
4721 index: 0,
4722 label,
4723 agent: "claude".to_owned(),
4724 branch: format!("magi/x/{label}"),
4725 worktree: PathBuf::from("/repo"),
4726 summary: summary.to_owned(),
4727 stat: String::new(),
4728 files: 0,
4729 commits: usize::from(!empty),
4730 empty,
4731 failed: failed.map(str::to_owned),
4732 verified_noop: None,
4733 duration_ms: 0,
4734 folded: false,
4735 }
4736 }
4737
4738 #[test]
4739 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
4740 let mut state = run_state(RunStatus::Blocked);
4741 state.gate = vec![
4742 CommandOutcome {
4743 command: "cargo make check".to_owned(),
4744 code: Some(0),
4745 output_tail: "ok".to_owned(),
4746 duration_ms: 0,
4747 resource_blocked: false,
4748 },
4749 CommandOutcome {
4750 command: "cargo test".to_owned(),
4751 code: Some(101),
4752 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
4753 duration_ms: 0,
4754 resource_blocked: false,
4755 },
4756 ];
4757 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
4758 assert!(d.contains("cargo test"), "{d}");
4759 assert!(
4760 !d.contains("cargo make check"),
4761 "a passing check is not a diagnostic: {d}"
4762 );
4763 assert!(d.contains("assertion failed"), "{d}");
4764 }
4765
4766 #[test]
4767 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
4768 let mut state = run_state(RunStatus::Blocked);
4769 state.event(
4770 "land",
4771 "stopped: the fixer produced no commit while 2 check(s) were failing \
4772 (build, lint); stopping instead of looping on an unchanged tree",
4773 );
4774 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
4775 assert!(d.contains("build"), "{d}");
4776 assert!(d.contains("lint"), "{d}");
4777 assert!(d.contains("fixer produced no commit"), "{d}");
4778 }
4779
4780 #[test]
4781 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
4782 // `describe`'s output becomes `Task::last_error` verbatim, and the
4783 // phone renders that in the same alarm-styled box an ordinary
4784 // failure gets. A bare `verified_noop` there would read exactly like
4785 // the failure this status exists to be told apart from.
4786 let state = run_state(RunStatus::VerifiedNoop);
4787 let d = describe(&state);
4788 assert!(
4789 d.contains("agent-verified no-op"),
4790 "expected the display label, not the wire spelling: {d}"
4791 );
4792 assert!(!d.contains("verified_noop"), "{d}");
4793 }
4794
4795 #[test]
4796 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
4797 // The whole point of the feature: a run held as "no candidate produced
4798 // a change" can mean the implementer actually finished the task and
4799 // only left a clean local tree behind - see AGENTS.md on this exact
4800 // failure mode. The diagnostic has to carry what the agent actually
4801 // said, not just the fact that nothing was there to judge.
4802 let mut state = run_state(RunStatus::Failed);
4803 state.candidates = vec![candidate(
4804 'A',
4805 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
4806 true,
4807 None,
4808 )];
4809 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
4810 assert!(d.contains("candidate A"), "{d}");
4811 assert!(d.contains("tagged v1.2.3"), "{d}");
4812 }
4813
4814 #[test]
4815 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
4816 let mut state = run_state(RunStatus::Failed);
4817 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
4818 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
4819 assert!(d.contains("candidate A"), "{d}");
4820 assert!(d.contains("agent timed out"), "{d}");
4821 }
4822
4823 #[test]
4824 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
4825 // A viable candidate existed, the gate never ran, and nothing land
4826 // said matches - `Task::last_error` is left to explain this one alone.
4827 let mut state = run_state(RunStatus::Failed);
4828 state.candidates = vec![candidate('A', "did the work", false, None)];
4829 assert!(diagnostic(&state).is_none());
4830 }
4831
4832 #[test]
4833 fn diagnostic_is_bounded_however_much_a_run_printed() {
4834 let mut state = run_state(RunStatus::Blocked);
4835 state.gate = vec![
4836 CommandOutcome {
4837 command: "cargo test".to_owned(),
4838 code: Some(101),
4839 output_tail: "x".repeat(50_000),
4840 duration_ms: 0,
4841 resource_blocked: false,
4842 },
4843 CommandOutcome {
4844 command: "cargo clippy".to_owned(),
4845 code: Some(1),
4846 output_tail: "y".repeat(50_000),
4847 duration_ms: 0,
4848 resource_blocked: false,
4849 },
4850 ];
4851 state.candidates = vec![
4852 candidate('A', &"z".repeat(50_000), true, None),
4853 candidate('B', &"w".repeat(50_000), true, None),
4854 ];
4855 let d = diagnostic(&state).expect("plenty here to diagnose");
4856 assert!(
4857 d.len() <= DIAGNOSTIC_MAX,
4858 "diagnostic grew to {} bytes, unbounded",
4859 d.len()
4860 );
4861 }
4862
4863 #[test]
4864 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
4865 let mut state = run_state(RunStatus::Blocked);
4866 state.gate = vec![CommandOutcome {
4867 command: "cargo test".to_owned(),
4868 code: Some(101),
4869 output_tail: "assertion failed".to_owned(),
4870 duration_ms: 0,
4871 resource_blocked: false,
4872 }];
4873 let verdict = Verdict {
4874 status: RunStatus::Blocked,
4875 left_pr: false,
4876 quota_hit: false,
4877 parked: false,
4878 no_viable_candidates: false,
4879 };
4880
4881 // Attempt one of two still has a retry coming: no diagnostic yet, the
4882 // task is going to run again and this run's evidence would go stale.
4883 let mut t = task();
4884 t.start("run-1".to_owned());
4885 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4886 assert_eq!(t.status, TaskStatus::Failed);
4887 assert!(t.diagnostic.is_none());
4888
4889 // Attempt two exhausts the budget: now it is held, and the
4890 // diagnostic is what `magi task show` has to say more than one line.
4891 t.start("run-2".to_owned());
4892 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4893 assert_eq!(t.status, TaskStatus::Held);
4894 let d = t.diagnostic.expect("a held task must carry its diagnostic");
4895 assert!(d.contains("cargo test"), "{d}");
4896 }
4897
4898 #[test]
4899 fn a_held_task_names_the_open_question_it_is_waiting_on() {
4900 // Task 20260928-191407-05fd's own bug: a verified no-op that filed a
4901 // `magi ask` question settled Held with `hold_reason: null`, so the
4902 // notification said nothing actionable. `note_open_question` should
4903 // append the question id to whatever `handed_off` already wrote.
4904 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4905 let home = crate::run::home();
4906 let state = run_state(RunStatus::VerifiedNoop);
4907 let mut q = ask::Question::new(
4908 state.id.clone(),
4909 "implement".to_owned(),
4910 "impl-A".to_owned(),
4911 "is this really a no-op?".to_owned(),
4912 String::new(),
4913 Vec::new(),
4914 );
4915 Questions::at(home.join("questions")).put(&mut q).unwrap();
4916
4917 let verdict = Verdict {
4918 status: RunStatus::VerifiedNoop,
4919 left_pr: false,
4920 quota_hit: false,
4921 parked: false,
4922 no_viable_candidates: false,
4923 };
4924 let mut t = task();
4925 t.start(state.id.clone());
4926 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4927
4928 assert_eq!(t.status, TaskStatus::Held);
4929 let reason = t.hold_reason.expect("a held task must record why");
4930 assert!(
4931 reason.starts_with("run ended agent-verified no-op"),
4932 "the original settle reason must survive unchanged: {reason}"
4933 );
4934 assert!(
4935 reason.contains(q.short()),
4936 "the open question's id must be named so the notice is actionable: {reason}"
4937 );
4938 }
4939
4940 #[test]
4941 fn a_held_task_with_no_open_question_keeps_its_plain_reason() {
4942 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4943 let state = run_state(RunStatus::VerifiedNoop);
4944
4945 let verdict = Verdict {
4946 status: RunStatus::VerifiedNoop,
4947 left_pr: false,
4948 quota_hit: false,
4949 parked: false,
4950 no_viable_candidates: false,
4951 };
4952 let mut t = task();
4953 t.start(state.id.clone());
4954 settle_and_diagnose(&mut t, verdict, "run ended agent-verified no-op", 5, &state);
4955
4956 assert_eq!(t.status, TaskStatus::Held);
4957 assert_eq!(
4958 t.hold_reason.as_deref(),
4959 Some("run ended agent-verified no-op"),
4960 "nothing to append when the question was already answered or never asked"
4961 );
4962 }
4963
4964 #[test]
4965 fn supersede_prior_runs_rewrites_an_earlier_blocked_attempt_once_a_later_one_lands() {
4966 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4967 let mut first = run_state(RunStatus::Blocked);
4968 first.id = "20260101-000000-sup1".to_owned();
4969 first.save().unwrap();
4970 let mut second = run_state(RunStatus::Merged);
4971 second.id = "20260101-000000-sup2".to_owned();
4972 second.save().unwrap();
4973
4974 let mut t = task();
4975 t.runs = vec![first.id.clone(), second.id.clone()];
4976 t.status = TaskStatus::Done;
4977
4978 supersede_prior_runs(&t, &crate::run::home());
4979
4980 assert_eq!(
4981 RunState::load(&first.id).unwrap().status,
4982 RunStatus::Superseded,
4983 "the first attempt's Blocked no longer needs anyone's attention"
4984 );
4985 assert_eq!(
4986 RunState::load(&second.id).unwrap().status,
4987 RunStatus::Merged,
4988 "the run that actually succeeded is left exactly as it was"
4989 );
4990 }
4991
4992 #[test]
4993 fn supersede_prior_runs_leaves_a_manually_resumed_attempt_alone() {
4994 // `is_working_on` alone only proves a *daemon* claim; a `magi run
4995 // --resume` invoked by hand outside the daemon never touches
4996 // `daemon.json` at all, so it would look identical to a genuinely
4997 // idle run without also consulting `RunState::liveness`, which reads
4998 // this run's own recorded `driver_pid` instead.
4999 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5000 let mut first = run_state(RunStatus::Blocked);
5001 first.id = "20260101-000000-sup9".to_owned();
5002 // This test process's own pid: guaranteed alive without needing a
5003 // real second process or daemon.
5004 first.driver_pid = Some(std::process::id());
5005 first.driver_started_at = Some(
5006 crate::proc::process_started_at(std::process::id())
5007 .expect("this test process's own start time must be queryable"),
5008 );
5009 first.save().unwrap();
5010 let mut second = run_state(RunStatus::Merged);
5011 second.id = "20260101-000000-supa".to_owned();
5012 second.save().unwrap();
5013
5014 let mut t = task();
5015 t.runs = vec![first.id.clone(), second.id.clone()];
5016 t.status = TaskStatus::Done;
5017
5018 supersede_prior_runs(&t, &crate::run::home());
5019
5020 assert_eq!(
5021 RunState::load(&first.id).unwrap().status,
5022 RunStatus::Blocked,
5023 "a live driver_pid means something is still actually working this run, \
5024 even though no daemon claims it - rewriting under it would just be \
5025 undone the next time that process saves"
5026 );
5027 }
5028
5029 #[test]
5030 fn resweep_catches_up_a_run_left_live_once_its_manual_process_is_no_longer_driving_it() {
5031 // The first resweep must skip a still-live attempt exactly like
5032 // `supersede_prior_runs` itself does; a later resweep, once that
5033 // process is no longer actually driving it, is what closes the gap
5034 // `supersede_prior_runs` alone leaves - a task only ever reaches
5035 // `Done` once, so nothing else would ever look at this run again.
5036 let dir = tempfile::tempdir().unwrap();
5037 let home = dir.path().to_path_buf();
5038 let queue = Queue::at(dir.path().join("queue"));
5039
5040 let mut first = run_state(RunStatus::Blocked);
5041 first.id = "20260101-000000-supd".to_owned();
5042 first.driver_pid = Some(std::process::id());
5043 first.driver_started_at = Some(
5044 crate::proc::process_started_at(std::process::id())
5045 .expect("this test process's own start time must be queryable"),
5046 );
5047 first.save_under(&home).unwrap();
5048 let mut second = run_state(RunStatus::Merged);
5049 second.id = "20260101-000000-supe".to_owned();
5050 second.save_under(&home).unwrap();
5051
5052 let mut t = task();
5053 t.runs = vec![first.id.clone(), second.id.clone()];
5054 t.status = TaskStatus::Done;
5055 queue.put(&mut t).unwrap();
5056
5057 resweep_superseded_attempts(&queue, &home);
5058 assert_eq!(
5059 RunState::load_under(&first.id, &home).unwrap().status,
5060 RunStatus::Blocked,
5061 "still live on the first pass, so still untouched"
5062 );
5063
5064 // Stand in for the manual process no longer being the one driving
5065 // this run: same pid (this test process really is still alive), but
5066 // an identity marker that no longer matches it - see
5067 // `RunState::liveness`'s own doc for why a mismatched
5068 // `driver_started_at` reads as `Dead`, not merely `Unknown`.
5069 let mut stale = RunState::load_under(&first.id, &home).unwrap();
5070 stale.driver_started_at = Some("not-this-processes-real-start-time".to_owned());
5071 stale.save_under(&home).unwrap();
5072
5073 resweep_superseded_attempts(&queue, &home);
5074 assert_eq!(
5075 RunState::load_under(&first.id, &home).unwrap().status,
5076 RunStatus::Superseded,
5077 "the second pass catches up what the first one correctly skipped"
5078 );
5079 }
5080
5081 #[test]
5082 fn supersede_prior_runs_leaves_concurrent_blocked_attempts_alone_while_the_task_is_not_done() {
5083 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5084 let mut first = run_state(RunStatus::Blocked);
5085 first.id = "20260101-000000-sup3".to_owned();
5086 first.save().unwrap();
5087 let mut second = run_state(RunStatus::Blocked);
5088 second.id = "20260101-000000-sup4".to_owned();
5089 second.save().unwrap();
5090
5091 let mut t = task();
5092 t.runs = vec![first.id.clone(), second.id.clone()];
5093 // Still retrying: nothing about this task's story is settled yet, so
5094 // neither Blocked run may be relabelled, even though a later attempt
5095 // already exists.
5096 t.status = TaskStatus::Failed;
5097
5098 supersede_prior_runs(&t, &crate::run::home());
5099
5100 assert_eq!(
5101 RunState::load(&first.id).unwrap().status,
5102 RunStatus::Blocked
5103 );
5104 assert_eq!(
5105 RunState::load(&second.id).unwrap().status,
5106 RunStatus::Blocked
5107 );
5108 }
5109
5110 #[test]
5111 fn supersede_prior_runs_does_nothing_when_the_task_was_closed_by_hand() {
5112 // `magi task done` (or the API's equivalent) can close a task with no
5113 // run of its own ever having succeeded - there is nothing here that
5114 // counts as "the attempt that finished it", so nothing is rewritten.
5115 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5116 let mut first = run_state(RunStatus::Blocked);
5117 first.id = "20260101-000000-sup5".to_owned();
5118 first.save().unwrap();
5119
5120 let mut t = task();
5121 t.runs = vec![first.id.clone()];
5122 t.status = TaskStatus::Done;
5123
5124 supersede_prior_runs(&t, &crate::run::home());
5125
5126 assert_eq!(
5127 RunState::load(&first.id).unwrap().status,
5128 RunStatus::Blocked,
5129 "a single-attempt task has no earlier run to supersede"
5130 );
5131 }
5132
5133 #[test]
5134 fn supersede_prior_runs_does_nothing_when_the_last_recorded_attempt_never_landed() {
5135 // `magi task done` (or the web/conductor equivalents) can close a
5136 // task in any status, including one whose *last* recorded attempt is
5137 // itself still `Blocked`/`Failed` - a manual merge magi's own loop
5138 // never watched, say. `runs.last()` being `Done`-adjacent is not
5139 // proof it actually succeeded, so nothing earlier may be relabelled
5140 // on its say-so alone.
5141 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5142 let mut first = run_state(RunStatus::Blocked);
5143 first.id = "20260101-000000-supb".to_owned();
5144 first.save().unwrap();
5145 let mut second = run_state(RunStatus::Failed);
5146 second.id = "20260101-000000-supc".to_owned();
5147 second.save().unwrap();
5148
5149 let mut t = task();
5150 t.runs = vec![first.id.clone(), second.id.clone()];
5151 t.status = TaskStatus::Done;
5152
5153 supersede_prior_runs(&t, &crate::run::home());
5154
5155 assert_eq!(
5156 RunState::load(&first.id).unwrap().status,
5157 RunStatus::Blocked,
5158 "the task's last attempt never landed, so there is nothing here \
5159 actually superseding it"
5160 );
5161 }
5162
5163 #[test]
5164 fn supersede_prior_runs_leaves_a_failed_or_verified_noop_attempt_as_is() {
5165 // Only `Blocked`/`Stalled` mean "sitting there waiting for a human
5166 // to look" - `Failed` and `VerifiedNoop` are already their own
5167 // terminal answers and must not be relabelled into a third one.
5168 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5169 let mut failed = run_state(RunStatus::Failed);
5170 failed.id = "20260101-000000-sup6".to_owned();
5171 failed.save().unwrap();
5172 let mut noop = run_state(RunStatus::VerifiedNoop);
5173 noop.id = "20260101-000000-sup7".to_owned();
5174 noop.save().unwrap();
5175 let mut winner = run_state(RunStatus::Ready);
5176 winner.id = "20260101-000000-sup8".to_owned();
5177 winner.save().unwrap();
5178
5179 let mut t = task();
5180 t.runs = vec![failed.id.clone(), noop.id.clone(), winner.id.clone()];
5181 t.status = TaskStatus::Done;
5182
5183 supersede_prior_runs(&t, &crate::run::home());
5184
5185 assert_eq!(
5186 RunState::load(&failed.id).unwrap().status,
5187 RunStatus::Failed
5188 );
5189 assert_eq!(
5190 RunState::load(&noop.id).unwrap().status,
5191 RunStatus::VerifiedNoop
5192 );
5193 }
5194
5195 fn approval_question(run: &str) -> ask::Question {
5196 ask::Question::new(
5197 run.to_owned(),
5198 land::APPROVAL_NODE.to_owned(),
5199 "land".to_owned(),
5200 "merge?".to_owned(),
5201 String::new(),
5202 vec!["merge".to_owned(), "hold".to_owned()],
5203 )
5204 }
5205
5206 #[test]
5207 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
5208 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5209 let mut state = run_state(RunStatus::Landing);
5210 state.id = "20260101-000000-fre1".to_owned();
5211 state.parked = true;
5212 state.save().unwrap();
5213 ask::Questions::open()
5214 .put(&mut approval_question(&state.id))
5215 .unwrap();
5216
5217 let mut t = task();
5218 t.runs.push(state.id.clone());
5219 assert_eq!(
5220 land_resume_state(&t),
5221 LandResume::StillWaiting,
5222 "nobody has answered and the timeout has not passed"
5223 );
5224 }
5225
5226 #[test]
5227 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
5228 // `ask::ask_and_wait`'s own deadline used to retire a question
5229 // nobody answered; land's approval bypasses that wait (see
5230 // `land::approval_gate`), so this is now the only place
5231 // `graph.answer_timeout` is enforced for a land approval at all.
5232 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
5233 let mut state = run_state(RunStatus::Landing);
5234 state.id = "20260101-000000-exp1".to_owned();
5235 state.parked = true;
5236 state.config.graph.answer_timeout = 60;
5237 state.save().unwrap();
5238
5239 let store = ask::Questions::open();
5240 let mut q = approval_question(&state.id);
5241 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
5242 store.put(&mut q).unwrap();
5243
5244 let mut t = task();
5245 t.runs.push(state.id.clone());
5246 assert_eq!(
5247 land_resume_state(&t),
5248 LandResume::Ready,
5249 "an expired question must not be waited on forever"
5250 );
5251
5252 let after = store.get(&q.id).unwrap();
5253 assert!(
5254 !after.status.open(),
5255 "the question is abandoned, not silently ignored"
5256 );
5257 assert!(
5258 after.resolution().is_none(),
5259 "an abandoned question is not read as a decision"
5260 );
5261 }
5262
5263 #[test]
5264 fn reclaim_settles_a_running_task_against_its_last_run() {
5265 let mut t = task();
5266 t.start("20260904-000000-4043".to_owned());
5267 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
5268 assert_eq!(
5269 t.status,
5270 TaskStatus::Done,
5271 "a run that actually finished must not stay `running` forever"
5272 );
5273 }
5274
5275 #[test]
5276 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
5277 // A blocked run with attempts left goes back to `Failed`, exactly as
5278 // it would from `attempt` itself - `reclaim` must not invent a second
5279 // policy for a task a daemon merely stopped without reporting.
5280 let mut t = task();
5281 t.start("20260904-000000-4043".to_owned());
5282 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
5283 assert_eq!(t.status, TaskStatus::Failed);
5284 assert!(t.status.runnable());
5285 }
5286
5287 #[test]
5288 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
5289 let mut t = task();
5290 t.start("20260904-000000-4043".to_owned());
5291 reclaim(&mut t, None, 2);
5292 assert_eq!(t.status, TaskStatus::Held);
5293 assert!(
5294 t.last_error
5295 .as_deref()
5296 .is_some_and(|e| e.contains("running")),
5297 "the operator needs to know why this task was held"
5298 );
5299 }
5300
5301 #[test]
5302 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
5303 let dir = tempfile::tempdir().unwrap();
5304 let queue = Queue::at(dir.path().to_path_buf());
5305
5306 // No run recorded, so this never has to touch `RunState::load`.
5307 let mut orphaned = task();
5308 orphaned.id = "20260904-000000-orph".to_owned();
5309 orphaned.status = TaskStatus::Running;
5310 orphaned.attempts = 1;
5311 queue.put(&mut orphaned).unwrap();
5312
5313 let mut alive = task();
5314 alive.id = "20260904-000000-live".to_owned();
5315 alive.status = TaskStatus::Running;
5316 alive.attempts = 1;
5317 queue.put(&mut alive).unwrap();
5318 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
5319
5320 let mut queued = task();
5321 queued.id = "20260904-000000-wait".to_owned();
5322 queue.put(&mut queued).unwrap();
5323
5324 let reclaimed = reclaim_orphaned_running(&queue, 2);
5325 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
5326
5327 assert_eq!(
5328 queue.get(&orphaned.id).unwrap().status,
5329 TaskStatus::Held,
5330 "nothing was driving it and there was no run to recover"
5331 );
5332 assert_eq!(
5333 queue.get(&alive.id).unwrap().status,
5334 TaskStatus::Running,
5335 "a live claim must protect the task it belongs to"
5336 );
5337 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
5338 }
5339
5340 /// Read a run.json back from an explicit `home`, the same way
5341 /// `reclaim_abandoned_runs` itself does - never through the
5342 /// process-global `RunState::load`, which this test's own `home` (an
5343 /// isolated tempdir, never pinned into the shared `OnceLock`) does not
5344 /// use at all.
5345 fn read_run_under(home: &Path, id: &str) -> RunState {
5346 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
5347 serde_json::from_str(&body).unwrap()
5348 }
5349
5350 #[test]
5351 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
5352 let dir = tempfile::tempdir().unwrap();
5353 let home = dir.path().to_path_buf();
5354 let now = Timestamp::now();
5355 let overrun_seat = || crate::run::ActiveSeat {
5356 node: "implement".to_owned(),
5357 started_at: now - jiff::SignedDuration::new(21_000, 0),
5358 timeout_secs: 3_600,
5359 attempt: 0,
5360 task: None,
5361 command: None,
5362 index: None,
5363 total: None,
5364 };
5365
5366 let mut dead = run_state(RunStatus::Implementing);
5367 dead.id = "20260101-000000-dead".to_owned();
5368 dead.active.insert("impl-A".to_owned(), overrun_seat());
5369 // A `driver_pid` the injected query below confirms gone outright —
5370 // `liveness` reads this as `Dead`, not merely "no daemon claims it".
5371 dead.driver_pid = Some(4242);
5372 dead.save_under(&home).unwrap();
5373
5374 // Same shape, but a live daemon's heartbeat names it: must be left
5375 // exactly alone, however far past its own timeout the seat sits.
5376 let mut alive = run_state(RunStatus::Implementing);
5377 alive.id = "20260101-000000-aliv".to_owned();
5378 alive.active.insert("impl-A".to_owned(), overrun_seat());
5379 alive.save_under(&home).unwrap();
5380 let mut status = Status::new();
5381 status.current = vec![Current {
5382 task: "20260101-000000-task".to_owned(),
5383 run: alive.id.clone(),
5384 }];
5385 write_status_to(&home.join("daemon.json"), &status).unwrap();
5386
5387 // The abandoned seat left an open question behind: nobody is left to
5388 // read an answer once the run is failed, and this must not wait for
5389 // some later daemon startup's own sweep to notice that.
5390 let questions = Questions::at(home.join("questions"));
5391 let mut q = ask::Question::new(
5392 dead.id.clone(),
5393 "implement".to_owned(),
5394 "impl-A".to_owned(),
5395 "Which storage backend?".to_owned(),
5396 String::new(),
5397 vec!["SQLite".to_owned(), "Redis".to_owned()],
5398 );
5399 questions.put(&mut q).unwrap();
5400
5401 let abandoned = reclaim_abandoned_runs_with(
5402 &home,
5403 now,
5404 |pid| if pid == 4242 { Some(false) } else { None },
5405 |_| panic!("a query answering Dead outright needs no identity corroboration"),
5406 );
5407 assert_eq!(abandoned, vec![dead.id.clone()]);
5408
5409 let reloaded = read_run_under(&home, &dead.id);
5410 assert_eq!(reloaded.status, RunStatus::Failed);
5411 assert!(reloaded.active.is_empty());
5412 assert!(
5413 !questions.get(&q.id).unwrap().status.open(),
5414 "the failed run's own open question must be settled in the same pass"
5415 );
5416
5417 let still_alive = read_run_under(&home, &alive.id);
5418 assert_eq!(
5419 still_alive.status,
5420 RunStatus::Implementing,
5421 "a live daemon's claim protects it"
5422 );
5423 assert!(!still_alive.active.is_empty());
5424 }
5425
5426 /// The exact shape a review round flagged as broken: `magi serve` running
5427 /// in this same `home` scans *every* run on disk, including a manual
5428 /// `magi review` / `magi run` this daemon never started and that
5429 /// therefore claims no heartbeat of its own. Before this scan asked
5430 /// `liveness` rather than just `is_working_on`, a manual run whose active
5431 /// seat merely ran a little past its own timeout — the CLI finishing up,
5432 /// its result still being collected — got wiped and failed by a daemon
5433 /// that had nothing to do with it, out from under a process that was
5434 /// still very much running.
5435 #[test]
5436 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
5437 let dir = tempfile::tempdir().unwrap();
5438 let home = dir.path().to_path_buf();
5439 let now = Timestamp::now();
5440
5441 let mut manual = run_state(RunStatus::Reviewing);
5442 manual.id = "20260101-000000-manl".to_owned();
5443 manual.active.insert(
5444 "review-1".to_owned(),
5445 crate::run::ActiveSeat {
5446 node: "review".to_owned(),
5447 started_at: now - jiff::SignedDuration::new(21_000, 0),
5448 timeout_secs: 3_600,
5449 attempt: 0,
5450 task: None,
5451 command: None,
5452 index: None,
5453 total: None,
5454 },
5455 );
5456 // Not claimed by any daemon (no `daemon.json` at all in this `home`),
5457 // but a real, still-running process: `liveness` must corroborate this
5458 // as `Live`, not read the missing daemon claim as death.
5459 manual.driver_pid = Some(4242);
5460 manual.driver_started_at = Some("2026-09-22T10:00:00Z".to_owned());
5461 manual.save_under(&home).unwrap();
5462
5463 let abandoned = reclaim_abandoned_runs_with(
5464 &home,
5465 now,
5466 |pid| if pid == 4242 { Some(true) } else { None },
5467 |pid| {
5468 if pid == 4242 {
5469 Some("2026-09-22T10:00:00Z".to_owned())
5470 } else {
5471 None
5472 }
5473 },
5474 );
5475 assert!(
5476 abandoned.is_empty(),
5477 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
5478 );
5479
5480 let reloaded = read_run_under(&home, &manual.id);
5481 assert_eq!(reloaded.status, RunStatus::Reviewing);
5482 assert!(!reloaded.active.is_empty());
5483 }
5484
5485 #[test]
5486 fn an_already_claimed_task_is_skipped_rather_than_failed() {
5487 let dir = tempfile::tempdir().unwrap();
5488 let queue = Queue::at(dir.path().to_path_buf());
5489 let mut only = task();
5490 queue.put(&mut only).unwrap();
5491
5492 let _elsewhere = queue.claim(&only.id).unwrap();
5493 let candidates = runnable(&queue);
5494 assert_eq!(candidates.len(), 1, "the task is still runnable");
5495 assert!(
5496 queue.claim(&candidates[0].id).is_err(),
5497 "the loop cannot take a claim somebody else holds"
5498 );
5499
5500 let after = queue.get(&only.id).unwrap();
5501 assert_eq!(after.status, TaskStatus::Queued);
5502 assert_eq!(
5503 after.attempts, 0,
5504 "losing the race is not an attempt at the task"
5505 );
5506 assert_eq!(after.last_error, None);
5507 }
5508
5509 #[test]
5510 fn the_status_file_round_trips_and_its_heartbeat_advances() {
5511 let dir = tempfile::tempdir().unwrap();
5512 let path = dir.path().join("daemon.json");
5513
5514 let mut status = Status::new();
5515 status.idle = false;
5516 status.completed = 7;
5517 status.current = vec![Current {
5518 task: "20260902-000000-t111".to_owned(),
5519 run: "20260902-000001-r111".to_owned(),
5520 }];
5521 write_status_to(&path, &status).unwrap();
5522 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5523 assert_eq!(first.schema, SCHEMA);
5524 assert_eq!(first.pid, std::process::id());
5525 assert!(!first.idle);
5526 assert_eq!(first.completed, 7);
5527 assert_eq!(first.current, status.current);
5528 assert!(
5529 !path.with_extension("json.tmp").exists(),
5530 "the temp file is renamed, not left behind"
5531 );
5532
5533 std::thread::sleep(Duration::from_millis(5));
5534 status.updated_at = Timestamp::now();
5535 status.polls = 3;
5536 write_status_to(&path, &status).unwrap();
5537 let second: Status =
5538 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
5539 assert!(
5540 second.updated_at > first.updated_at,
5541 "a reader can only detect staleness if the heartbeat moves"
5542 );
5543 assert_eq!(
5544 second.started_at, first.started_at,
5545 "the start time is not a heartbeat"
5546 );
5547 assert_eq!(second.polls, 3);
5548 }
5549
5550 #[test]
5551 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
5552 let dir = tempfile::tempdir().unwrap();
5553
5554 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
5555
5556 let mut status = Status::new();
5557 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
5558 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5559 let stale = read_status(dir.path()).unwrap();
5560 assert!(
5561 !stale.running(Timestamp::now()),
5562 "a minute without a heartbeat is a dead daemon, not a busy one"
5563 );
5564 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
5565
5566 status.updated_at = Timestamp::now();
5567 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5568 let fresh = read_status(dir.path()).unwrap();
5569 assert!(fresh.running(Timestamp::now()));
5570 }
5571
5572 #[test]
5573 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
5574 let dir = tempfile::tempdir().unwrap();
5575 let now = Timestamp::now();
5576 let mine = "20260903-080619-01c2";
5577
5578 assert!(
5579 !is_working_on(dir.path(), mine, now),
5580 "no status file means nobody is working on anything"
5581 );
5582
5583 let mut status = Status::new();
5584 status.current = vec![Current {
5585 task: "20260903-080340-0167".to_owned(),
5586 run: mine.to_owned(),
5587 }];
5588 status.updated_at = now;
5589 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5590 assert!(is_working_on(dir.path(), mine, now));
5591 assert!(
5592 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
5593 "a daemon busy with one run is not working on another"
5594 );
5595
5596 // A killed daemon stops writing heartbeats but leaves the file behind
5597 // naming the run it died in. That run must not be undeletable forever.
5598 status.updated_at = now - jiff::SignedDuration::from_secs(600);
5599 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5600 assert!(
5601 !is_working_on(dir.path(), mine, now),
5602 "a stale heartbeat is a dead daemon, so its run is a leftover"
5603 );
5604 }
5605
5606 #[test]
5607 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
5608 let dir = tempfile::tempdir().unwrap();
5609 let now = Timestamp::now();
5610
5611 assert!(
5612 !is_working_on_short(dir.path(), "01c2", now),
5613 "no status file means nobody is working on anything"
5614 );
5615
5616 let mut status = Status::new();
5617 status.current = vec![Current {
5618 task: "20260903-080340-0167".to_owned(),
5619 run: "20260903-080619-01c2".to_owned(),
5620 }];
5621 status.updated_at = now;
5622 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5623 assert!(
5624 is_working_on_short(dir.path(), "01c2", now),
5625 "the run's short id is the last block of its full id"
5626 );
5627 assert!(
5628 !is_working_on_short(dir.path(), "3cbf", now),
5629 "a daemon busy with one worktree bay is not working on another"
5630 );
5631 }
5632
5633 #[test]
5634 fn a_newer_status_file_still_yields_a_reading() {
5635 let dir = tempfile::tempdir().unwrap();
5636 // A field this build has never heard of must not turn the reading into
5637 // nothing at all; that is the whole reason the reader is permissive.
5638 std::fs::write(
5639 dir.path().join("daemon.json"),
5640 serde_json::json!({
5641 "schema": 2,
5642 "updated_at": Timestamp::now().to_string(),
5643 "idle": true,
5644 "surprise": { "nested": [1, 2, 3] },
5645 })
5646 .to_string(),
5647 )
5648 .unwrap();
5649
5650 let reading = read_status(dir.path()).expect("a forward-compatible read");
5651 assert!(reading.running(Timestamp::now()));
5652 assert!(reading.idle);
5653 assert!(reading.current.is_empty());
5654 }
5655
5656 #[test]
5657 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
5658 // A daemon started before `current` became a list keeps writing this
5659 // shape on every heartbeat until it is restarted. A rolling upgrade
5660 // - a newer `magi web` or `magi doctor` reading an older `magi
5661 // serve`'s heartbeat - must still see the run it is on, not "no
5662 // daemon" from a type mismatch failing the whole struct.
5663 let dir = tempfile::tempdir().unwrap();
5664 std::fs::write(
5665 dir.path().join("daemon.json"),
5666 serde_json::json!({
5667 "schema": 1,
5668 "pid": 4242,
5669 "updated_at": Timestamp::now().to_string(),
5670 "idle": false,
5671 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
5672 "completed": 3,
5673 "polls": 9,
5674 })
5675 .to_string(),
5676 )
5677 .unwrap();
5678
5679 let reading = read_status(dir.path()).expect("an older shape must still parse");
5680 assert!(reading.running(Timestamp::now()));
5681 assert_eq!(
5682 reading.current,
5683 vec![Current {
5684 task: "20260902-140501-aaaa".to_owned(),
5685 run: "20260902-140502-bbbb".to_owned(),
5686 }]
5687 );
5688 }
5689
5690 #[test]
5691 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
5692 let dir = tempfile::tempdir().unwrap();
5693 std::fs::write(
5694 dir.path().join("daemon.json"),
5695 serde_json::json!({
5696 "schema": 1,
5697 "updated_at": Timestamp::now().to_string(),
5698 "idle": true,
5699 "current": null,
5700 })
5701 .to_string(),
5702 )
5703 .unwrap();
5704 let with_null = read_status(dir.path()).expect("null must still parse");
5705 assert!(with_null.current.is_empty());
5706
5707 std::fs::write(
5708 dir.path().join("daemon.json"),
5709 serde_json::json!({
5710 "schema": 1,
5711 "updated_at": Timestamp::now().to_string(),
5712 "idle": true,
5713 })
5714 .to_string(),
5715 )
5716 .unwrap();
5717 let absent = read_status(dir.path()).expect("a missing field must still parse");
5718 assert!(absent.current.is_empty());
5719 }
5720
5721 #[test]
5722 fn a_task_without_a_repository_runs_in_the_daemons_default() {
5723 let fallback = Path::new("/default");
5724 let mut blank = task();
5725 blank.repo = PathBuf::new();
5726 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
5727 let mut dot = task();
5728 dot.repo = PathBuf::from(".");
5729 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
5730 assert_eq!(
5731 repo_for(&task(), fallback),
5732 PathBuf::from("/repo"),
5733 "a task that names a repository keeps it"
5734 );
5735 }
5736
5737 #[test]
5738 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
5739 // Three seats said out loud. What `solo` promises is one candidate
5740 // *whatever the config asks for*, so the contrast has to be a number
5741 // this test owns - it used to be `Config::default()`'s, which became
5742 // 1 when one implementation became the default and left the two
5743 // halves of this test asserting the same thing.
5744 let mut solo_cfg = Config::default();
5745 solo_cfg.graph.candidates = 3;
5746 let mut solo_task = task();
5747 solo_task.solo = true;
5748 apply_solo(&mut solo_cfg, &solo_task);
5749 assert_eq!(solo_cfg.graph.candidates, 1);
5750
5751 let mut plain_cfg = Config::default();
5752 plain_cfg.graph.candidates = 3;
5753 let plain_task = task();
5754 assert!(!plain_task.solo);
5755 apply_solo(&mut plain_cfg, &plain_task);
5756 assert_eq!(
5757 plain_cfg.graph.candidates, 3,
5758 "a task that did not ask to run alone keeps the config's candidates"
5759 );
5760 }
5761
5762 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
5763 QuotaLoss {
5764 seat: seat.into(),
5765 node: "judge".into(),
5766 at: at.parse().unwrap(),
5767 reset: reset.map(str::to_string),
5768 }
5769 }
5770
5771 #[test]
5772 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
5773 let old: Vec<QuotaLoss> = (1..=4)
5774 .map(|i| {
5775 loss(
5776 &format!("judge-{i}"),
5777 "2026-09-23T05:23:00Z",
5778 Some("2:40pm (Asia/Tokyo)"),
5779 )
5780 })
5781 .collect();
5782 let fresh = losses_this_attempt(&old, &old);
5783 assert!(fresh.is_empty());
5784 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
5785 // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
5786 }
5787
5788 #[test]
5789 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
5790 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
5791 let now = Timestamp::now();
5792 let mut after = old.clone();
5793 after.push(loss("judge-2", &now.to_string(), None));
5794 let fresh = losses_this_attempt(&old, &after);
5795 assert_eq!(fresh, vec![after[1].clone()]);
5796 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
5797 assert_eq!(
5798 until,
5799 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
5800 );
5801 }
5802
5803 #[test]
5804 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
5805 // `recover_stall` removes judge-1's loss and the retry then hits quota
5806 // again: the vector is the same length, so an index diff sees nothing.
5807 let before = vec![
5808 loss("judge-1", "2026-09-23T05:23:00Z", None),
5809 loss("judge-2", "2026-09-23T05:24:00Z", None),
5810 ];
5811 let after = vec![
5812 loss("judge-2", "2026-09-23T05:24:00Z", None),
5813 loss("judge-1", "2026-09-24T01:00:00Z", None),
5814 ];
5815 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
5816 }
5817
5818 #[test]
5819 fn merge_overrides_are_parsed_or_refused() {
5820 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
5821 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
5822 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
5823 assert!(merge_mode("squash").is_err());
5824 }
5825
5826 #[test]
5827 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
5828 let now = Timestamp::now();
5829 let fallback = Duration::from_secs(300);
5830 let cap = Duration::from_secs(1800);
5831
5832 // No reset hint at all: the fallback.
5833 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
5834
5835 // A reset ten minutes out, well inside the cap: waited for exactly.
5836 let soon = now + jiff::SignedDuration::from_secs(600);
5837 assert_eq!(
5838 quota_wait(Some(soon), now, fallback, cap),
5839 Duration::from_secs(600)
5840 );
5841
5842 // A reset already in the past is not trusted: the fallback, not a
5843 // zero or negative wait that would spin the loop right back around.
5844 let past = now - jiff::SignedDuration::from_secs(60);
5845 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
5846
5847 // A reset further out than the cap is trusted for direction but not
5848 // for magnitude: a parsing slip must not sleep the loop for a day.
5849 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
5850 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
5851 }
5852
5853 #[test]
5854 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
5855 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5856
5857 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
5858 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
5859
5860 // Same clock reading, but it has already gone by today: read as
5861 // tomorrow's, since the CLI would not still be reporting a limit past
5862 // its own stated reset.
5863 let already_past =
5864 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
5865 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
5866
5867 assert!(
5868 parse_reset_hint("session limit reached", now, now).is_none(),
5869 "free text with no recognised shape is not guessed at"
5870 );
5871 assert!(
5872 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
5873 "an unresolvable zone name is not guessed at either"
5874 );
5875 }
5876
5877 #[test]
5878 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
5879 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5880
5881 let at = parse_reset_hint(
5882 "You've hit your usage limit. Visit \
5883 https://chatgpt.com/codex/settings/usage to purchase more \
5884 credits or try again at Sep 19th, 2026 5:10 PM.",
5885 now,
5886 now,
5887 )
5888 .expect("the codex reset wording is a recognised shape");
5889 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
5890
5891 // The month is explicit, so a date already earlier in the same
5892 // sentence-implied year than `now` is trusted as written rather than
5893 // rolled forward a year the way the bracketed shape rolls a
5894 // same-day clock reading to tomorrow.
5895 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
5896 .expect("an explicit year needs no rollover");
5897 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
5898
5899 assert!(
5900 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
5901 "a two-digit year is not the documented shape and is not guessed at"
5902 );
5903 assert!(
5904 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
5905 "a four-letter month name is not the documented three-letter abbreviation"
5906 );
5907 assert!(
5908 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
5909 "an explicit zone on the dated shape is a format nobody has \
5910 documented, and is refused rather than guessed at as UTC"
5911 );
5912 }
5913
5914 #[test]
5915 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
5916 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
5917 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
5918
5919 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
5920 assert_eq!(at.as_second() - recorded.as_second(), 3769);
5921
5922 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
5923 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
5924
5925 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
5926 assert!(
5927 parse_reset_hint(bad, now, recorded).is_none(),
5928 "{bad:?} must not be guessed at"
5929 );
5930 }
5931 }
5932
5933 /// A loop whose queue lives in a temp tree and whose poll interval is far
5934 /// longer than the test's patience, so anything that waits out a poll
5935 /// instead of noticing the stop fails rather than merely being slow.
5936 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
5937 let config = dir.join("magi.toml");
5938 std::fs::write(
5939 &config,
5940 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
5941 )
5942 .unwrap();
5943 let opts = Opts {
5944 poll: Duration::from_secs(30),
5945 config: Some(config),
5946 // The explicit fixture config keeps startup cleanup from reading
5947 // machine configuration. This fictional repository likewise
5948 // keeps any best-effort git cleanup away from this checkout.
5949 repo: dir.join("repo"),
5950 ..Opts::default()
5951 };
5952 // The status file goes in a directory that does not exist yet, so its
5953 // creation is itself evidence the loop published one. `worktrees`
5954 // must be just as fictional: the janitor reclaims worktrees under it
5955 // for real, and a test that let it fall through to
5956 // `crate::run::default_worktree_root()` would have it reclaim
5957 // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
5958 // which is exactly what happened before this function took the
5959 // parameter at all.
5960 let home = dir.join("home");
5961 let worktrees = dir.join("wt");
5962 (
5963 opts,
5964 Queue::at(dir.join("queue")),
5965 home.join("daemon.json"),
5966 home,
5967 worktrees,
5968 )
5969 }
5970
5971 #[test]
5972 fn a_stop_is_idempotent_and_once_set_stays_set() {
5973 let stop = Stop::new();
5974 assert!(!stop.stopped());
5975
5976 stop.stop();
5977 assert!(stop.stopped());
5978 stop.stop();
5979 assert!(stop.stopped(), "a second stop is not a toggle");
5980
5981 let shared = stop.clone();
5982 assert!(
5983 shared.stopped(),
5984 "a clone is the same stop; that is how the loop and its caller share one"
5985 );
5986 }
5987
5988 #[test]
5989 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
5990 let stop = Stop::new();
5991 stop.enter();
5992 assert!(
5993 !stop.finishing(),
5994 "a busy loop nobody has asked to stop is just running"
5995 );
5996
5997 stop.stop();
5998 assert!(
5999 stop.finishing(),
6000 "a stop asked for mid-run has not landed until the run is settled"
6001 );
6002
6003 stop.exit();
6004 assert!(
6005 !stop.finishing(),
6006 "once the run is settled the stop has landed and there is nothing to finish"
6007 );
6008 }
6009
6010 #[test]
6011 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
6012 let stop = Stop::new();
6013 stop.enter();
6014 stop.enter();
6015 stop.stop();
6016 assert!(stop.finishing(), "two runs still in flight");
6017
6018 stop.exit();
6019 assert!(
6020 stop.finishing(),
6021 "one run finished, but a sibling is still working"
6022 );
6023
6024 stop.exit();
6025 assert!(
6026 !stop.finishing(),
6027 "the last run out is what actually lands the stop"
6028 );
6029 }
6030
6031 #[tokio::test]
6032 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
6033 let dir = tempfile::tempdir().unwrap();
6034 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6035 let stop = Stop::new();
6036 stop.stop();
6037
6038 let began = std::time::Instant::now();
6039 tokio::time::timeout(
6040 Duration::from_secs(2),
6041 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6042 )
6043 .await
6044 .expect("a stopped loop must return, not sit out its poll interval")
6045 .expect("the loop's own setup and teardown must not fail");
6046 assert!(
6047 began.elapsed() < opts.poll,
6048 "returned only after {:?}, which is a poll interval, not a stop",
6049 began.elapsed()
6050 );
6051 }
6052
6053 #[tokio::test]
6054 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
6055 let dir = tempfile::tempdir().unwrap();
6056 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6057 let stop = Stop::new();
6058
6059 // Asked for after the loop is already parked on its empty queue, which
6060 // is the case an operator tapping stop on a phone actually hits.
6061 let asker = {
6062 let stop = stop.clone();
6063 tokio::spawn(async move {
6064 tokio::time::sleep(Duration::from_millis(20)).await;
6065 stop.stop();
6066 })
6067 };
6068
6069 let began = std::time::Instant::now();
6070 tokio::time::timeout(
6071 Duration::from_secs(2),
6072 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6073 )
6074 .await
6075 .expect("a stop asked for while idle must wake the wait")
6076 .expect("the loop's own setup and teardown must not fail");
6077 asker.await.unwrap();
6078 assert!(
6079 began.elapsed() < opts.poll,
6080 "returned only after {:?}, so the stop waited on the sleep",
6081 began.elapsed()
6082 );
6083 }
6084
6085 #[tokio::test]
6086 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
6087 let dir = tempfile::tempdir().unwrap();
6088 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6089 let stop = Stop::new();
6090 stop.stop();
6091
6092 tokio::time::timeout(
6093 Duration::from_secs(2),
6094 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6095 )
6096 .await
6097 .expect("a stopped loop must return")
6098 .expect("the loop's own setup and teardown must not fail");
6099
6100 assert!(
6101 home.is_dir(),
6102 "the loop did publish a status file, so its removal is the teardown and not an absence"
6103 );
6104 assert!(
6105 !status_file.exists(),
6106 "a stopped loop clears its status file"
6107 );
6108 assert!(
6109 read_status(&home).is_none(),
6110 "a reader must see no daemon at all, not a heartbeat that merely stopped"
6111 );
6112 }
6113
6114 #[tokio::test]
6115 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
6116 let dir = tempfile::tempdir().unwrap();
6117 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
6118 opts.once = true;
6119
6120 let mut settled = RunState::new(
6121 dir.path().join("repo"),
6122 "main".to_owned(),
6123 "abc1234".to_owned(),
6124 "fixture".to_owned(),
6125 Config::default(),
6126 );
6127 settled.status = RunStatus::Ready;
6128 let run_dir = home.join("runs").join(&settled.id);
6129 std::fs::create_dir_all(&run_dir).unwrap();
6130 std::fs::write(
6131 run_dir.join("run.json"),
6132 serde_json::to_string_pretty(&settled).unwrap(),
6133 )
6134 .unwrap();
6135 let questions = Questions::at(home.join("questions"));
6136 let mut question = ask::Question::new(
6137 settled.id.clone(),
6138 "review".to_owned(),
6139 "reviewer-1".to_owned(),
6140 "Continue?".to_owned(),
6141 String::new(),
6142 Vec::new(),
6143 );
6144 questions.put(&mut question).unwrap();
6145
6146 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
6147 .await
6148 .unwrap();
6149
6150 assert_eq!(
6151 questions.get(&question.id).unwrap().status,
6152 ask::QuestionStatus::Abandoned,
6153 "an empty --once drain still performs startup question cleanup"
6154 );
6155 }
6156
6157 #[test]
6158 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
6159 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6160
6161 assert!(
6162 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
6163 "never checked before: due at once"
6164 );
6165
6166 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
6167 assert!(
6168 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
6169 "well inside the interval: not due yet"
6170 );
6171
6172 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
6173 assert!(
6174 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
6175 "exactly at the edge: not yet due, same convention as `clean::due`"
6176 );
6177
6178 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
6179 assert!(
6180 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
6181 "past the interval: due again"
6182 );
6183 }
6184
6185 /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
6186 /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
6187 /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
6188 /// and the congestion test below both need, and must not drift apart.
6189 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
6190 let config = dir.join("magi.toml");
6191 // A literal (single-quoted) TOML string, not a basic one: the cache
6192 // path is a Windows path full of backslashes, and a basic string
6193 // would have TOML try to interpret `\U` (from `\Users\...`) as a
6194 // Unicode escape and fail to parse - the same trap `magi.toml`'s own
6195 // `{{ vars.cache }}` rendering documents.
6196 std::fs::write(
6197 &config,
6198 format!(
6199 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
6200 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
6201 cache_dir.display()
6202 ),
6203 )
6204 .unwrap();
6205 Opts {
6206 config: Some(config),
6207 repo: dir.join("repo"),
6208 ..Opts::default()
6209 }
6210 }
6211
6212 #[tokio::test]
6213 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
6214 let dir = tempfile::tempdir().unwrap();
6215 let home = dir.path().join("home");
6216 let cache_dir = dir.path().join("cache");
6217 std::fs::create_dir_all(&cache_dir).unwrap();
6218 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
6219 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
6220
6221 // Nobody has asked this daemon to stop, which is the ordinary case;
6222 // the skip that a stop buys is asserted by its own test below.
6223 let running = Stop::new();
6224 let mut last_checked = None;
6225 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6226 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
6227 .await;
6228 assert_eq!(
6229 crate::disk::dir_size(&cache_dir),
6230 0,
6231 "over the cap on the first check ever: pruned at once, no idle queue required"
6232 );
6233 assert_eq!(last_checked, Some(t0));
6234
6235 // A fresh oversized file lands, but the next check is not due yet.
6236 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
6237 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
6238 maybe_prune_cache_between_runs(
6239 &opts.repo,
6240 &opts,
6241 &home,
6242 &running,
6243 &mut last_checked,
6244 too_soon,
6245 )
6246 .await;
6247 assert_eq!(
6248 crate::disk::dir_size(&cache_dir),
6249 10,
6250 "too soon since the last check: left alone rather than rescanned every call"
6251 );
6252 assert_eq!(
6253 last_checked,
6254 Some(t0),
6255 "an idle check does not reset the clock"
6256 );
6257
6258 // Once the interval elapses, the same oversized cache is caught again.
6259 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
6260 maybe_prune_cache_between_runs(
6261 &opts.repo,
6262 &opts,
6263 &home,
6264 &running,
6265 &mut last_checked,
6266 due_again,
6267 )
6268 .await;
6269 assert_eq!(
6270 crate::disk::dir_size(&cache_dir),
6271 0,
6272 "due again: pruned back under the cap"
6273 );
6274 }
6275
6276 /// A stop must not queue behind housekeeping. The prune below is a
6277 /// synchronous walk of the whole cache with no await point in it, so a
6278 /// loop that entered it could not get back to its own `stopped()` test
6279 /// until the walk finished - and because no run is in flight at this
6280 /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
6281 /// the stop had already landed. The idle branch has always made this same
6282 /// check before reaching `janitor`; the between-runs path makes it too.
6283 #[tokio::test]
6284 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
6285 let dir = tempfile::tempdir().unwrap();
6286 let home = dir.path().join("home");
6287 let cache_dir = dir.path().join("cache");
6288 std::fs::create_dir_all(&cache_dir).unwrap();
6289 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
6290 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
6291
6292 let stop = Stop::new();
6293 stop.stop();
6294 assert!(
6295 !stop.finishing(),
6296 "no run is in flight at a between-runs boundary, so nothing else \
6297 would tell the operator this stop had not taken effect yet"
6298 );
6299
6300 let mut last_checked = None;
6301 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
6302 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
6303 .await;
6304 assert_eq!(
6305 crate::disk::dir_size(&cache_dir),
6306 10,
6307 "over its cap, and due for the first check ever, but a stop outranks \
6308 it: the cap is a standing policy the next start measures again"
6309 );
6310 assert_eq!(
6311 last_checked, None,
6312 "a check that never happened must not claim the interval"
6313 );
6314 }
6315
6316 /// The regression this whole change exists for: gate timeouts on runs
6317 /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
6318 /// GiB against a 10 GiB cap, because the operator's queue never had a
6319 /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
6320 /// `janitor` pass.
6321 ///
6322 /// Reproduced here with a task whose repository is never created:
6323 /// `Runner::start` fails at `git::toplevel` in a few milliseconds,
6324 /// spawning no agent CLI, so the task keeps failing and re-queuing
6325 /// (`Task::fail` with attempts still under the budget leaves it
6326 /// `Failed`, which `TaskStatus::runnable` still offers) for as long as
6327 /// the loop keeps polling - exactly the "queue with no idle moment"
6328 /// this task describes, produced without a real competition.
6329 #[tokio::test]
6330 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
6331 let dir = tempfile::tempdir().unwrap();
6332 let cache_dir = dir.path().join("cache");
6333 std::fs::create_dir_all(&cache_dir).unwrap();
6334 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
6335
6336 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
6337 opts.poll = Duration::from_millis(20);
6338 opts.max_attempts = 1_000;
6339
6340 let queue = Queue::at(dir.path().join("queue"));
6341 let mut t = Task::new(
6342 "x".to_owned(),
6343 "x".to_owned(),
6344 opts.repo.clone(),
6345 Source::Human,
6346 );
6347 queue.put(&mut t).unwrap();
6348
6349 let home = dir.path().join("home");
6350 let worktrees = dir.path().join("wt");
6351 let status_file = home.join("daemon.json");
6352 let stop = Stop::new();
6353 let stopper = {
6354 let stop = stop.clone();
6355 tokio::spawn(async move {
6356 tokio::time::sleep(Duration::from_millis(400)).await;
6357 stop.stop();
6358 })
6359 };
6360
6361 tokio::time::timeout(
6362 Duration::from_secs(10),
6363 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
6364 )
6365 .await
6366 .expect("the loop must not hang on a queue that keeps producing failing work")
6367 .expect("the loop's own setup and teardown must not fail");
6368 stopper.await.unwrap();
6369
6370 let after = queue.get(&t.id).unwrap();
6371 assert!(
6372 after.attempts >= 2,
6373 "the harness must actually have retried more than once, or this is not \
6374 exercising a busy queue at all (got {} attempt(s))",
6375 after.attempts
6376 );
6377 assert!(
6378 after.status.runnable(),
6379 "still under its attempt budget: the queue never reached a natural idle \
6380 on its own, only the external stop ended the test"
6381 );
6382
6383 assert_eq!(
6384 crate::disk::dir_size(&cache_dir),
6385 0,
6386 "an oversized cache must not be left to grow unboundedly just because the \
6387 queue kept the loop busy the whole time"
6388 );
6389 }
6390
6391 #[test]
6392 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
6393 let dir = tempfile::tempdir().unwrap();
6394 let queue = Queue::at(dir.path().join("queue"));
6395 let questions = Questions::at(dir.path().join("questions"));
6396 let mut task = task();
6397 queue.put(&mut task).unwrap();
6398
6399 let mut task_question = ask::Question::new(
6400 task.id.clone(),
6401 crate::conduct::NODE.to_owned(),
6402 "conduct".to_owned(),
6403 "Which backend?".to_owned(),
6404 String::new(),
6405 Vec::new(),
6406 );
6407 questions.put(&mut task_question).unwrap();
6408 task.block(vec![task_question.id.clone()], None);
6409 queue.put(&mut task).unwrap();
6410
6411 let mut run_question = ask::Question::new(
6412 "20260101-000000-run1".to_owned(),
6413 "review".to_owned(),
6414 "reviewer-1".to_owned(),
6415 "Run question".to_owned(),
6416 String::new(),
6417 Vec::new(),
6418 );
6419 questions.put(&mut run_question).unwrap();
6420
6421 // A question from another node whose `run` happens to equal this
6422 // task's id — the same field, filled in for an unrelated reason. Only
6423 // `crate::conduct::NODE` questions use `run` as a task id; this one
6424 // must never be touched by this reconciliation, even after release.
6425 let mut coincidental = ask::Question::new(
6426 task.id.clone(),
6427 "review".to_owned(),
6428 "reviewer-1".to_owned(),
6429 "Unrelated review question".to_owned(),
6430 String::new(),
6431 Vec::new(),
6432 );
6433 questions.put(&mut coincidental).unwrap();
6434
6435 reconcile_task_questions(&queue, &questions);
6436 assert!(questions.get(&task_question.id).unwrap().status.open());
6437 assert!(questions.get(&run_question.id).unwrap().status.open());
6438 assert!(questions.get(&coincidental.id).unwrap().status.open());
6439
6440 task.release();
6441 queue.put(&mut task).unwrap();
6442 reconcile_task_questions(&queue, &questions);
6443 assert_eq!(
6444 questions.get(&task_question.id).unwrap().status,
6445 ask::QuestionStatus::Abandoned
6446 );
6447 assert!(
6448 questions.get(&run_question.id).unwrap().status.open(),
6449 "run questions remain the run janitor's responsibility"
6450 );
6451 assert!(
6452 questions.get(&coincidental.id).unwrap().status.open(),
6453 "a non-conductor question must not be abandoned just because its \
6454 run id coincides with a task id"
6455 );
6456 }
6457
6458 #[test]
6459 fn a_freshly_started_running_task_is_never_stalled() {
6460 let dir = tempfile::tempdir().unwrap();
6461 let mut t = task();
6462 t.start("run-1".to_owned());
6463 // `updated_at` is `Timestamp::now()`, left alone: no live daemon
6464 // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
6465 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
6466 }
6467
6468 #[test]
6469 fn a_long_running_task_with_no_live_daemon_is_stalled() {
6470 let dir = tempfile::tempdir().unwrap();
6471 let mut t = task();
6472 t.start("run-1".to_owned());
6473 t.updated_at = Timestamp::now()
6474 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6475 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
6476 assert_eq!(
6477 stalled_tasks(
6478 &Queue::at(dir.path().join("q")),
6479 dir.path(),
6480 Timestamp::now()
6481 )
6482 .len(),
6483 0,
6484 "the task was never written to this queue"
6485 );
6486 }
6487
6488 #[test]
6489 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
6490 let dir = tempfile::tempdir().unwrap();
6491 let mut t = task();
6492 t.id = "20260903-080340-0167".to_owned();
6493 t.start("20260903-080619-01c2".to_owned());
6494 t.updated_at = Timestamp::now()
6495 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
6496
6497 let mut status = Status::new();
6498 status.current = vec![Current {
6499 task: t.id.clone(),
6500 run: "20260903-080619-01c2".to_owned(),
6501 }];
6502 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
6503
6504 assert!(
6505 !is_stalled(&t, dir.path(), Timestamp::now()),
6506 "a live daemon's own heartbeat rules out stalled, however long the task has run"
6507 );
6508 }
6509
6510 /// Rewrite a task's `updated_at` on disk directly, bypassing
6511 /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
6512 /// a fixture look like it has genuinely been `running` for a while.
6513 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
6514 let path = queue.path_of(id);
6515 let body = std::fs::read_to_string(&path).unwrap();
6516 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
6517 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
6518 v["updated_at"] = serde_json::Value::String(old.to_string());
6519 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
6520 }
6521
6522 #[test]
6523 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
6524 // The realistic `poll()` ordering, not `is_stalled` in isolation:
6525 // `reclaim_orphaned_running` runs first, on every poll, and settles
6526 // any `running` task whose claim it can actually take. For most
6527 // crashes that is immediate - a dead pid is proof enough for
6528 // `sweep_stale_claims` to drop the lock the same tick, and the very
6529 // next claim attempt succeeds. But a lock whose pid cannot be parsed
6530 // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
6531 // `sweep_stale_claims`'s own doc), so the lock - and the claim
6532 // failure behind it - can legitimately outlive many polls. This is
6533 // exactly the gap `stalled_tasks` exists to surface well before that
6534 // six-hour sweep would: reclaim leaves the task `running`, and it
6535 // must still reach the conductor as stalled.
6536 let dir = tempfile::tempdir().unwrap();
6537 let queue = Queue::at(dir.path().join("queue"));
6538 let home = dir.path().join("home");
6539
6540 let mut t = task();
6541 t.id = "20260101-000001-lock".to_owned();
6542 t.start("run-1".to_owned());
6543 queue.put(&mut t).unwrap();
6544 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6545 std::fs::write(
6546 dir.path().join("queue").join(format!("{}.lock", t.id)),
6547 "not a pid",
6548 )
6549 .unwrap();
6550
6551 let now = Timestamp::now();
6552 assert!(
6553 reclaim_orphaned_running(&queue, 2).is_empty(),
6554 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
6555 and reclaim must leave the task alone"
6556 );
6557 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
6558
6559 let stalled = stalled_tasks(&queue, &home, now);
6560 assert_eq!(
6561 stalled.len(),
6562 1,
6563 "reclaim's inability to claim it yet must not hide it from the conductor"
6564 );
6565 assert_eq!(stalled[0].id, t.id);
6566 }
6567
6568 #[test]
6569 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
6570 let dir = tempfile::tempdir().unwrap();
6571 crate::run::set_home(dir.path().join("run-home"));
6572 let queue = Queue::at(dir.path().join("queue"));
6573 let home = dir.path().join("home");
6574 let questions = Questions::at(dir.path().join("questions"));
6575
6576 let mut t = task();
6577 t.id = "20260101-000003-dead".to_owned();
6578 t.start("missing-run".to_owned());
6579 queue.put(&mut t).unwrap();
6580 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
6581
6582 // This is the real poll ordering: retain the deterministic stalled
6583 // input before a claim proves the owner is gone and reclaims it.
6584 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6585 assert_eq!(
6586 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
6587 [&t.id]
6588 );
6589 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
6590 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
6591
6592 // Reclaim drops its guard before conductor decisions are applied, so
6593 // the decision for the captured stalled input has a real write path.
6594 crate::conduct::apply(
6595 &queue,
6596 &questions,
6597 &crate::conduct::Verdict {
6598 decisions: vec![crate::conduct::Decision {
6599 id: t.id.clone(),
6600 recovery: Some(crate::conduct::Recovery::Requeue),
6601 ..crate::conduct::Decision::default()
6602 }],
6603 },
6604 )
6605 .unwrap();
6606 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
6607 }
6608
6609 #[test]
6610 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
6611 let dir = tempfile::tempdir().unwrap();
6612 let queue = Queue::at(dir.path().join("queue"));
6613 let home = dir.path().join("home");
6614
6615 let mut fresh = task();
6616 fresh.id = "20260101-000001-aaaa".to_owned();
6617 fresh.start("run-1".to_owned());
6618 queue.put(&mut fresh).unwrap();
6619
6620 let mut old = task();
6621 old.id = "20260101-000002-bbbb".to_owned();
6622 old.start("run-2".to_owned());
6623 queue.put(&mut old).unwrap();
6624 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
6625
6626 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
6627 assert_eq!(stalled.len(), 1);
6628 assert_eq!(stalled[0].id, old.id);
6629 }
6630
6631 #[test]
6632 fn queued_and_finished_task_views_partition_by_status() {
6633 let dir = tempfile::tempdir().unwrap();
6634 let queue = Queue::at(dir.path().join("queue"));
6635
6636 let mut queued = task();
6637 queued.id = "20260101-000001-aaaa".to_owned();
6638 queue.put(&mut queued).unwrap();
6639
6640 let mut failed = task();
6641 failed.id = "20260101-000002-bbbb".to_owned();
6642 failed.start("run-1".to_owned());
6643 failed.fail("gate red", 5);
6644 queue.put(&mut failed).unwrap();
6645
6646 let mut held = task();
6647 held.id = "20260101-000003-cccc".to_owned();
6648 held.hold_machine(None);
6649 queue.put(&mut held).unwrap();
6650
6651 let mut running = task();
6652 running.id = "20260101-000004-dddd".to_owned();
6653 running.start("run-2".to_owned());
6654 queue.put(&mut running).unwrap();
6655
6656 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
6657 assert_eq!(queued_ids, [queued.id.clone()]);
6658
6659 let mut finished_ids: Vec<String> =
6660 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
6661 finished_ids.sort_unstable();
6662 let mut want = vec![failed.id.clone(), held.id.clone()];
6663 want.sort_unstable();
6664 assert_eq!(finished_ids, want);
6665 }
6666
6667 #[test]
6668 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
6669 let dir = tempfile::tempdir().unwrap();
6670 let queue = Queue::at(dir.path().join("queue"));
6671 let questions = ask::Questions::at(dir.path().join("questions"));
6672
6673 let mut dep = task();
6674 dep.id = "20260101-000001-dep0".to_owned();
6675 dep.succeed();
6676 queue.put(&mut dep).unwrap();
6677
6678 let mut still_going = task();
6679 still_going.id = "20260101-000002-dep1".to_owned();
6680 queue.put(&mut still_going).unwrap();
6681
6682 let mut blocked = task();
6683 blocked.id = "20260101-000003-main".to_owned();
6684 blocked.block(
6685 vec![dep.id.clone(), still_going.id.clone()],
6686 Some("waits on both".to_owned()),
6687 );
6688 queue.put(&mut blocked).unwrap();
6689
6690 resolve_blockers(&queue, &questions);
6691
6692 let after = queue.get(&blocked.id).unwrap();
6693 assert_eq!(
6694 after.status,
6695 TaskStatus::Blocked,
6696 "one dependency is still outstanding"
6697 );
6698 assert_eq!(after.blocked_by, [still_going.id.clone()]);
6699 }
6700
6701 #[test]
6702 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
6703 let dir = tempfile::tempdir().unwrap();
6704 let queue = Queue::at(dir.path().join("queue"));
6705 let questions = ask::Questions::at(dir.path().join("questions"));
6706
6707 let mut q = crate::ask::Question::new(
6708 "20260101-000001-main".to_owned(),
6709 crate::conduct::NODE.to_owned(),
6710 "conduct".to_owned(),
6711 "Which backend?".to_owned(),
6712 String::new(),
6713 Vec::new(),
6714 );
6715 questions.put(&mut q).unwrap();
6716 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
6717 .unwrap();
6718 questions.put(&mut q).unwrap();
6719
6720 let mut blocked = task();
6721 blocked.id = "20260101-000001-main".to_owned();
6722 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
6723 queue.put(&mut blocked).unwrap();
6724
6725 resolve_blockers(&queue, &questions);
6726
6727 let after = queue.get(&blocked.id).unwrap();
6728 assert_eq!(
6729 after.status,
6730 TaskStatus::Queued,
6731 "the only blocker resolved"
6732 );
6733 assert_eq!(after.answers.len(), 1);
6734 assert_eq!(after.answers[0].question, "Which backend?");
6735 assert_eq!(after.answers[0].answer, "SQLite");
6736
6737 // And the run this task starts next is told about it.
6738 let instruction = instruction_for(&after);
6739 assert!(instruction.contains("Which backend?"));
6740 assert!(instruction.contains("SQLite"));
6741 }
6742
6743 #[test]
6744 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
6745 // Reproduces the reported bug (task 3958): a task held out of
6746 // attempts, blocked on a `crate::conduct` follow-up question, must
6747 // come back `held` once that question is answered - never `queued`,
6748 // whatever the answer said - or it silently re-enters the
6749 // competition queue with its attempts already exhausted.
6750 let dir = tempfile::tempdir().unwrap();
6751 let queue = Queue::at(dir.path().join("queue"));
6752 let questions = ask::Questions::at(dir.path().join("questions"));
6753
6754 let mut q = crate::ask::Question::new(
6755 "20260101-000001-main".to_owned(),
6756 crate::conduct::NODE.to_owned(),
6757 "conduct".to_owned(),
6758 "How should this be handled?".to_owned(),
6759 String::new(),
6760 Vec::new(),
6761 );
6762 questions.put(&mut q).unwrap();
6763 q.answer(crate::ask::Answer::Text(
6764 "leave it held, a human will look at it later".to_owned(),
6765 ))
6766 .unwrap();
6767 questions.put(&mut q).unwrap();
6768
6769 let mut held = task();
6770 held.id = "20260101-000001-main".to_owned();
6771 held.hold_machine(Some("out of attempts".to_owned()));
6772 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
6773 queue.put(&mut held).unwrap();
6774
6775 resolve_blockers(&queue, &questions);
6776
6777 let after = queue.get(&held.id).unwrap();
6778 assert_eq!(after.status, TaskStatus::Held);
6779 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
6780 assert_eq!(
6781 after.answers[0].answer,
6782 "leave it held, a human will look at it later"
6783 );
6784 }
6785
6786 #[test]
6787 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
6788 // Reproduces the reported bug: a task blocked on a task id that was
6789 // removed (`magi task rm`, or deleted by hand) can never see that id
6790 // reach `Done`, so the ordinary per-id loop has nothing to notice and
6791 // would otherwise leave the task `blocked` forever with no way for an
6792 // operator to find out why.
6793 let dir = tempfile::tempdir().unwrap();
6794 let queue = Queue::at(dir.path().join("queue"));
6795 let questions = ask::Questions::at(dir.path().join("questions"));
6796
6797 let mut still_going = task();
6798 still_going.id = "20260101-000002-dep1".to_owned();
6799 queue.put(&mut still_going).unwrap();
6800
6801 let mut blocked = task();
6802 blocked.id = "20260101-000003-main".to_owned();
6803 blocked.block(
6804 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
6805 Some("waits on both".to_owned()),
6806 );
6807 queue.put(&mut blocked).unwrap();
6808
6809 resolve_blockers(&queue, &questions);
6810
6811 let after = queue.get(&blocked.id).unwrap();
6812 assert_eq!(
6813 after.status,
6814 TaskStatus::Held,
6815 "a missing dependency must not leave the task blocked forever"
6816 );
6817 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
6818 assert!(after.blocked_by.is_empty());
6819 let reason = after.hold_reason.as_deref().unwrap_or_default();
6820 assert!(
6821 reason.contains("20260101-000001-gone"),
6822 "the missing id must be named so an operator can tell what happened: {reason}"
6823 );
6824 assert!(
6825 reason.contains(&still_going.id),
6826 "the still-valid dependency must not silently vanish from the record: {reason}"
6827 );
6828 }
6829
6830 #[test]
6831 fn instruction_for_is_unchanged_without_any_answers() {
6832 let t = task();
6833 assert_eq!(instruction_for(&t), t.instruction);
6834 }
6835
6836 #[test]
6837 fn resumed_instruction_is_unchanged_without_any_answers() {
6838 let t = task();
6839 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
6840 }
6841
6842 #[test]
6843 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
6844 let mut t = task();
6845 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6846 // The run's own instruction on disk predates the answer: it is the
6847 // plain original text `Runner::start` saved before the operator was
6848 // ever asked anything.
6849 let old = t.instruction.clone();
6850
6851 let refreshed = resumed_instruction(&old, &t);
6852 assert!(refreshed.starts_with(&old), "the original text is kept");
6853 assert!(refreshed.contains("Which backend?"));
6854 assert!(refreshed.contains("SQLite"));
6855 }
6856
6857 #[test]
6858 fn resumed_instruction_keeps_an_original_answers_heading() {
6859 let mut t = task();
6860 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
6861 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6862
6863 let refreshed = resumed_instruction(&t.instruction, &t);
6864
6865 assert!(
6866 refreshed.starts_with(&t.instruction),
6867 "an answers heading in the original instruction is not the appended block"
6868 );
6869 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
6870 assert!(refreshed.contains("Which backend?"));
6871 assert!(refreshed.contains("SQLite"));
6872
6873 let repeated = resumed_instruction(&refreshed, &t);
6874 assert_eq!(
6875 repeated, refreshed,
6876 "only the final appended block is refreshed"
6877 );
6878 }
6879
6880 #[test]
6881 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
6882 let mut t = task();
6883 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6884
6885 // A first resume appends the block; a second resume of the same run,
6886 // with no new answer in between, must reproduce exactly the same
6887 // text rather than appending the block a second time.
6888 let once = resumed_instruction(&t.instruction, &t);
6889 let twice = resumed_instruction(&once, &t);
6890 assert_eq!(once, twice);
6891 assert_eq!(once.matches("Which backend?").count(), 1);
6892
6893 // A later answer replaces the block wholesale rather than growing it.
6894 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
6895 let refreshed = resumed_instruction(&once, &t);
6896 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
6897 assert!(refreshed.contains("Which backend?"));
6898 assert!(refreshed.contains("Which cache?"));
6899 }
6900
6901 #[test]
6902 fn prepare_instruction_covers_all_three_starters() {
6903 let mut t = task();
6904 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6905
6906 // Start: a fresh run gets the task text plus every answer so far —
6907 // exactly `instruction_for`.
6908 assert_eq!(
6909 prepare_instruction(&Starter::Start, None, &t),
6910 Some(instruction_for(&t))
6911 );
6912
6913 // Resume: the run's prior instruction is refreshed with the answer,
6914 // not discarded and not left stale.
6915 let old = t.instruction.clone();
6916 assert_eq!(
6917 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
6918 Some(resumed_instruction(&old, &t))
6919 );
6920
6921 // Review: a review-only pass builds its own instruction from the
6922 // branch's history in `crate::graph`, with no task statement at all -
6923 // this boundary must leave it alone.
6924 assert_eq!(
6925 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
6926 None
6927 );
6928 }
6929
6930 #[test]
6931 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
6932 assert_eq!(
6933 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
6934 Starter::Review("magi/eba2/A".to_owned())
6935 );
6936 }
6937
6938 #[test]
6939 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
6940 assert_eq!(
6941 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
6942 Starter::Start,
6943 "a vanished review branch must not fall back to resuming the old run either"
6944 );
6945 }
6946
6947 #[test]
6948 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
6949 assert_eq!(
6950 choose_starter(None, false, Some("some-run")),
6951 Starter::Resume("some-run".to_owned())
6952 );
6953 assert_eq!(choose_starter(None, false, None), Starter::Start);
6954 }
6955
6956 #[test]
6957 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
6958 let mut released = task();
6959 released.start("stalled-run".to_owned());
6960 released.requeue();
6961 let unfinished = (!released.fresh_start)
6962 .then(|| Some("stalled-run".to_owned()))
6963 .flatten();
6964 assert_eq!(
6965 choose_starter(None, false, unfinished.as_deref()),
6966 Starter::Start,
6967 "release keeps run history but must not resume it"
6968 );
6969 assert_eq!(released.runs, ["stalled-run"]);
6970 }
6971
6972 #[test]
6973 fn an_ordinary_release_keeps_a_resumable_run_available() {
6974 let mut released = task();
6975 released.start("stalled-run".to_owned());
6976 released.release();
6977 let unfinished = (!released.fresh_start)
6978 .then(|| Some("stalled-run".to_owned()))
6979 .flatten();
6980 assert_eq!(
6981 choose_starter(None, false, unfinished.as_deref()),
6982 Starter::Resume("stalled-run".to_owned()),
6983 "manual release must preserve the normal resume path"
6984 );
6985 }
6986
6987 #[test]
6988 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
6989 let mut state = run_state(RunStatus::Blocked);
6990 state.config.graph.review_rounds = 3;
6991 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
6992 assert!(exhausted_review_budget(&state));
6993
6994 // One round still unused: resuming can still ask a reviewer something.
6995 state.reviews.pop();
6996 assert!(!exhausted_review_budget(&state));
6997
6998 // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
6999 // count: only a `Blocked` run re-enters the review loop on resume.
7000 let mut stalled = run_state(RunStatus::Stalled);
7001 stalled.config.graph.review_rounds = 1;
7002 stalled.reviews = vec![review_round(1)];
7003 assert!(!exhausted_review_budget(&stalled));
7004 }
7005
7006 fn review_round(round: usize) -> crate::run::ReviewRound {
7007 crate::run::ReviewRound {
7008 round,
7009 head: "deadbeef".to_owned(),
7010 verified_head: None,
7011 verified_at: None,
7012 reviews: Vec::new(),
7013 e2e: Vec::new(),
7014 verify_retried: false,
7015 e2e_deferred: false,
7016 e2e_defer_reason: None,
7017 fix: None,
7018 blocking: 0,
7019 answered: 1,
7020 expected: 1,
7021 clean: false,
7022 progressed: true,
7023 vote_split: false,
7024 reconsideration: Vec::new(),
7025 verdict: None,
7026 }
7027 }
7028
7029 #[test]
7030 fn awaiting_resume_is_a_failed_task_whose_last_run_parked_and_can_be_resumed() {
7031 let mut run = RunState::new(
7032 PathBuf::from("/repo"),
7033 "main".to_owned(),
7034 "abc1234def".to_owned(),
7035 "add retries".to_owned(),
7036 Config::default(),
7037 );
7038 run.status = RunStatus::Judging;
7039 run.parked = true;
7040 let mut task = Task::new(
7041 "add retries".to_owned(),
7042 "add retries".to_owned(),
7043 PathBuf::from("/repo"),
7044 crate::queue::Source::Human,
7045 );
7046 task.status = TaskStatus::Failed;
7047 task.runs = vec![run.id.clone()];
7048 let with = |t: &Task, r: &RunState| awaiting_resume_with(t, |_| Ok(r.clone()));
7049 assert!(with(&task, &run), "parked after judging is the case");
7050
7051 let mut not_parked = run.clone();
7052 not_parked.parked = false;
7053 not_parked.status = RunStatus::Stalled;
7054 assert!(!with(&task, ¬_parked), "a stall is the conductor's");
7055
7056 let mut fresh = task.clone();
7057 fresh.fresh_start = true;
7058 assert!(!with(&fresh, &run), "a requeue asked for a new competition");
7059
7060 let mut review = task.clone();
7061 review.review_branch = Some("magi/x/A".to_owned());
7062 assert!(!with(&review, &run), "review is ranked before resume");
7063
7064 let mut held = task.clone();
7065 held.status = TaskStatus::Held;
7066 assert!(!with(&held, &run), "a hold stays visible to the conductor");
7067
7068 let mut released = run.clone();
7069 released.released_to = Some("20260901-000000-new1".to_owned());
7070 assert!(!with(&task, &released), "nothing left to resume into");
7071
7072 assert!(!awaiting_resume_with(&task, |_| anyhow::bail!(
7073 "unreadable"
7074 )));
7075 }
7076
7077 #[test]
7078 fn unfinished_run_never_offers_a_run_whose_worktree_was_released() {
7079 let mut released = RunState::new(
7080 PathBuf::from("/repo"),
7081 "main".to_owned(),
7082 "abc1234def".to_owned(),
7083 "add retries".to_owned(),
7084 Config::default(),
7085 );
7086 released.status = RunStatus::Blocked;
7087 assert_eq!(
7088 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
7089 Some(released.id.clone())
7090 );
7091 released.released_to = Some("20260901-000000-new1".to_owned());
7092 assert_eq!(
7093 unfinished_run_with(&[released.id.clone()], "t", |_| Ok(released.clone())),
7094 None,
7095 "there is nothing left to resume it into"
7096 );
7097 }
7098
7099 #[test]
7100 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
7101 // Mirrors the failure this exists to close: a task's last run ended
7102 // `Blocked` with the review budget spent, `crate::conduct` chose
7103 // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
7104 // evidence), and without this check `attempt` would go on treating
7105 // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
7106 // review loop iterates zero times over an already-spent budget, so
7107 // the resumed run settles right back to `Blocked` having asked nobody
7108 // anything, and `Requeue`'s promised fresh competition never happens.
7109 let mut exhausted = RunState::new(
7110 PathBuf::from("/repo"),
7111 "main".to_owned(),
7112 "abc1234def".to_owned(),
7113 "add retries".to_owned(),
7114 Config::default(),
7115 );
7116 exhausted.status = RunStatus::Blocked;
7117 exhausted.config.graph.review_rounds = 1;
7118 exhausted.reviews = vec![review_round(1)];
7119
7120 assert_eq!(
7121 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
7122 None,
7123 "an exhausted `Blocked` run must not be offered as resumable"
7124 );
7125
7126 // A `Blocked` run with rounds still unused is genuinely worth
7127 // resuming, and must still be found.
7128 let mut has_budget_left = RunState::new(
7129 PathBuf::from("/repo"),
7130 "main".to_owned(),
7131 "abc1234def".to_owned(),
7132 "add retries".to_owned(),
7133 Config::default(),
7134 );
7135 has_budget_left.status = RunStatus::Blocked;
7136 has_budget_left.config.graph.review_rounds = 3;
7137 has_budget_left.reviews = vec![review_round(1)];
7138
7139 assert_eq!(
7140 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
7141 Ok(has_budget_left.clone())
7142 }),
7143 Some(has_budget_left.id.clone())
7144 );
7145 }
7146
7147 #[test]
7148 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
7149 // A task whose history holds an *older* run that still looks
7150 // resumable (say, a competition `Runner::review` was started
7151 // alongside after that older run went `Stalled`) and a *newest* run
7152 // that is `Blocked` with its review budget spent. `Recovery::Requeue`
7153 // on this task must mean a fresh competition — falling back to the
7154 // stale, superseded `Stalled` run instead would resurrect history
7155 // nothing asked to revisit and silently defeat the requeue.
7156 let mut older_stalled = RunState::new(
7157 PathBuf::from("/repo"),
7158 "main".to_owned(),
7159 "abc1234def".to_owned(),
7160 "add retries".to_owned(),
7161 Config::default(),
7162 );
7163 older_stalled.status = RunStatus::Stalled;
7164
7165 let mut newest_exhausted = RunState::new(
7166 PathBuf::from("/repo"),
7167 "main".to_owned(),
7168 "abc1234def".to_owned(),
7169 "add retries".to_owned(),
7170 Config::default(),
7171 );
7172 newest_exhausted.status = RunStatus::Blocked;
7173 newest_exhausted.config.graph.review_rounds = 1;
7174 newest_exhausted.reviews = vec![review_round(1)];
7175
7176 assert_eq!(
7177 unfinished_run_with(
7178 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
7179 "t",
7180 |_| Ok(newest_exhausted.clone())
7181 ),
7182 None,
7183 "the newest run is exhausted, so nothing here is worth resuming - \
7184 least of all the older, already-superseded run"
7185 );
7186 }
7187
7188 #[test]
7189 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
7190 assert_eq!(
7191 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
7192 Err(anyhow::anyhow!("fixture is absent"))
7193 }),
7194 None
7195 );
7196 }
7197
7198 fn action_question(run: &str, action: ask::ChoiceAction) -> ask::Question {
7199 let mut q = ask::Question::new(
7200 run.to_owned(),
7201 "implement".to_owned(),
7202 "impl-A".to_owned(),
7203 "continue?".to_owned(),
7204 String::new(),
7205 vec!["resume で続行する".to_owned(), "other".to_owned()],
7206 );
7207 q.actions.insert("resume で続行する".to_owned(), action);
7208 q.answer(ask::Answer::Choice("resume で続行する".to_owned()))
7209 .unwrap();
7210 q
7211 }
7212
7213 fn held_task_with(run: &str) -> Task {
7214 let mut t = task();
7215 t.runs = vec![run.to_owned()];
7216 t.hold_machine(Some("waiting for magi resume to be executed".to_owned()));
7217 t
7218 }
7219
7220 fn resume_action(run: &str) -> ask::ChoiceAction {
7221 ask::ChoiceAction::Resume { run: run.into() }
7222 }
7223
7224 #[test]
7225 fn decide_action_resumes_only_the_latest_resumable_run() {
7226 let t = held_task_with("r1");
7227 let q = action_question("r1", resume_action("r1"));
7228 let load = |s: RunState| move |_: &str| Ok(s);
7229 assert_eq!(
7230 decide_action(&t, &q, load(run_state(RunStatus::Blocked))),
7231 ActionDecision::Resume("r1".into())
7232 );
7233 // Not the latest run of the task.
7234 let q_other = action_question("r1", resume_action("r0"));
7235 assert!(matches!(
7236 decide_action(&t, &q_other, load(run_state(RunStatus::Blocked))),
7237 ActionDecision::Refuse(_)
7238 ));
7239 // A finished run cannot make progress.
7240 assert!(matches!(
7241 decide_action(&t, &q, load(run_state(RunStatus::Ready))),
7242 ActionDecision::Refuse(_)
7243 ));
7244 // A released one either.
7245 let mut released = run_state(RunStatus::Blocked);
7246 released.released_to = Some("elsewhere".into());
7247 assert!(matches!(
7248 decide_action(&t, &q, load(released)),
7249 ActionDecision::Refuse(_)
7250 ));
7251 // Unreadable state is a refusal, never a fresh competition.
7252 assert!(matches!(
7253 decide_action(&t, &q, |_: &str| bail!("gone")),
7254 ActionDecision::Refuse(_)
7255 ));
7256 }
7257
7258 #[test]
7259 fn decide_action_ignores_a_question_about_an_earlier_run() {
7260 let mut t = held_task_with("r1");
7261 t.runs.push("r2".to_owned());
7262 let never = |_: &str| -> Result<RunState> { bail!("not read") };
7263 assert_eq!(
7264 decide_action(&t, &action_question("r1", ask::ChoiceAction::Done), never),
7265 ActionDecision::Stale
7266 );
7267 }
7268
7269 #[test]
7270 fn decide_action_maps_requeue_and_done_and_never_acts_twice() {
7271 let mut t = held_task_with("r1");
7272 let never = |_: &str| -> Result<RunState> { bail!("not read") };
7273 assert_eq!(
7274 decide_action(
7275 &t,
7276 &action_question("r1", ask::ChoiceAction::Requeue),
7277 never
7278 ),
7279 ActionDecision::Requeue
7280 );
7281 let done_q = action_question("r1", ask::ChoiceAction::Done);
7282 assert_eq!(decide_action(&t, &done_q, never), ActionDecision::Done);
7283 t.mark_action_applied(&done_q.id);
7284 assert_eq!(decide_action(&t, &done_q, never), ActionDecision::Skip);
7285
7286 // A plain answer (no action for that label) does nothing.
7287 let mut plain = action_question("r1", ask::ChoiceAction::Done);
7288 plain.actions.clear();
7289 assert_eq!(
7290 decide_action(&held_task_with("r1"), &plain, never),
7291 ActionDecision::Skip
7292 );
7293 // A running task is left alone.
7294 let mut running = held_task_with("r1");
7295 running.status = TaskStatus::Running;
7296 assert_eq!(
7297 decide_action(
7298 &running,
7299 &action_question("r1", ask::ChoiceAction::Done),
7300 never
7301 ),
7302 ActionDecision::Skip
7303 );
7304 }
7305
7306 #[test]
7307 fn apply_choice_actions_releases_the_task_pinned_to_its_run_and_only_once() {
7308 let dir = tempfile::tempdir().unwrap();
7309 let queue = Queue::at(dir.path().join("queue"));
7310 let questions = Questions::at(dir.path().join("questions"));
7311 let home = dir.path().join("home");
7312 let mut state = run_state(RunStatus::Blocked);
7313 state.id = "20260101-000000-act1".to_owned();
7314 state.save_under(&home).unwrap();
7315
7316 let mut t = held_task_with(&state.id);
7317 queue.put(&mut t).unwrap();
7318 let mut q = action_question(&state.id, resume_action(&state.id));
7319 questions.put(&mut q).unwrap();
7320
7321 apply_choice_actions(&queue, &questions, &home);
7322 let after = queue.get(&t.id).unwrap();
7323 assert_eq!(after.status, TaskStatus::Queued);
7324 assert!(!after.fresh_start);
7325 assert!(after.action_applied(&q.id));
7326 let pin = after.resume_override.clone().unwrap();
7327 assert_eq!(pin.pinned_run.as_deref(), Some(state.id.as_str()));
7328 assert!(pin.forced);
7329
7330 // Held again later: the same answer does not release it a second time.
7331 let mut again = queue.get(&t.id).unwrap();
7332 again.hold_machine(Some("later".into()));
7333 queue.put(&mut again).unwrap();
7334 apply_choice_actions(&queue, &questions, &home);
7335 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7336 }
7337
7338 #[test]
7339 fn an_answer_the_waiter_already_delivered_is_not_acted_on_again() {
7340 let dir = tempfile::tempdir().unwrap();
7341 let queue = Queue::at(dir.path().join("queue"));
7342 let questions = Questions::at(dir.path().join("questions"));
7343 let home = dir.path().join("home");
7344 let mut state = run_state(RunStatus::Blocked);
7345 state.id = "20260101-000000-act2".to_owned();
7346 state.save_under(&home).unwrap();
7347
7348 let mut t = held_task_with(&state.id);
7349 queue.put(&mut t).unwrap();
7350 let mut q = action_question(&state.id, resume_action(&state.id));
7351 q.answer_delivered = true;
7352 questions.put(&mut q).unwrap();
7353
7354 apply_choice_actions(&queue, &questions, &home);
7355 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
7356
7357 // Undelivered: the daemon takes the delivery itself, exactly once.
7358 let mut q2 = action_question(&state.id, resume_action(&state.id));
7359 questions.put(&mut q2).unwrap();
7360 apply_choice_actions(&queue, &questions, &home);
7361 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
7362 assert!(questions.get(&q2.id).unwrap().answer_delivered);
7363 }
7364}