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::{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/// Retire an unanswered conductor question after its task no longer refers to
727/// it. Conductor questions use the task id in `Question::run`, so run-based
728/// cleanup cannot observe a manual release or completion.
729///
730/// Restricted to `Question::node == crate::conduct::NODE`: an ordinary run's
731/// own question also carries a `run`, and a run id that happens to collide
732/// with some task's id is not this loop's business — only a conductor
733/// question actually uses the task id that way. One `Questions::list()` scan
734/// is taken up front and matched against the in-memory task set, rather than
735/// calling `Questions::open_for` (a full disk scan on its own) once per task.
736fn reconcile_task_questions(queue: &Queue, questions: &Questions) {
737 let tasks = queue.list();
738 let by_id: std::collections::BTreeMap<&str, &Task> =
739 tasks.iter().map(|t| (t.id.as_str(), t)).collect();
740 let referenced: std::collections::BTreeSet<&str> = tasks
741 .iter()
742 .flat_map(|task| task.blocked_by.iter().map(String::as_str))
743 .collect();
744
745 for mut question in questions.list() {
746 if !question.status.open() || question.node != crate::conduct::NODE {
747 continue;
748 }
749 // Keep questions a task still names, including when the reference
750 // moved to a dependent task.
751 if referenced.contains(question.id.as_str()) {
752 continue;
753 }
754 let Some(task) = by_id.get(question.run.as_str()) else {
755 continue;
756 };
757 question.abandon(format!(
758 "task {} no longer waits for this answer",
759 task.short()
760 ));
761 if let Err(e) = questions.put(&mut question) {
762 tracing::warn!(
763 "could not retire question {} for task {}: {e:#}",
764 question.short(),
765 task.short()
766 );
767 }
768 }
769}
770
771/// What a finished run tells the queue about the task it came from.
772///
773/// A struct rather than a fourth and fifth boolean argument: the two flags
774/// answer different questions about the same run, and a call site passing
775/// `(…, true, false)` is one transposition away from refunding attempts
776/// forever.
777#[derive(Debug, Clone, Copy)]
778pub struct Verdict {
779 /// Where the graph stopped.
780 pub status: RunStatus,
781 /// The run opened a pull request.
782 pub left_pr: bool,
783 /// At least one seat was lost to a rate limit.
784 pub quota_hit: bool,
785 /// The run parked at a node boundary because it was asked to.
786 pub parked: bool,
787 /// The run never produced a single candidate a judge could look at.
788 ///
789 /// Distinct from `quota_hit`: a run can lose a seat to a rate limit and
790 /// still have another candidate worth judging, in which case the loss was
791 /// not the reason nothing came of the run. This is `true` only when the
792 /// implement wave ended with nothing viable at all.
793 pub no_viable_candidates: bool,
794}
795
796/// Record a finished run against the task it came from.
797///
798/// Kept pure and separate from the loop because this mapping *is* the retry
799/// policy, and a policy that can only be exercised by spawning a graph is a
800/// policy nobody checks. The table:
801///
802/// | run status | task becomes | attempt spent |
803/// |---------------------------------------|---------------------|---------------|
804/// | parked at a boundary | `Failed` (requeued) | **no** |
805/// | `Merged`, `Ready` | `Done` | yes |
806/// | `Stalled`, quota hit | `Failed` (requeued) | **no** |
807/// | `Failed`, quota hit, no viable cand. | `Failed` (requeued) | **no** |
808/// | `Stalled`, no quota | `Failed`, or `Held` | yes |
809/// | `Blocked` with a PR | `Held` | yes |
810/// | `Blocked`, `Failed` otherwise | `Failed`, or `Held` | yes |
811/// | `VerifiedNoop` | `Held` | yes |
812/// | anything non-terminal | `Failed`, or `Held` | yes |
813///
814/// The `VerifiedNoop` row is independent of the `Failed`-quota row above it,
815/// deliberately: every candidate agreeing there is nothing to write is not a
816/// machine fact about a rate limit, it is an unverified claim about the
817/// *task* that a human still has to check — see [`RunStatus::VerifiedNoop`]'s
818/// own doc and [`Task::handed_off`]. `Held` rather than `Done` on purpose: the
819/// claim could be wrong (a misread instruction, a stale check), and closing
820/// the task automatically on an implementer's say-so would be the exact
821/// failure mode task 391f's own audit was raised to avoid. `attempt spent` is
822/// `yes` here for the same reason it is on the `Blocked`-with-a-PR row just
823/// above, which settles through the same [`Task::handed_off`]: `Held` is not
824/// `Failed`-and-requeued, so nothing retries this task on the same unverified
825/// claim regardless of whether the one already-spent attempt is refunded, and
826/// [`Task::release`] resets the count to zero anyway the moment a human looks
827/// at the evidence and lets it run again.
828///
829/// The `Stalled`-quota and `Failed`-quota rows are the ones worth reading
830/// twice, together. A quorum lost to rate limits is a property of the machine
831/// and not of the task, so the attempt is refunded and a reset quota picks
832/// the work up where it stopped — and that is just as true when every
833/// implement seat lost the same race and `after_implement` bails with nothing
834/// to judge, which surfaces as `Failed` rather than `Stalled` but is the same
835/// machine fact. The `no_viable_candidates` guard is what keeps that row
836/// narrow: a `Failed` run that produced a real candidate which then lost for
837/// some other reason still spends the attempt, exactly like the quorum lost
838/// to judges that answered with the wrong shape is ordinary flakiness, and
839/// refunding *that* takes the bound off the retry loop entirely: run e633
840/// stalled with `quota: []` after two judges wrote unusable JSON, was
841/// refunded, and the next attempt paid for a fresh hour-long implement wave
842/// before it could fail the same way. `max_attempts` exists precisely so
843/// that cannot repeat forever.
844///
845/// A non-terminal status means `execute` returned while the graph was still
846/// mid-flight, which is a bug rather than a verdict; it is treated as a
847/// failure so that a task cannot loop on it either.
848///
849/// `left_pr` splits the `Blocked` row, and it is the difference between a run
850/// that failed and a run that finished into a gate. See [`Task::handed_off`].
851pub fn settle(task: &mut Task, verdict: Verdict, detail: &str, max_attempts: usize) {
852 // A parked run is the operator's own doing, and its work is intact on
853 // disk. The task goes back in line with its attempt refunded so the next
854 // loop resumes the same run - which `one_task` prefers over competing
855 // again - and so that swapping the binary a few times cannot exhaust a
856 // budget meant for agents that actually misbehaved.
857 if verdict.parked {
858 task.stall(detail);
859 return;
860 }
861 match verdict.status {
862 RunStatus::Merged | RunStatus::Ready => task.succeed(),
863 RunStatus::Stalled if verdict.quota_hit => task.stall(detail),
864 RunStatus::Failed if verdict.quota_hit && verdict.no_viable_candidates => {
865 task.stall(detail)
866 }
867 RunStatus::Stalled | RunStatus::Failed => task.fail(detail, max_attempts),
868 RunStatus::Blocked if verdict.left_pr => task.handed_off(detail),
869 RunStatus::Blocked => task.fail(detail, max_attempts),
870 RunStatus::VerifiedNoop => task.handed_off(detail),
871 other => task.fail(
872 format!(
873 "the graph stopped at `{}` without reaching a terminal status: {detail}",
874 label(other)
875 ),
876 max_attempts,
877 ),
878 }
879}
880
881/// [`settle`], plus attaching the run's own [`diagnostic`] excerpt once the
882/// task ends up held.
883///
884/// The one place [`attempt`] (a live finish) and [`reclaim`] (recovering one a
885/// dead daemon never got back to) share this, so the two cannot drift into
886/// disagreeing about which held tasks get a diagnostic.
887fn settle_and_diagnose(
888 task: &mut Task,
889 verdict: Verdict,
890 detail: &str,
891 max_attempts: usize,
892 state: &RunState,
893) {
894 settle(task, verdict, detail, max_attempts);
895 if task.status == TaskStatus::Held {
896 task.diagnostic = diagnostic(state);
897 }
898}
899
900/// Reconcile a task left at [`TaskStatus::Running`] by a daemon that never
901/// got back to [`settle`] for it — a crash, a `SIGKILL`, or a run carried on
902/// by some other means entirely, like a manual `magi run` resume that
903/// finishes the graph outside the queue's bookkeeping.
904///
905/// Pure and separate from [`reclaim_orphaned_running`] for the same reason
906/// `settle` is separate from `attempt`: a task recovered this way must land
907/// exactly where a live daemon would have put it — the same policy table,
908/// not a second one that quietly drifts from it — and that is only checkable
909/// without spawning a real run.
910fn reclaim(task: &mut Task, last_run: Option<RunState>, max_attempts: usize) {
911 match last_run {
912 Some(state) => {
913 let verdict = Verdict {
914 status: state.status,
915 left_pr: state.pr.is_some(),
916 quota_hit: !state.quota.is_empty(),
917 parked: state.parked,
918 no_viable_candidates: state.viable().is_empty(),
919 };
920 let detail = format!(
921 "recovered a `running` task whose daemon never recorded the outcome: {}",
922 describe(&state)
923 );
924 settle_and_diagnose(task, verdict, &detail, max_attempts, &state);
925 }
926 None => {
927 let why = "task was `running` with no live daemon and no readable \
928 run to recover; held for a human to check what happened";
929 task.last_error = Some(why.to_owned());
930 // The phone shows `hold_reason`, so a task held by the machine
931 // says why there too and not only in `last_error`.
932 task.hold_machine(Some(why.to_owned()));
933 }
934 }
935}
936
937/// Find every task left at `running` that no live process is actually
938/// driving, and settle each one against whatever its last run became.
939///
940/// # Why a claim is proof, not a guess
941///
942/// [`poll`] takes a task's [`Queue::claim`] *before* [`Task::start`] writes
943/// `running`, and the guard is held for the task's whole time in that status:
944/// `attempt` does not return, and the loop does not move past the scope
945/// holding the claim, until the run has settled. So a `running` task whose
946/// lock is gone cannot have a live owner — this process or any other —
947/// without needing a staleness threshold or a pid check the way
948/// [`sweep_stale_claims`] does for the narrower case of a lock left next to a
949/// task that never got as far as `running` at all. Taking the claim here is
950/// the whole test: it either fails, because something really does hold it
951/// and the task is left alone, or it succeeds, which is the proof — and it is
952/// kept for the rest of the decision so nothing else can start a competing
953/// run while this one is being written.
954///
955/// Called on every poll, not only at startup, for the reason
956/// [`sweep_stale_claims`] now is too: a daemon that has been up for days must
957/// keep noticing this, not only on the one morning it happened to restart.
958fn reclaim_orphaned_running(queue: &Queue, max_attempts: usize) -> Vec<String> {
959 let mut reclaimed = Vec::new();
960 for listed in queue.list() {
961 if listed.status != TaskStatus::Running {
962 continue;
963 }
964 let Ok(_claim) = queue.claim(&listed.id) else {
965 continue;
966 };
967 // Re-read under the claim: a release or an edit landed by a human
968 // between the listing above and the claim just taken must not be
969 // clobbered by a decision based on the stale copy.
970 let Ok(mut task) = queue.get(&listed.id) else {
971 continue;
972 };
973 if task.status != TaskStatus::Running {
974 continue;
975 }
976 let last_run = task.runs.last().and_then(|id| RunState::load(id).ok());
977 // `execute` normally abandons a run's own open questions the moment
978 // `status` lands somewhere non-resumable (see `graph::Runner::settle_questions`),
979 // but a daemon that crashed *inside* that path - mid `land`'s CI wait,
980 // say - can leave a `run.json` already at `Merged`/`Ready`/`Failed`
981 // with the question still `open`, because the process died before
982 // reaching that call. `reclaim` itself stays pure on purpose (see its
983 // own doc), so the same cleanup runs here instead, against the run
984 // this reclaim is already reading. `settle_run` costs nothing when
985 // `execute` already got there first.
986 if let Some(state) = &last_run
987 && let Err(e) = ask::Questions::open().settle_run(&state.id, state.status)
988 {
989 tracing::warn!("abandon questions for {}: {e:#}", state.id);
990 }
991 reclaim(&mut task, last_run, max_attempts);
992 record(queue, &mut task);
993 reclaimed.push(task.id.clone());
994 }
995 reclaimed
996}
997
998/// Find every run whose `run.json` is provably dead — every seat it still
999/// lists as [`crate::run::RunState::active`] has overrun its own timeout, and
1000/// [`crate::run::RunState::liveness`] reads [`crate::run::Liveness::Dead`],
1001/// not merely "no daemon claims it" — and fail it, clearing the leftover
1002/// active seats so the run stops reading as `implementing` (or whichever
1003/// node) forever.
1004///
1005/// [`reclaim_orphaned_running`] settles the *task* a dead daemon left
1006/// `running`, using whatever `run.json` already says — but nothing in that
1007/// path, nor in [`reclaim`], ever writes back to the run itself (`reclaim`
1008/// stays pure on purpose, see its own doc), so a `run.json` a killed process
1009/// never got back to sits exactly where it was left: `active` full of seats
1010/// nobody will ever answer for, `status` stuck on whatever node was in
1011/// flight. `magi show` already tells an operator this in prose (`no live
1012/// daemon claims this run right now`); this is what makes that fact durable
1013/// on disk, the same way a task's own `TaskStatus::Running` does not get to
1014/// stay stuck once nothing is driving it.
1015///
1016/// Runs on every poll, not only at startup, for the reason
1017/// [`sweep_stale_claims`] and [`reclaim_orphaned_running`] already are: a
1018/// daemon up for days must keep noticing a run some other, now-dead, daemon
1019/// left behind just as readily as one it trips over on the way up.
1020///
1021/// Walks `home.join("runs")` directly and reads each `run.json` on its own,
1022/// rather than the process-global [`RunState::load`] / [`crate::run::list_ids`] —
1023/// the same reason [`crate::clean`]'s housekeeping passes take an explicit
1024/// `runs` directory instead: `home` here is a parameter precisely so a test
1025/// can point it away from the operator's real history (see [`drive`]'s own
1026/// doc), and a scan that fell through to the global home anyway would walk
1027/// whichever directory some *other* process or test pinned into that
1028/// `OnceLock` first — mutating runs this call was never handed.
1029fn reclaim_abandoned_runs(home: &Path, now: Timestamp) -> Vec<String> {
1030 reclaim_abandoned_runs_with(
1031 home,
1032 now,
1033 crate::proc::pid_status,
1034 crate::proc::process_started_at,
1035 )
1036}
1037
1038/// [`reclaim_abandoned_runs`] with its `driver_pid` liveness/identity queries
1039/// supplied by the caller — mirrors [`sweep_stale_claims_with`], which exists
1040/// for the identical reason: this sweep's real damage (wiping a run's active
1041/// seats and failing it) has to be provable against an injected answer in a
1042/// test, not just the real process table.
1043fn reclaim_abandoned_runs_with<F, G>(
1044 home: &Path,
1045 now: Timestamp,
1046 query: F,
1047 identity: G,
1048) -> Vec<String>
1049where
1050 F: Fn(u32) -> Option<bool>,
1051 G: Fn(u32) -> Option<String>,
1052{
1053 let mut abandoned = Vec::new();
1054 for entry in std::fs::read_dir(home.join("runs"))
1055 .into_iter()
1056 .flatten()
1057 .flatten()
1058 {
1059 let id = entry.file_name().to_string_lossy().into_owned();
1060 if !crate::run::is_run_id(&id) {
1061 continue;
1062 }
1063 // Unreadable is `clean::fold_due`'s problem, not this one's — see
1064 // that module's docs for why a run this cannot parse is left alone
1065 // rather than guessed at. A different schema number is not that: this
1066 // touches only `status` and `active`, never a field whose meaning a
1067 // schema bump changed, so an old record's values serve this exactly
1068 // as well as a current one's (see `clean::read_state`'s own doc for
1069 // the same reasoning applied to folding).
1070 let Ok(body) = std::fs::read_to_string(entry.path().join("run.json")) else {
1071 continue;
1072 };
1073 let Ok(mut state) = serde_json::from_str::<RunState>(&body) else {
1074 continue;
1075 };
1076 if state.status.done() || !state.active_all_overrun(now) {
1077 continue;
1078 }
1079 // Not `!is_working_on(..)` alone: that is only "no *daemon* claims
1080 // it", which is also the normal, healthy shape of a manual `magi
1081 // run` / `magi review` sharing this same home — this scan walks
1082 // every run on disk, not only ones this daemon itself started. Such
1083 // a run's active seats can legitimately sit past their own timeout
1084 // for a little while (the CLI finishing up, its result still being
1085 // collected) without the process driving it having died. `liveness`
1086 // is what actually tells the two apart, by corroborating
1087 // `driver_pid` against the process it names — see its own doc. Only
1088 // its strongest, provable answer licenses wiping this run's active
1089 // seats and failing it out from under whatever is still running it.
1090 let daemon_claims = is_working_on(home, &id, now);
1091 if state.liveness_with(daemon_claims, &query, &identity) != crate::run::Liveness::Dead {
1092 continue;
1093 }
1094 state.abandon("daemon");
1095 if let Err(e) = state.save_under(home) {
1096 tracing::warn!("could not persist abandoned run {id}: {e:#}");
1097 continue;
1098 }
1099 // This run never passes through `Runner::execute` again, so its end
1100 // is announced here.
1101 if let Some(notice) = notices::run_ended(&state) {
1102 notices::raise_in(home, notice);
1103 }
1104 // The seat that asked is gone for good now, exactly like any other
1105 // door `graph::Runner::settle_questions` closes the moment `status`
1106 // lands somewhere non-resumable - see that method's own doc. Nothing
1107 // else reaches this one before the next `janitor()` startup pass
1108 // (`clean::abandon_settled_questions`), and a daemon that stays up
1109 // for days must not leave an open question badging the operator
1110 // until it happens to restart.
1111 if let Err(e) = Questions::at(home.join("questions")).settle_run(&id, state.status) {
1112 tracing::warn!("abandon questions for {id}: {e:#}");
1113 }
1114 abandoned.push(id);
1115 }
1116 abandoned
1117}
1118
1119/// Run the loop until Ctrl-C, or until the queue drains with [`Opts::once`].
1120///
1121/// A thin wrapper over [`serve_until`] with a stop nothing but Ctrl-C ever
1122/// sets, so there is one loop body rather than two that drift apart the first
1123/// time the retry policy changes on only one of them.
1124pub async fn serve(opts: Opts) -> Result<()> {
1125 serve_until(opts, Stop::new()).await
1126}
1127
1128/// [`serve`], but stopping when `stop` is set as well as on Ctrl-C.
1129///
1130/// Neither a signal nor a `stop` abandons a run in flight. Killing the graph
1131/// mid-node leaves worktrees, branches and agent sessions behind, and every
1132/// agent call already paid for is lost; finishing the run costs the operator a
1133/// wait and saves them a cleanup. A stop therefore only sets a flag: the
1134/// current `execute` runs to its terminal status, the task's outcome is
1135/// recorded, and only then does the loop return. That window is what
1136/// [`Stop::finishing`] is for. An operator who genuinely wants the run dead
1137/// still has a second Ctrl-C, which the runtime turns into a process kill —
1138/// and the task left `Running` then tells the next daemon, and the next human,
1139/// where to look.
1140///
1141/// While the queue is empty the stop is honoured within one wakeup rather than
1142/// one poll interval: the wait is a `select!` against [`Stop`]'s notify, so a
1143/// caller that taps stop does not sit through the remainder of a sleep.
1144pub async fn serve_until(opts: Opts, stop: Stop) -> Result<()> {
1145 let signal = {
1146 let stop = stop.clone();
1147 tokio::spawn(async move {
1148 if tokio::signal::ctrl_c().await.is_ok() {
1149 stop.stop();
1150 tracing::info!("shutdown requested; a run in flight will be finished first");
1151 }
1152 })
1153 };
1154
1155 let worktrees_root = opts
1156 .worktrees_root
1157 .clone()
1158 .unwrap_or_else(crate::run::default_worktree_root);
1159 let outcome = drive(
1160 &opts,
1161 &Queue::open(),
1162 &status_path(),
1163 &crate::run::home(),
1164 &worktrees_root,
1165 &stop,
1166 )
1167 .await;
1168
1169 signal.abort();
1170 outcome
1171}
1172
1173/// The loop proper: setup, poll, teardown, with the queue and the status file
1174/// supplied rather than discovered.
1175///
1176/// All three of `home`, `worktrees_root` and the queue/status paths are
1177/// parameters rather than resolved here, for the same reason:
1178/// [`crate::run::home`] is process-global and its override is a `OnceLock`,
1179/// so a unit test that pinned it would fight every other test in the binary,
1180/// and a loop that resolved its own worktree bay could only be exercised
1181/// against the operator's real `~/wt/<repo>` - publishing over a live
1182/// daemon's status file, claiming tasks out of a live backlog, and, since
1183/// [`janitor`] runs on every idle tick, reclaiming worktrees out from under
1184/// whatever the operator actually has on disk.
1185async fn drive(
1186 opts: &Opts,
1187 queue: &Queue,
1188 status_file: &Path,
1189 home: &Path,
1190 worktrees_root: &Path,
1191 stop: &Stop,
1192) -> Result<()> {
1193 // The status file is a *snapshot*, not a stream of events: a reader only
1194 // ever wants the latest values, and every tick rewrites the whole file
1195 // anyway. A shared `Mutex<Status>` therefore says exactly what is meant,
1196 // while an mpsc channel would force the loop to re-send unchanged fields on
1197 // every heartbeat — or the heartbeat to keep its own shadow copy of them —
1198 // for no gain. The lock is only ever held across a field assignment, never
1199 // across an await.
1200 let status = Arc::new(Mutex::new(Status::new()));
1201 write_status_to(status_file, &lock(&status)).context("publish the daemon status file")?;
1202 let beat = tokio::spawn(heartbeat(Arc::clone(&status), status_file.to_path_buf()));
1203
1204 // Read once at startup, not per task: how many runs this loop drives at
1205 // once is a property of the machine running it, not of whichever
1206 // repository a given task happens to name - see
1207 // `Config::daemon.max_concurrent_runs`'s doc for why that is a machine
1208 // fact in the same sense the agent roster is.
1209 let daemon_cfg = prepare(&opts.repo, opts)
1210 .map(|c| c.daemon)
1211 .unwrap_or_default();
1212 let concurrency = max_concurrent(daemon_cfg.max_concurrent_runs);
1213
1214 tracing::info!(
1215 "magi serve: queue {} (poll {}s, {} attempts per task, {} run(s) at once{})",
1216 queue.root().display(),
1217 opts.poll.as_secs(),
1218 opts.max_attempts,
1219 concurrency,
1220 if daemon_cfg.pause_for_interrupts {
1221 ", interrupts enabled"
1222 } else {
1223 ""
1224 }
1225 );
1226
1227 // `--once` drains an already-idle queue without reaching the idle wait,
1228 // but must still perform the startup cleanup.
1229 janitor(&opts.repo, opts, home, worktrees_root).await;
1230
1231 let outcome = poll(
1232 opts,
1233 queue,
1234 &status,
1235 home,
1236 worktrees_root,
1237 stop,
1238 DispatchLimits {
1239 max_concurrent: concurrency,
1240 pause_for_interrupts: daemon_cfg.pause_for_interrupts,
1241 },
1242 )
1243 .await;
1244
1245 beat.abort();
1246 clear_status_at(status_file);
1247 outcome
1248}
1249
1250/// Refresh the status file on a fixed tick.
1251///
1252/// Separate from the loop because a run takes tens of minutes: a status file
1253/// written only between tasks would look stale for the whole of every run, and
1254/// a reader would report the daemon dead exactly while it was busiest.
1255async fn heartbeat(status: Arc<Mutex<Status>>, path: PathBuf) {
1256 loop {
1257 tokio::time::sleep(HEARTBEAT).await;
1258 let snapshot = {
1259 let mut guard = lock(&status);
1260 guard.updated_at = Timestamp::now();
1261 guard.clone()
1262 };
1263 if let Err(e) = write_status_to(&path, &snapshot) {
1264 // A failed heartbeat must not take the daemon down: the loop is the
1265 // product, the status file is only the window onto it.
1266 tracing::warn!("could not refresh the daemon status file: {e:#}");
1267 }
1268 }
1269}
1270
1271/// Whether a task's last run is sitting in `land`'s merge-approval wait, and
1272/// if so, whether that wait is over.
1273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1274enum LandResume {
1275 /// The task's last run is not parked on a land approval; schedule it
1276 /// like any other candidate.
1277 NotLanding,
1278 /// Parked in `land`, waiting on a question nobody has answered yet.
1279 /// Left alone: attempting it now would only re-observe the same pull
1280 /// request and park again, spending a `gh` call on a decision that has
1281 /// not changed since the last time this was checked.
1282 StillWaiting,
1283 /// Parked in `land`, and the question is settled - answered or
1284 /// abandoned. Resuming this is the one kind of candidate that must not
1285 /// wait on a free [`Config::daemon`] concurrency slot: see [`poll`].
1286 Ready,
1287}
1288
1289/// Classify a runnable candidate by whether it is parked on a land-merge
1290/// approval. Read-only - no claim taken, nothing written - so it is cheap
1291/// enough to call on every candidate, every poll.
1292fn land_resume_state(task: &Task) -> LandResume {
1293 let Some(run_id) = task.runs.last() else {
1294 return LandResume::NotLanding;
1295 };
1296 let Ok(state) = RunState::load(run_id) else {
1297 return LandResume::NotLanding;
1298 };
1299 if state.status != RunStatus::Landing || !state.parked {
1300 return LandResume::NotLanding;
1301 }
1302 let store = ask::Questions::open();
1303 let waiting = store
1304 .list()
1305 .into_iter()
1306 .filter(|q| &q.run == run_id && q.node == land::APPROVAL_NODE)
1307 .max_by(|a, b| a.id.cmp(&b.id));
1308 let Some(mut q) = waiting else {
1309 return LandResume::Ready;
1310 };
1311 if !q.status.open() {
1312 return LandResume::Ready;
1313 }
1314 // `ask::ask_and_wait`'s own deadline is what used to retire a question
1315 // nobody ever answered; land's approval bypasses that wait entirely (see
1316 // `land::approval_gate`), so the same deadline has to be enforced here
1317 // instead, or `graph.answer_timeout` silently stops meaning anything for
1318 // a land approval and a run can sit `StillWaiting` forever with nobody
1319 // told to look at it.
1320 let timeout = Duration::from_secs(state.config.graph.answer_timeout);
1321 let elapsed = Timestamp::now().as_second() - q.asked_at.as_second();
1322 if elapsed >= 0 && elapsed as u64 >= timeout.as_secs() {
1323 q.abandon(format!(
1324 "no answer within {}s of asking",
1325 timeout.as_secs().max(1)
1326 ));
1327 // If this can't be persisted, do not treat the wait as settled on a
1328 // guess: fall through and try again next poll.
1329 if store.put(&mut q).is_ok() {
1330 return LandResume::Ready;
1331 }
1332 }
1333 LandResume::StillWaiting
1334}
1335
1336/// How often the loop rechecks for new work while something it already
1337/// started is still running, rather than sleeping out the whole
1338/// [`Opts::poll`] interval.
1339///
1340/// Short on purpose: this is what lets a land-merge approval that comes back
1341/// while another task is mid-competition be noticed and resumed within a
1342/// fraction of a second, not within the next multi-second poll.
1343const RECHECK_WHILE_BUSY: Duration = Duration::from_millis(200);
1344
1345/// How often [`poll`] rechecks the shared build cache against its cap at a
1346/// boundary between runs (see [`maybe_prune_cache_between_runs`]), instead of
1347/// waiting for the queue to run dry.
1348///
1349/// A queue that never empties means the `janitor` call at the bottom of this
1350/// loop's fully-idle branch can go unreached for as long as the backlog
1351/// lasts. Five minutes is far below a single gate's own 1200s timeout, so a
1352/// cache that started the day at its 10 GiB cap cannot grow anywhere near the
1353/// 81.8 GiB an idle-only check let it reach before this existed, and it is
1354/// well above the cost of a `dir_size` walk over a multi-gigabyte cache, so a
1355/// backlog of short tasks does not pay for that walk on every poll.
1356const CACHE_CHECK_INTERVAL_SECS: u64 = 5 * 60;
1357
1358/// Frees one attempt's concurrency slot - `Stop`'s busy count and its entry
1359/// in `Status::current` - on drop, so both are released even if the attempt
1360/// panics rather than returning.
1361///
1362/// A `Drop` impl rather than statements written after the `.await` it
1363/// guards: a panic unwinds straight past code placed "after" a call, and
1364/// `Runner::execute`'s chain reaches deep enough into agent-output parsing
1365/// that ruling a panic out there is not a bet this loop can make. Without
1366/// this, one panicking run would leave [`Stop::busy_now`] stuck `true`
1367/// forever - the idle branch in [`poll`], and with it the janitor, would
1368/// never run again - and a ghost entry in `Status::current` naming a task
1369/// nothing is still working on.
1370struct InFlightGuard<'a> {
1371 status: &'a Arc<Mutex<Status>>,
1372 stop: &'a Stop,
1373 task_id: &'a str,
1374}
1375
1376impl Drop for InFlightGuard<'_> {
1377 fn drop(&mut self) {
1378 lock(self.status).current.retain(|c| c.task != self.task_id);
1379 self.stop.exit();
1380 }
1381}
1382
1383/// State of [`poll`]'s own interrupt-scheduling sequence - see
1384/// [`crate::config::Daemon::pause_for_interrupts`]. Advanced once per tick by
1385/// [`advance_interrupt`] and consulted by [`interrupt_gate`], both pure and
1386/// both kept free of `Task`'s non-identity fields on purpose: every decision
1387/// here turns only on task ids and which ones are in flight, so the "never
1388/// more than one run at once" and "exactly one resume" invariants can be
1389/// pinned down with a plain `#[test]`, no `Runner`, no tokio, no fixture
1390/// queue - which is exactly the coverage this feature's first two attempts
1391/// were missing.
1392///
1393/// Deliberately in-memory only, not written to disk anywhere: a daemon
1394/// restart mid-sequence loses track of which run it had asked to park and
1395/// which task was meant to run first, and simply falls back to `Idle` -
1396/// see [`drive`]'s own setup. The parked run itself is not lost - it is
1397/// sitting in the queue exactly like any other resumable, interrupted task,
1398/// `RunStatus::resumable` and [`Task::interrupt`] both intact on disk - it
1399/// just resumes on the ordinary priority order rather than guaranteed to go
1400/// first. Giving that guarantee a crash-proof memory would mean a new queue
1401/// field and a recovery ordering to go with it, which is exactly the
1402/// complexity this feature's constraints rule out for the one property that
1403/// actually matters: at most one run, ever, at once.
1404#[derive(Debug, Clone, PartialEq, Eq)]
1405enum Interrupt {
1406 /// No interrupt sequence in progress. Ordinary dispatch applies.
1407 Idle,
1408 /// `interrupt_task` is runnable and exactly one other run is in flight;
1409 /// `parked` names that one task's id. Dispatch is withheld from
1410 /// everyone, including `interrupt_task` itself, until it has left
1411 /// flight - only then is `interrupt_task` let through.
1412 ///
1413 /// `parked` is a `Vec` rather than a bare id for symmetry with
1414 /// [`Interrupt::Running`] and [`Interrupt::Resuming`], but
1415 /// [`advance_interrupt`]'s own `Idle` branch only ever starts a sequence
1416 /// when exactly one run is in flight, so it is guaranteed to hold
1417 /// exactly one entry in practice - see that branch's own doc for why
1418 /// more than one is deliberately never attempted.
1419 Parking {
1420 parked: Vec<String>,
1421 interrupt_task: String,
1422 },
1423 /// `interrupt_task` is dispatched and in flight alone. Dispatch is
1424 /// withheld from everyone until it leaves flight - merged, failed, held,
1425 /// it makes no difference - at which point the sequence moves to
1426 /// [`Interrupt::Resuming`], never straight back to [`Interrupt::Idle`]:
1427 /// going straight to `Idle` would hand `parked` back to ordinary
1428 /// priority-order dispatch, where a higher-priority task filed in the
1429 /// meantime could start ahead of it.
1430 Running {
1431 parked: Vec<String>,
1432 interrupt_task: String,
1433 },
1434 /// `interrupt_task` left flight; `parked` still names the one run this
1435 /// sequence owes a resume. Dispatch is withheld from everyone except
1436 /// that task - see [`interrupt_gate`] - so the resume this feature
1437 /// promises is never raced by, or run alongside, an unrelated candidate.
1438 /// Ends the moment it is seen in flight, or - see `advance_interrupt`'s
1439 /// own doc on abandonment - the moment it is no longer runnable at all.
1440 Resuming { parked: Vec<String> },
1441}
1442
1443/// One tick of the interrupt scheduler's own state machine. Pure: `in_flight`
1444/// and `runnable` are read-only snapshots of this tick's reality, and the
1445/// only side effect the caller still owes the world is asking whichever
1446/// `Pause` handles `parked` names to actually park - see [`poll`]'s own call
1447/// site.
1448///
1449/// `runnable` only has to carry `id` and `interrupt`; the whole [`Task`] is
1450/// accepted rather than a narrower type because that is what [`poll`] already
1451/// has on hand from [`runnable`], and building a second, smaller list on
1452/// every tick just to satisfy this signature would cost more than it proves.
1453///
1454/// Abandonment: [`Interrupt::Parking`] and [`Interrupt::Resuming`] both fall
1455/// back to a task they are waiting on no longer being [`runnable`] - held,
1456/// blocked, deleted, or finished by some other means entirely, all of which
1457/// an operator can do to a task sitting in the queue with no claim on it at
1458/// all, at any moment, interrupt sequence or not. Without this check the
1459/// sequence would wait forever for a dispatch that can never come, and
1460/// `interrupt_gate` would withhold every other task in the queue right along
1461/// with it - a single `magi task hold` on the wrong id turning into a
1462/// daemon that never dispatches anything again.
1463fn advance_interrupt(state: Interrupt, in_flight: &[String], runnable: &[Task]) -> Interrupt {
1464 match state {
1465 Interrupt::Idle => {
1466 // Not just "something to interrupt": exactly one thing. More
1467 // than one run in flight only happens above the default
1468 // `max_concurrent_runs = 1`, and `parked` guarantees "exactly
1469 // one resume, never run alongside anything else" only because
1470 // it is only ever seeded with exactly one id - see
1471 // `Interrupt::Resuming`'s own doc on why releasing more than one
1472 // parked id back to ordinary dispatch cannot be made safe
1473 // against that same setting's own extra concurrency slots.
1474 // Waiting here for the herd to settle to one is the
1475 // simplification this feature's own constraints ask for rather
1476 // than a second concurrency model to reconcile with the first.
1477 if in_flight.len() != 1 {
1478 return Interrupt::Idle;
1479 }
1480 match runnable.iter().find(|t| t.interrupt) {
1481 Some(t) => Interrupt::Parking {
1482 parked: in_flight.to_vec(),
1483 interrupt_task: t.id.clone(),
1484 },
1485 None => Interrupt::Idle,
1486 }
1487 }
1488 Interrupt::Parking {
1489 parked,
1490 interrupt_task,
1491 } => {
1492 if in_flight.iter().any(|id| parked.contains(id)) {
1493 // Still waiting for what was in flight to actually stop.
1494 Interrupt::Parking {
1495 parked,
1496 interrupt_task,
1497 }
1498 } else if in_flight.contains(&interrupt_task) {
1499 Interrupt::Running {
1500 parked,
1501 interrupt_task,
1502 }
1503 } else if runnable.iter().any(|t| t.id == interrupt_task) {
1504 // The parked run(s) are gone, but the interrupt task has not
1505 // been dispatched yet on this tick - `interrupt_gate` is
1506 // what lets it through next.
1507 Interrupt::Parking {
1508 parked,
1509 interrupt_task,
1510 }
1511 } else {
1512 // The interrupt task itself is no longer runnable - see this
1513 // function's own doc on abandonment. The parked run(s) still
1514 // get their guaranteed resume; there is simply no interrupt
1515 // to run ahead of them any longer.
1516 Interrupt::Resuming { parked }
1517 }
1518 }
1519 Interrupt::Running {
1520 parked,
1521 interrupt_task,
1522 } => {
1523 if in_flight.contains(&interrupt_task) {
1524 Interrupt::Running {
1525 parked,
1526 interrupt_task,
1527 }
1528 } else {
1529 // The interrupt task's own run reached a terminal status,
1530 // whichever one - this is the *only* trigger that moves the
1531 // sequence on, driven straight off the same in-flight
1532 // bookkeeping `poll` already reaps every tick, not a second,
1533 // independent poll of anything.
1534 Interrupt::Resuming { parked }
1535 }
1536 }
1537 Interrupt::Resuming { parked } => {
1538 if in_flight.iter().any(|id| parked.contains(id)) {
1539 // One of the parked runs has been dispatched - the resume
1540 // this sequence owed is fulfilled. Whatever else is left in
1541 // `parked` (ordinarily nothing, at the default concurrency
1542 // of one) rejoins ordinary priority-order dispatch, same as
1543 // any other runnable task.
1544 Interrupt::Idle
1545 } else if runnable.iter().any(|t| parked.contains(&t.id)) {
1546 Interrupt::Resuming { parked }
1547 } else {
1548 // Abandonment (see this function's own doc): nothing left in
1549 // `parked` is even runnable any longer.
1550 Interrupt::Idle
1551 }
1552 }
1553 }
1554}
1555
1556/// [`Interrupt`], but with [`crate::config::Daemon::pause_for_interrupts`]
1557/// folded in: disabled, the sequence can never leave [`Interrupt::Idle`], so
1558/// a task marked [`Task::interrupt`] on a daemon that has not opted in is
1559/// indistinguishable from any other runnable task - exactly the "off does
1560/// nothing" this feature promises.
1561fn advance_interrupt_tick(
1562 enabled: bool,
1563 state: Interrupt,
1564 in_flight: &[String],
1565 runnable: &[Task],
1566) -> Interrupt {
1567 if !enabled {
1568 return Interrupt::Idle;
1569 }
1570 advance_interrupt(state, in_flight, runnable)
1571}
1572
1573/// Which of this tick's runnable candidates the interrupt sequence actually
1574/// allows to be dispatched. Pure, and separate from [`advance_interrupt`] so
1575/// each half is assertable on its own: this is the half that keeps a
1576/// competition and an interrupt from ever running at the same moment.
1577fn interrupt_gate(state: &Interrupt, in_flight: &[String], candidates: Vec<Task>) -> Vec<Task> {
1578 match state {
1579 Interrupt::Idle => candidates,
1580 Interrupt::Parking {
1581 parked,
1582 interrupt_task,
1583 } => {
1584 if in_flight.iter().any(|id| parked.contains(id)) {
1585 Vec::new()
1586 } else {
1587 candidates
1588 .into_iter()
1589 .filter(|t| &t.id == interrupt_task)
1590 .collect()
1591 }
1592 }
1593 Interrupt::Running { .. } => Vec::new(),
1594 // At most one: even if `parked` names more than one id (more than
1595 // one run was in flight when the sequence began, only possible
1596 // above the default `max_concurrent_runs = 1`), only the first match
1597 // is offered. Capping this to a single candidate - not merely to
1598 // `parked`'s own ids - is what makes "exactly one resume, never two
1599 // dispatched together" true regardless of how many ordinary slots
1600 // happen to be free this tick.
1601 Interrupt::Resuming { parked } => candidates
1602 .into_iter()
1603 .find(|t| parked.contains(&t.id))
1604 .into_iter()
1605 .collect(),
1606 }
1607}
1608
1609/// The daemon-loop knobs [`poll`] needs from [`crate::config::Daemon`],
1610/// bundled into one parameter so `poll`'s own signature stays readable -
1611/// see [`drive`]'s call site for where these are actually read.
1612struct DispatchLimits {
1613 /// How many *ordinary* candidates run at once. See
1614 /// [`crate::config::Daemon::max_concurrent_runs`].
1615 max_concurrent: usize,
1616 /// See [`crate::config::Daemon::pause_for_interrupts`].
1617 pause_for_interrupts: bool,
1618}
1619
1620/// Which semaphore, if any, dispatching a candidate should draw its permit
1621/// from.
1622///
1623/// Pure and separate from [`poll`]'s loop body for the same reason
1624/// [`advance_interrupt`] is: the choice between "skip the ordinary pool
1625/// entirely", "spend the one urgent slot" and "spend an ordinary slot" is
1626/// exactly the policy this feature adds, and a policy only exercisable by
1627/// running the whole loop is a policy nobody checks.
1628#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1629enum PermitKind {
1630 /// A land-merge resume (see [`LandResume::Ready`]): bypasses every slot.
1631 /// Checked first - a task can be both a land resume and marked
1632 /// [`Task::urgent`], and the resume's own "must not queue behind
1633 /// anything" guarantee takes precedence.
1634 None,
1635 /// [`Task::urgent`]: the one extra slot in `urgent_sem`, spent instead of
1636 /// (never in addition to trying) the ordinary pool. This is what lets
1637 /// an urgent task dispatch while every ordinary slot is already checked
1638 /// out, and what stops a second urgent task from opening a third run: it
1639 /// waits on this same one-slot semaphore rather than falling through to
1640 /// the ordinary one.
1641 Urgent,
1642 /// The ordinary `max_concurrent_runs` pool - unaffected by either of the
1643 /// above.
1644 Ordinary,
1645}
1646
1647/// [`PermitKind`] for one candidate. `priority` is [`LandResume::Ready`]'s
1648/// own boolean, already computed by the caller from [`land_resume_state`].
1649fn permit_kind(priority: bool, urgent: bool) -> PermitKind {
1650 if priority {
1651 PermitKind::None
1652 } else if urgent {
1653 PermitKind::Urgent
1654 } else {
1655 PermitKind::Ordinary
1656 }
1657}
1658
1659/// Poll the queue until stopped, factored out so [`drive`] owns only setup and
1660/// teardown and cannot skip the teardown on an early return.
1661///
1662/// `limits.max_concurrent` bounds how many *ordinary* candidates run at once,
1663/// see [`crate::config::Daemon::max_concurrent_runs`]. A run parked on a
1664/// land approval that has since been answered is dispatched outside that
1665/// bound the moment [`land_resume_state`] reports it [`LandResume::Ready`]:
1666/// the whole point of parking there is that it must not queue behind
1667/// whatever else the loop happens to be running, even at the default of one.
1668/// A [`Task::urgent`] candidate is exempt from the same bound the same way,
1669/// through its own one-slot `urgent_sem` (see [`permit_kind`]). Every one of
1670/// these exemptions is still subject to the interrupt gate below, urgent
1671/// included: a land-resume or urgent candidate is exactly as much "something
1672/// else running" as an ordinary one from the interrupt sequence's point of
1673/// view, and letting either slip through while a run is being parked, or
1674/// while the interrupt task itself has the floor, is precisely the second
1675/// run 75dd's own "at most one run, ever, at once" guarantee must never
1676/// allow - see [`Interrupt`]'s own doc.
1677async fn poll(
1678 opts: &Opts,
1679 queue: &Queue,
1680 status: &Arc<Mutex<Status>>,
1681 home: &Path,
1682 worktrees_root: &Path,
1683 stop: &Stop,
1684 limits: DispatchLimits,
1685) -> Result<()> {
1686 let DispatchLimits {
1687 max_concurrent,
1688 pause_for_interrupts,
1689 } = limits;
1690 // Only consulted by `once`, where a task that just failed is still
1691 // `runnable` and would otherwise be picked up again inside the same drain.
1692 // In the long-running mode a later poll retrying a failed task is the point,
1693 // and the attempt counter is what bounds it.
1694 let mut attempted: Vec<String> = Vec::new();
1695 let sem = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
1696 // One extra, permanent slot for `--urgent` tasks (see `Task::urgent`),
1697 // entirely separate from `sem`: an urgent candidate must dispatch
1698 // alongside whatever `sem` already has checked out, never by waiting for
1699 // one of those ordinary slots to free up and never by growing
1700 // `max_concurrent_runs` itself. Sized at one, not unbounded - see
1701 // `permit_kind`'s own doc - so a second `--urgent` task queues behind the
1702 // first on this same slot rather than opening a third run.
1703 let urgent_sem = Arc::new(tokio::sync::Semaphore::new(1));
1704 // A quota hit is a fact about the machine, not the task that happened to
1705 // surface it, and every other *ordinary* candidate is no less likely to
1706 // hit the same wall - see the warning below. A land-merge resume is
1707 // exempt: it is a human decision finishing, not a fresh competition, and
1708 // must not sit out a quota cooldown it did not cause.
1709 let quota_cooldown_until: Arc<Mutex<Option<Timestamp>>> = Arc::new(Mutex::new(None));
1710 let mut inflight: tokio::task::JoinSet<()> = tokio::task::JoinSet::new();
1711 let mut conductor = Conductor::new();
1712 // See `maybe_prune_cache_between_runs`'s own doc: this is the cache check
1713 // a congested queue would otherwise starve of the fully-idle branch below.
1714 let mut cache_last_checked: Option<Timestamp> = None;
1715 // See `Interrupt`'s own doc: in-memory only, advanced once per tick.
1716 let mut interrupt = Interrupt::Idle;
1717 // The `Pause` handed to each dispatched candidate's own `Runner` - see
1718 // `attempt`'s new parameter - kept here so the tick that decides to park
1719 // a run for an interrupt can reach that specific run's handle and no
1720 // other's. Pruned to whatever is still in flight at the top of every
1721 // tick, so a finished attempt's handle does not linger.
1722 let mut interrupt_pauses: std::collections::HashMap<String, crate::graph::Pause> =
1723 std::collections::HashMap::new();
1724
1725 while !stop.stopped() {
1726 lock(status).polls += 1;
1727
1728 // Reap whatever finished since the last tick without blocking on
1729 // anything still running. `InFlightGuard` already released the slot
1730 // even if the spawned attempt panicked; this only surfaces that it
1731 // happened, since a panic swallowed here otherwise leaves no trace.
1732 while let Some(result) = inflight.try_join_next() {
1733 if let Err(e) = result {
1734 tracing::error!("a spawned attempt did not finish cleanly: {e}");
1735 notices::raise(Notice::error(
1736 "loop:attempt",
1737 "A queued attempt ended abnormally; check the task it was running.",
1738 ));
1739 }
1740 }
1741
1742 let swept = sweep_stale_claims(queue, STALE_CLAIM);
1743 if !swept.is_empty() {
1744 tracing::warn!(
1745 "swept {} stale claim(s) left behind by an earlier daemon: {}",
1746 swept.len(),
1747 swept.join(", ")
1748 );
1749 }
1750 // Capture stalled work before reclaiming it. A dead daemon's ordinary
1751 // lock is swept and reclaimed in this same poll, but the conductor
1752 // must still see that it was stranded rather than only its mechanical
1753 // terminal state.
1754 let now = Timestamp::now();
1755
1756 // No run this daemon spawned is mid-compile right now, whether or
1757 // not another candidate is about to start - see
1758 // `maybe_prune_cache_between_runs`'s own doc for why this cannot
1759 // wait for the queue to run dry.
1760 if !stop.busy_now() {
1761 maybe_prune_cache_between_runs(
1762 &opts.repo,
1763 opts,
1764 home,
1765 stop,
1766 &mut cache_last_checked,
1767 now,
1768 )
1769 .await;
1770 }
1771
1772 let stalled = stalled_tasks(queue, home, now);
1773 let stalled_ids: std::collections::BTreeSet<_> =
1774 stalled.iter().map(|task| task.id.clone()).collect();
1775 let reclaimed = reclaim_orphaned_running(queue, opts.max_attempts);
1776 if !reclaimed.is_empty() {
1777 tracing::warn!(
1778 "reclaimed {} task(s) left `running` by a daemon that never \
1779 recorded the outcome: {}",
1780 reclaimed.len(),
1781 reclaimed.join(", ")
1782 );
1783 }
1784 let abandoned_runs = reclaim_abandoned_runs(home, now);
1785 if !abandoned_runs.is_empty() {
1786 tracing::warn!(
1787 "failed {} run(s) left behind by a killed process, past every \
1788 active seat's own timeout: {}",
1789 abandoned_runs.len(),
1790 abandoned_runs.join(", ")
1791 );
1792 }
1793
1794 // `home`, not `ask::Questions::open()`'s own process-global default:
1795 // `poll` is handed its home explicitly precisely so a test can point
1796 // it elsewhere, the same reason `Queue::at` and the status file path
1797 // are parameters rather than resolved here - see `drive`'s own doc.
1798 let questions = Questions::at(home.join("questions"));
1799
1800 // Deterministic: no model, run before the conductor sees anything so
1801 // its input reflects the queue's current, already-resolved state.
1802 resolve_blockers(queue, &questions);
1803 reconcile_task_questions(queue, &questions);
1804
1805 // The conductor gets one look per cycle, right before the loop takes
1806 // its next task, and only when there is something new to look at -
1807 // see `Conductor::worth_a_look`'s own doc for why "stalled is
1808 // non-empty" is the wrong test. Checked before `prepare` so an
1809 // unchanged cycle never pays for a synchronous config load.
1810 let finished: Vec<Task> = finished_tasks(queue)
1811 .into_iter()
1812 .filter(|task| !stalled_ids.contains(&task.id))
1813 .collect();
1814 let queued = queued_tasks(queue);
1815 // An empty queue has nothing to arrange. In particular, do not let
1816 // the conductor's initial snapshot cause synchronous config I/O
1817 // between the caller's stop notification and the idle wait below.
1818 if !(queued.is_empty() && stalled.is_empty() && finished.is_empty())
1819 && conductor.worth_a_look(queue, &stalled, &finished)
1820 {
1821 match prepare(&opts.repo, opts) {
1822 Ok(cfg) => {
1823 conductor
1824 .maybe_run(
1825 &cfg,
1826 &opts.repo,
1827 queue,
1828 &questions,
1829 home,
1830 &queued,
1831 &stalled,
1832 &finished,
1833 opts.max_attempts,
1834 )
1835 .await;
1836 }
1837 Err(e) => {
1838 tracing::warn!("conductor: no config: {e:#}");
1839 notices::raise(Notice::warn(
1840 "loop:no-config",
1841 "The loop could not read this repository's config, so held tasks are not being triaged.",
1842 ));
1843 }
1844 }
1845 }
1846
1847 let candidates: Vec<Task> = runnable(queue)
1848 .into_iter()
1849 .filter(|t| !opts.once || !attempted.contains(&t.id))
1850 .collect();
1851
1852 // A task id only stays a key here while its attempt is genuinely in
1853 // flight; `status.current` is the same liveness fact `InFlightGuard`
1854 // maintains for the phone's own status file, so this piggybacks on
1855 // it rather than tracking a second copy of the same thing.
1856 let in_flight: Vec<String> = lock(status)
1857 .current
1858 .iter()
1859 .map(|c| c.task.clone())
1860 .collect();
1861 interrupt_pauses.retain(|id, _| in_flight.contains(id));
1862
1863 interrupt =
1864 advance_interrupt_tick(pause_for_interrupts, interrupt, &in_flight, &candidates);
1865 if let Interrupt::Parking {
1866 parked,
1867 interrupt_task,
1868 } = &interrupt
1869 {
1870 let reason = format!(
1871 "task {} asked to run first",
1872 crate::run::short_of(interrupt_task)
1873 );
1874 for id in parked {
1875 if let Some(pause) = interrupt_pauses.get(id) {
1876 pause.park_because(reason.clone());
1877 }
1878 }
1879 }
1880 let candidates = interrupt_gate(&interrupt, &in_flight, candidates);
1881
1882 let cooling_down =
1883 lock("a_cooldown_until).is_some_and(|until| Timestamp::now() < until);
1884
1885 let mut started_any = false;
1886 for candidate in candidates {
1887 if stop.stopped() {
1888 break;
1889 }
1890
1891 let resume = land_resume_state(&candidate);
1892 if resume == LandResume::StillWaiting {
1893 continue;
1894 }
1895 let priority = resume == LandResume::Ready;
1896
1897 if !priority && cooling_down {
1898 continue;
1899 }
1900 let permit = match permit_kind(priority, candidate.urgent) {
1901 PermitKind::None => None,
1902 PermitKind::Urgent => match Arc::clone(&urgent_sem).try_acquire_owned() {
1903 Ok(p) => Some(p),
1904 // The one urgent slot is already spoken for by another
1905 // `--urgent` task's run. Keep looking rather than falling
1906 // back to the ordinary pool - see `PermitKind::Urgent`'s
1907 // own doc - a later candidate might still be an ordinary
1908 // task with a free slot, or another priority resume.
1909 Err(_) => continue,
1910 },
1911 PermitKind::Ordinary => match Arc::clone(&sem).try_acquire_owned() {
1912 Ok(p) => Some(p),
1913 // No ordinary slot free right now. A later candidate in
1914 // this same list might still be a priority resume or an
1915 // urgent task, so keep looking rather than stopping here.
1916 Err(_) => continue,
1917 },
1918 };
1919
1920 // A claim we cannot take means another daemon, or a human running
1921 // `magi run`, got there first. That is not the task's fault and
1922 // must not spend one of its attempts: move to the next candidate
1923 // rather than recording a failure.
1924 let Ok(claim) = queue.claim(&candidate.id) else {
1925 tracing::info!("task {} is claimed elsewhere; skipping", candidate.short());
1926 continue;
1927 };
1928 // Re-read under the claim: the task on disk may have been held or
1929 // edited between the listing and the lock.
1930 let mut task = match queue.get(&candidate.id) {
1931 Ok(t) if t.status.runnable() => t,
1932 Ok(_) => continue,
1933 Err(e) => {
1934 tracing::warn!("could not re-read task {}: {e:#}", candidate.short());
1935 continue;
1936 }
1937 };
1938 let task_id = task.id.clone();
1939 attempted.push(task_id.clone());
1940 lock(status).idle = false;
1941 // A stop asked for from here on is "finishing", not "stopped": the
1942 // run gets to reach a terminal status before the loop returns.
1943 stop.enter();
1944 started_any = true;
1945
1946 // A fresh, unshared handle - never `stop.pause()` - so parking
1947 // this run for an interrupt cannot leak into any other run this
1948 // loop ever drives. See `Pause`'s own doc.
1949 let run_pause = crate::graph::Pause::new();
1950 interrupt_pauses.insert(task_id.clone(), run_pause.clone());
1951
1952 let opts = opts.clone();
1953 let queue = queue.clone();
1954 let status = Arc::clone(status);
1955 let stop = stop.clone();
1956 let quota_cooldown_until = Arc::clone("a_cooldown_until);
1957 inflight.spawn(async move {
1958 // Held for the whole attempt: dropping either at the end of
1959 // this task is what releases the claim and, for an ordinary
1960 // candidate, frees its concurrency slot back to the loop.
1961 let _claim = claim;
1962 let _permit = permit;
1963 // See `InFlightGuard`: this must survive a panic inside `attempt`.
1964 let _inflight = InFlightGuard {
1965 status: &status,
1966 stop: &stop,
1967 task_id: &task_id,
1968 };
1969 let quota = attempt(&opts, &queue, &status, &stop, run_pause, &mut task).await;
1970 lock(&status).completed += 1;
1971 // A quota loss is a fact about the machine, not this task, and
1972 // the next ordinary candidate the loop offers is no less
1973 // likely to hit the same wall: without a cooldown here a
1974 // whole backlog can be run - and failed - in the seconds it
1975 // takes each attempt to notice the CLI is out of quota.
1976 let now = Timestamp::now();
1977 if let Some(until) = cooldown_until("a, now) {
1978 let wait = until.as_second() - now.as_second();
1979 *lock("a_cooldown_until) = Some(until);
1980 let hint = quota
1981 .iter()
1982 .find(|q| q.reset.is_some())
1983 .and_then(|q| q.reset.as_deref());
1984 match hint {
1985 Some(h) => tracing::warn!(
1986 "quota hit; waiting {wait}s before taking another ordinary task \
1987 (CLI reported reset: {h})"
1988 ),
1989 None => tracing::warn!(
1990 "quota hit; waiting {wait}s before taking another ordinary task \
1991 (no reset hint reported)"
1992 ),
1993 }
1994 }
1995 });
1996 }
1997
1998 if started_any {
1999 continue;
2000 }
2001
2002 if stop.busy_now() {
2003 // Something started on an earlier tick is still running. Recheck
2004 // soon rather than sleeping out the whole poll interval - a freed
2005 // slot, or a land approval answered mid-run, must not sit idle
2006 // for it.
2007 stop.idle(RECHECK_WHILE_BUSY.min(opts.poll)).await;
2008 continue;
2009 }
2010
2011 // Truly idle: nothing new to start and nothing still running.
2012 lock(status).idle = true;
2013 if opts.once {
2014 // A one-shot drain must perform the same post-work cleanup as a
2015 // daemon that reached a normal idle interval. The startup pass
2016 // cannot see runs or cache files produced by this drain.
2017 janitor(&opts.repo, opts, home, worktrees_root).await;
2018 triage_held(queue, home, opts).await;
2019 break;
2020 }
2021 stop.idle(opts.poll).await;
2022 if stop.stopped() {
2023 continue;
2024 }
2025 // Housekeeping only after a full quiet interval. Running it before
2026 // the first idle wait can block the executor while an operator's
2027 // stop request is waiting to be scheduled, defeating Stop's retained
2028 // wake permit. No run can start while this branch is active, so the
2029 // janitor still never races an in-flight compile.
2030 janitor(&opts.repo, opts, home, worktrees_root).await;
2031 triage_held(queue, home, opts).await;
2032 }
2033
2034 // Never return while a run is still in flight, whichever way the loop
2035 // above exited: a stop only sets a flag - see `serve_until` - and
2036 // returning here while `inflight` still holds spawned work would abandon
2037 // it exactly as a mid-node kill would.
2038 while let Some(result) = inflight.join_next().await {
2039 if let Err(e) = result {
2040 tracing::error!("a spawned attempt did not finish cleanly: {e}");
2041 notices::raise(Notice::error(
2042 "loop:attempt",
2043 "A queued attempt ended abnormally; check the task it was running.",
2044 ));
2045 }
2046 }
2047 Ok(())
2048}
2049
2050/// Run one claimed task to a terminal status and record the outcome.
2051///
2052/// Every transition is flushed to the queue as it happens, so the state on disk
2053/// is what actually occurred rather than what this process still intends to
2054/// write.
2055async fn attempt(
2056 opts: &Opts,
2057 queue: &Queue,
2058 status: &Arc<Mutex<Status>>,
2059 stop: &Stop,
2060 interrupt_pause: crate::graph::Pause,
2061 task: &mut Task,
2062) -> Vec<QuotaLoss> {
2063 let repo = repo_for(task, &opts.repo);
2064 tracing::info!(
2065 "task {} — {} (repo {})",
2066 task.short(),
2067 task.title,
2068 repo.display()
2069 );
2070
2071 let mut config = match prepare(&repo, opts) {
2072 Ok(c) => c,
2073 Err(e) => {
2074 // A setup failure spends an attempt even though no run was minted.
2075 // Without that, a task naming a repository that does not exist
2076 // would be retried at every poll for as long as the daemon lives.
2077 task.attempts += 1;
2078 task.fail(format!("config: {e:#}"), opts.max_attempts);
2079 record(queue, task);
2080 return Vec::new();
2081 }
2082 };
2083 apply_solo(&mut config, task);
2084
2085 // The free-space gate, checked *before* anything is minted: a task that
2086 // waits out a full disk costs nothing yet, and must not spend an attempt
2087 // or start a run the machine cannot finish. Held tasks stay in the list
2088 // for the human to see, and `magi task release` re-queues them when space
2089 // comes back - the same recovery as any other hold. A volume whose free
2090 // space cannot be measured closes the gate too: starting a run blind on a
2091 // disk that may be full is how the machine ends up with 6.7 GB free.
2092 if let Some(reason) = disk_gate(&repo, &config) {
2093 task.last_error = Some(reason.clone());
2094 task.hold_machine(Some(reason.clone()));
2095 record(queue, task);
2096 tracing::warn!("holding {} for want of disk space: {reason}", task.short());
2097 // Stable wording - the free-space figures live in the task's hold
2098 // reason, and changing numbers would relight the bell every poll.
2099 notices::raise(
2100 Notice::warn(
2101 &format!("disk:{}", repo.display()),
2102 "A task was held for want of free disk space; free some, then release it from the queue.",
2103 )
2104 .link(Link::Task {
2105 id: task.id.clone(),
2106 }),
2107 );
2108 return Vec::new();
2109 }
2110
2111 // A resumable run of this task is carried on, never re-competed. The
2112 // candidates are built and paid for, and a fresh competition races a
2113 // second implementation against them.
2114 //
2115 // Two runs paid for that lesson. Run 01c2 was blocked and the loop
2116 // started 3cbf on the same task a moment later, duplicating two and a
2117 // half hours of agent work. Then b25f stalled on a judge that timed out
2118 // and one that answered with no JSON - `quota: 0`, so nothing the machine
2119 // was to blame for - and 4043 started **one second** later, buying three
2120 // fresh implementations to reach the same panel. `RunStatus::resumable`
2121 // rather than `!done()` is what catches the second case: a stall is
2122 // terminal, and its cheap recovery re-asks only the absent seats.
2123 //
2124 // A load failure is warned about rather than silently read as "not
2125 // resumable": the alternative is exactly what let a schema mismatch on
2126 // run `eba2` fall through to a full re-competition with nobody told why.
2127 // `crate::conduct` is what actually offers a better answer than
2128 // `Runner::start` here (see `Recovery::Review`), once this task's next
2129 // failure shows it up as `held`/`failed` with the run state unreadable.
2130 let unfinished = (!task.fresh_start)
2131 .then(|| unfinished_run(&task.runs, task.short()))
2132 .flatten();
2133 // `crate::conduct` chose `Review` for this task on an earlier cycle: its
2134 // branch survived, and this reopens exactly that branch as a
2135 // review-only pass rather than resuming or competing again. Consumed
2136 // (cleared) here whichever way this goes, so it never outlives this one
2137 // attempt - see `queue::Task::review_branch`.
2138 let review_branch = task.review_branch.take();
2139 let branch_exists = match &review_branch {
2140 Some(branch) => crate::git::branch_exists(&repo, branch)
2141 .await
2142 .unwrap_or(false),
2143 None => false,
2144 };
2145 let starter = choose_starter(
2146 review_branch.as_deref(),
2147 branch_exists,
2148 unfinished.as_deref(),
2149 );
2150 let started = match &starter {
2151 Starter::Review(branch) => {
2152 tracing::info!(
2153 "task {} reopens `{branch}` as a review-only pass",
2154 task.short()
2155 );
2156 Runner::review(&repo, branch, config).await
2157 }
2158 Starter::Resume(id) => {
2159 tracing::info!("resuming run {id} rather than competing again");
2160 Runner::resume(id).map(|mut r| {
2161 if let Some(instruction) =
2162 prepare_instruction(&starter, Some(&r.state.instruction), task)
2163 {
2164 r.state.instruction = instruction;
2165 }
2166 r
2167 })
2168 }
2169 Starter::Start => {
2170 if let Some(branch) = &review_branch {
2171 tracing::warn!(
2172 "conductor chose review for task {} but branch `{branch}` no longer \
2173 exists; requeuing as a fresh competition instead",
2174 task.short()
2175 );
2176 }
2177 let instruction = prepare_instruction(&starter, None, task)
2178 .unwrap_or_else(|| task.instruction.clone());
2179 Runner::start(&repo, instruction, config).await
2180 }
2181 };
2182 let mut runner = match started {
2183 Ok(r) => r,
2184 Err(e) => {
2185 task.attempts += 1;
2186 task.fail(format!("could not start the run: {e:#}"), opts.max_attempts);
2187 record(queue, task);
2188 return Vec::new();
2189 }
2190 };
2191 // A stop that means "park" reaches the graph through this handle.
2192 runner.on_pause(stop.pause());
2193 // `poll`'s interrupt scheduler reaches this one run - and no other -
2194 // through this handle. See `Pause`'s own doc for why these are never
2195 // the same one.
2196 runner.watch_interrupt(interrupt_pause);
2197
2198 // `start` has minted the run, so the task can now point at it. Persisting
2199 // `Running` before `execute` is what makes a crash mid-run legible.
2200 let run = runner.state.id.clone();
2201 task.start(run.clone());
2202 record(queue, task);
2203 lock(status).current.push(Current {
2204 task: task.id.clone(),
2205 run,
2206 });
2207
2208 // `RunState::quota` is the run's whole history across every resume, so
2209 // only what this execution added may arm the cooldown or earn a refund.
2210 let quota_before = runner.state.quota.clone();
2211 let detail = match runner.execute().await {
2212 Ok(()) => describe(&runner.state),
2213 Err(e) => format!("{e:#}"),
2214 };
2215 let fresh = losses_this_attempt("a_before, &runner.state.quota);
2216 let verdict = Verdict {
2217 status: runner.state.status,
2218 // A run that opened a pull request handed its work over, whatever the
2219 // gate then decided about merging it.
2220 left_pr: runner.state.pr.is_some(),
2221 // Only a rate limit earns the task its attempt back - and only one
2222 // suffered now: a refund justified by a previous session's loss is
2223 // the same mistake as re-arming the cooldown from it. A stalled run
2224 // resumed without hitting quota again therefore spends its attempt,
2225 // like any other failure of the task's own.
2226 quota_hit: !fresh.is_empty(),
2227 // A run that parked was asked to stop; that is not a failure and must
2228 // not spend an attempt, or replacing the binary a few times would
2229 // exhaust a task's budget without an agent ever misbehaving.
2230 parked: runner.state.parked,
2231 // A quota loss that left nothing viable is the same machine fact as a
2232 // `Stalled` quota loss; see `settle`'s doc table.
2233 no_viable_candidates: runner.state.viable().is_empty(),
2234 };
2235 settle_and_diagnose(task, verdict, &detail, opts.max_attempts, &runner.state);
2236 record(queue, task);
2237 tracing::info!(
2238 "task {} is {} after run {} ({})",
2239 task.short(),
2240 task.status.as_str(),
2241 runner.state.short(),
2242 label(runner.state.status)
2243 );
2244 fresh
2245}
2246
2247/// The quota losses `after` holds that `before` did not: what one execution
2248/// suffered, as opposed to the run's history.
2249///
2250/// Compared by value rather than by length or position because
2251/// `Runner::recover_stall` drops a `QuotaLoss` when its seat ranks again, so
2252/// the vector can shrink and shift under a resume. A retried seat that hits
2253/// quota again is a `push` with a new `at`, so it shows up as new here.
2254/// `reclaim` deliberately keeps reading the whole history: after a crash there
2255/// is no attempt boundary to diff against.
2256fn losses_this_attempt(before: &[QuotaLoss], after: &[QuotaLoss]) -> Vec<QuotaLoss> {
2257 after
2258 .iter()
2259 .filter(|q| !before.contains(q))
2260 .cloned()
2261 .collect()
2262}
2263
2264/// When the loop-wide quota cooldown should end, given this attempt's losses;
2265/// `None` when there were none. Reset-hint parsing and the cap live here.
2266fn cooldown_until(quota: &[QuotaLoss], now: Timestamp) -> Option<Timestamp> {
2267 if quota.is_empty() {
2268 return None;
2269 }
2270 let with_hint = quota.iter().find(|q| q.reset.is_some());
2271 let reset_at = with_hint.and_then(|q| parse_reset_hint(q.reset.as_deref()?, now, q.at));
2272 let wait = quota_wait(reset_at, now, QUOTA_WAIT_FALLBACK, QUOTA_WAIT_CAP);
2273 let secs = i64::try_from(wait.as_secs()).unwrap_or(i64::MAX);
2274 Some(
2275 now.checked_add(jiff::SignedDuration::from_secs(secs))
2276 .unwrap_or(Timestamp::MAX),
2277 )
2278}
2279
2280/// Cut this attempt's candidate count to one when the task asked to run
2281/// alone.
2282///
2283/// Pure and separate from [`attempt`] so the one thing this feature changes -
2284/// which `candidates` a `solo` task's run is built with - can be asserted
2285/// without minting a run: `attempt` drives `graph::Runner`, which spawns real
2286/// agent CLIs, and no test may do that. `config` is mutated in place, taken by
2287/// value from the caller's own copy, so a repository's `magi.toml` on disk is
2288/// never touched - only the `Config` this one attempt hands to `Runner::start`.
2289fn apply_solo(config: &mut Config, task: &Task) {
2290 if task.solo {
2291 config.graph.candidates = 1;
2292 }
2293}
2294
2295/// Load the config for a task's repository, with the merge override applied.
2296fn prepare(repo: &Path, opts: &Opts) -> Result<Config> {
2297 let (mut config, _layers) = Config::discover(repo, opts.config.as_deref())?;
2298 if let Some(mode) = &opts.merge {
2299 config.merge.mode = merge_mode(mode)?;
2300 }
2301 Ok(config)
2302}
2303
2304/// Prune the shared build cache back under its cap at a safe boundary
2305/// between runs, so a queue that never empties - and so never reaches
2306/// [`poll`]'s fully-idle branch, where the ordinary [`janitor`] pass lives -
2307/// does not leave the cache to grow unchecked for as long as the backlog
2308/// lasts.
2309///
2310/// Called from [`poll`] only when `stop.busy_now()` is already `false`: the
2311/// same liveness fact the idle branch's own janitor call rests on - no run
2312/// this daemon spawned is still mid-compile - so pruning here races nothing.
2313/// The caller must not call this while a run is in flight; there is no
2314/// second `busy_now()` check inside this function, on purpose, because there
2315/// is nothing left to check that `busy_now()` has not already answered.
2316///
2317/// A stop that has already been asked for *is* checked here, for a different
2318/// reason. [`clean::prune_cache_if_over_limit`] walks the whole cache
2319/// synchronously before it decides anything, so the poll loop cannot get back
2320/// to its own `stopped()` test until that walk is over — and a loop already
2321/// on its way out must not make the operator wait out housekeeping it is
2322/// about to stop needing. This is the same call the idle branch makes when it
2323/// rechecks `stop.stopped()` after its wait before reaching [`janitor`], and
2324/// it matters more here: `busy_now()` is false throughout, so
2325/// [`Stop::finishing`] would report a stop as already landed while the walk
2326/// still held the loop. Nothing is lost by skipping — the cap is a standing
2327/// policy, and the next daemon's startup pass measures the same cache.
2328///
2329/// Rate-limited by [`CACHE_CHECK_INTERVAL_SECS`] rather than run on every
2330/// poll: a busy loop reaches this the instant one run's `InFlightGuard` drops
2331/// and the next has not yet claimed a task, which can be every few
2332/// milliseconds, and re-walking a multi-gigabyte cache that often would cost
2333/// more than the growth it is guarding against.
2334async fn maybe_prune_cache_between_runs(
2335 repo: &Path,
2336 opts: &Opts,
2337 home: &Path,
2338 stop: &Stop,
2339 last_checked: &mut Option<Timestamp>,
2340 now: Timestamp,
2341) {
2342 if stop.stopped() || !cache_check_due(*last_checked, now, CACHE_CHECK_INTERVAL_SECS) {
2343 return;
2344 }
2345 *last_checked = Some(now);
2346 let cfg = match prepare(repo, opts) {
2347 Ok(cfg) => cfg,
2348 Err(e) => {
2349 tracing::warn!("cache check: no config: {e:#}");
2350 return;
2351 }
2352 };
2353 match clean::prune_cache_if_over_limit(&cfg, home) {
2354 Ok(Some(pruned)) if pruned.files > 0 => tracing::info!(
2355 "housekeep: pruned {} file(s) ({} bytes) from the shared cache between runs",
2356 pruned.files,
2357 pruned.freed
2358 ),
2359 Ok(_) => {}
2360 Err(e) => {
2361 tracing::warn!("housekeep: prune cache: {e:#}");
2362 notices::raise_in(
2363 home,
2364 Notice::warn(
2365 "housekeep:cache",
2366 "Pruning the shared build cache failed; disk usage may keep growing.",
2367 ),
2368 );
2369 }
2370 }
2371}
2372
2373/// Whether [`maybe_prune_cache_between_runs`] should re-measure the cache
2374/// now, given when it last did (if ever). Pure, so the cadence is asserted
2375/// directly rather than by waiting out real minutes in a test.
2376fn cache_check_due(last_checked: Option<Timestamp>, now: Timestamp, interval_secs: u64) -> bool {
2377 last_checked.is_none_or(|last| clean::due(now, last, interval_secs))
2378}
2379
2380/// The disk janitor, with its housekeeping logged rather than fatal.
2381///
2382/// Called only at the loop's idle points, for the reason the caller documents:
2383/// a prune racing a live compile would delete files mid-build. The config is
2384/// re-read on every call because the repository that just ran may not be the
2385/// daemon's own default, and the cache directory is a repository fact.
2386///
2387/// `home` and `worktrees_root` are parameters rather than [`crate::run::home`]
2388/// and [`crate::run::default_worktree_root`] read here, for the same reason
2389/// [`drive`] takes its queue and status file rather than resolving them: a
2390/// test driving the loop must not reach through to the operator's real home
2391/// or worktree bay just because the janitor runs on every idle tick.
2392/// `worktrees_root` staying unread by [`clean::fold_due`] once made this easy
2393/// to get wrong silently - a test's `home` was already isolated, but nothing
2394/// exercised the parameter next to it, so a real worktree bay stayed wired in
2395/// underneath. The moment [`clean::fold_orphaned_worktrees`] started reading
2396/// it for real, every test in this file that drives the loop at all started
2397/// sweeping the operator's actual `~/wt/<repo>` instead of a fixture's.
2398async fn janitor(repo: &Path, opts: &Opts, home: &Path, worktrees_root: &Path) {
2399 let cfg = match prepare(repo, opts) {
2400 Ok(cfg) => cfg,
2401 Err(e) => {
2402 tracing::warn!("housekeep: no config: {e:#}");
2403 return;
2404 }
2405 };
2406 // A run's own worktree lives under `config.graph.worktree_root` when the
2407 // repository sets one - the same precedence `RunState::worktree_root`
2408 // uses - and `worktrees_root` only stands in for the *default* an
2409 // unconfigured repository resolves to (see this function's own
2410 // parameter, or the test fixture wiring one to a fake path). Housekeeping
2411 // that always swept the default regardless of this override would never
2412 // see, and so never reclaim, a single worktree for a repository that
2413 // relocated them elsewhere.
2414 let worktrees_root = cfg.graph.worktree_root.as_deref().unwrap_or(worktrees_root);
2415 let out = clean::housekeep(&cfg, home, worktrees_root, repo, Timestamp::now()).await;
2416 // Reported whenever there is anything to say, not only when `folded > 0`:
2417 // the incident this exists to prevent was 90 of 93 runs skipped and 0
2418 // folded, on every single pass, for months - a report gated on `folded`
2419 // would have stayed silent through every one of them.
2420 if out.folded > 0 || out.unreadable > 0 || out.orphaned_worktrees > 0 {
2421 let mut extra = Vec::new();
2422 if out.unreadable > 0 {
2423 extra.push(format!("{} unreadable", out.unreadable));
2424 }
2425 if out.orphaned_worktrees > 0 {
2426 extra.push(format!("{} orphaned worktree(s)", out.orphaned_worktrees));
2427 }
2428 let detail = if extra.is_empty() {
2429 String::new()
2430 } else {
2431 format!(" ({})", extra.join(", "))
2432 };
2433 tracing::info!("housekeep: folded {} run(s){detail}", out.folded);
2434 }
2435 if out.external_merges_recorded > 0 {
2436 tracing::info!(
2437 "housekeep: recorded {} run(s) as merged externally",
2438 out.external_merges_recorded
2439 );
2440 }
2441 if out.cache_files > 0 {
2442 tracing::info!(
2443 "housekeep: pruned {} file(s) ({} bytes) from the shared cache",
2444 out.cache_files,
2445 out.cache_freed
2446 );
2447 }
2448 if out.questions_abandoned > 0 {
2449 tracing::info!(
2450 "housekeep: abandoned {} question(s) left open by a finished run",
2451 out.questions_abandoned
2452 );
2453 }
2454}
2455
2456/// Run [`triage::run_once`] and log whatever it did, the same "only when
2457/// there is something to say" rule [`janitor`] follows for its own report.
2458///
2459/// Called at the same idle points as [`janitor`] - once per full poll
2460/// interval, never mid-attempt - for the same reason: it is not liveness
2461/// critical, and a task's own `hold_reason` string is the one thing this
2462/// would otherwise re-check (via [`crate::disk::free_bytes`]) on every busy
2463/// tick for no benefit.
2464async fn triage_held(queue: &Queue, home: &Path, opts: &Opts) {
2465 let questions = Questions::at(home.join("questions"));
2466 let report = triage::run_once(queue, &questions, opts.config.as_deref(), Timestamp::now());
2467 if report.is_empty() {
2468 return;
2469 }
2470 if !report.quarantined.is_empty() {
2471 tracing::info!(
2472 "triage: held {} blocked task(s) whose blocked-on task or \
2473 question no longer exists: {}",
2474 report.quarantined.len(),
2475 report.quarantined.join(", ")
2476 );
2477 }
2478 if !report.resumed.is_empty() {
2479 tracing::info!(
2480 "triage: resumed {} held task(s) whose machine hold had resolved: {}",
2481 report.resumed.len(),
2482 report.resumed.join(", ")
2483 );
2484 }
2485 if !report.asked.is_empty() {
2486 tracing::info!(
2487 "triage: asked about {} held task(s): {}",
2488 report.asked.len(),
2489 report.asked.join(", ")
2490 );
2491 }
2492 if !report.answered.is_empty() {
2493 tracing::info!(
2494 "triage: applied {} operator answer(s): {}",
2495 report.answered.len(),
2496 report.answered.join(", ")
2497 );
2498 }
2499}
2500
2501/// The free-space gate: what stands between this task and a new run, if
2502/// anything. `Some(reason)` holds the task; `None` lets it start.
2503///
2504/// A zero [`Config::disk::min_free_bytes`] opens the gate unconditionally -
2505/// the operator opted out. A measurement failure is a gate, not a pass: both
2506/// sides of "cannot tell" are served by not starting.
2507fn disk_gate(repo: &Path, config: &Config) -> Option<String> {
2508 disk_gate_with(repo, config, crate::disk::free_bytes)
2509}
2510
2511/// [`disk_gate`] with its free-space measurement supplied by the caller, so a
2512/// test can assert the exact wiring `attempt` runs - config's threshold in,
2513/// task-holding reason out - without asking the real machine's disk anything.
2514fn disk_gate_with<F: Fn(&Path) -> Result<u64>>(
2515 repo: &Path,
2516 config: &Config,
2517 free_bytes: F,
2518) -> Option<String> {
2519 let min = config.disk.min_free_bytes;
2520 if min == 0 {
2521 return None;
2522 }
2523 match free_bytes(repo) {
2524 Ok(free) => crate::disk::gate(free, min),
2525 Err(e) => Some(format!(
2526 "could not measure free space on {} ({e}); the disk gate refuses \
2527 to let a run start blind",
2528 repo.display()
2529 )),
2530 }
2531}
2532
2533/// How long to wait before offering another task when a run lost a seat to a
2534/// rate limit and its [`QuotaLoss::reset`] carried no hint [`parse_reset_hint`]
2535/// could read, or carried nothing at all. Long enough that a quota outage
2536/// cannot burn through a whole backlog in the few seconds each doomed attempt
2537/// takes to fail; short enough that a quota which clears early is not left
2538/// idle for the fallback's sake.
2539const QUOTA_WAIT_FALLBACK: Duration = Duration::from_secs(5 * 60);
2540
2541/// Longest a parsed reset hint may push the wait out to. The hint comes from
2542/// the CLI's own words, not a contract, so a parsing slip that lands a day
2543/// away must not leave the loop asleep for a day.
2544const QUOTA_WAIT_CAP: Duration = Duration::from_secs(30 * 60);
2545
2546/// How long [`poll`] should wait before offering the next task, after a run
2547/// lost at least one seat to a rate limit.
2548///
2549/// Pure and separate from the loop so the policy can be exercised without a
2550/// real quota outage. `reset_at` is the time [`parse_reset_hint`] made of the
2551/// CLI's free-text hint, if it could; `fallback` is what to wait when there is
2552/// nothing to parse, or the parsed time has already passed; `cap` bounds how
2553/// far a parsed hint is trusted to push the wait out.
2554fn quota_wait(
2555 reset_at: Option<Timestamp>,
2556 now: Timestamp,
2557 fallback: Duration,
2558 cap: Duration,
2559) -> Duration {
2560 match reset_at {
2561 Some(at) if at > now => {
2562 let secs = u64::try_from(at.as_second() - now.as_second()).unwrap_or(0);
2563 Duration::from_secs(secs).min(cap)
2564 }
2565 _ => fallback,
2566 }
2567}
2568
2569/// Best-effort reading of a [`QuotaLoss::reset`] hint into a concrete time.
2570///
2571/// `reset` is deliberately free text — see [`crate::agent::Quota`], which
2572/// explains why parsing it exactly "would be a bug factory" — so this only
2573/// recognises the shapes actually observed in the wild, and returns `None`
2574/// for anything else rather than guess at a format nobody has seen.
2575///
2576/// `recorded` is when the loss was noted ([`QuotaLoss::at`]). It anchors the
2577/// relative shape (`"in 1h2m49s"`, agy's), which counts from the moment the CLI
2578/// said it, not from whenever this loop happens to read it: anchoring on `now`
2579/// would push the reset later on every read and would read an already-elapsed
2580/// reset as still in the future. (A long hint is still clamped by
2581/// [`QUOTA_WAIT_CAP`]; the anchor matters for short hints and elapsed ones.)
2582fn parse_reset_hint(text: &str, now: Timestamp, recorded: Timestamp) -> Option<Timestamp> {
2583 parse_reset_hint_zoned(text, now)
2584 .or_else(|| parse_reset_hint_dated(text))
2585 .or_else(|| parse_reset_hint_relative(text, recorded))
2586}
2587
2588/// agy's shape: `"in 1h2m49s"` - `in`, then hours/minutes/seconds, each unit
2589/// optional but at least one required, in that order. A bare number or any
2590/// unknown unit is refused.
2591fn parse_reset_hint_relative(text: &str, recorded: Timestamp) -> Option<Timestamp> {
2592 let rest = text.trim().trim_end_matches('.').strip_prefix("in ")?;
2593 let mut rest = rest.trim();
2594 if rest.is_empty() {
2595 return None;
2596 }
2597 let mut total: i64 = 0;
2598 let mut matched = false;
2599 for (unit, secs) in [('h', 3600), ('m', 60), ('s', 1)] {
2600 if let Some((digits, tail)) = rest.split_once(unit)
2601 && !digits.is_empty()
2602 && digits.bytes().all(|b| b.is_ascii_digit())
2603 {
2604 total += digits.parse::<i64>().ok()?.checked_mul(secs)?;
2605 rest = tail;
2606 matched = true;
2607 }
2608 }
2609 if !rest.is_empty() || !matched {
2610 return None;
2611 }
2612 recorded
2613 .checked_add(jiff::SignedDuration::from_secs(total))
2614 .ok()
2615}
2616
2617/// Reads a 12-hour `"H:MMam/pm"` clock reading (whitespace trimmed,
2618/// case-insensitive) into a 24-hour hour and minute. Shared by every
2619/// reset-hint shape below.
2620fn parse_12h_clock(clock: &str) -> Option<(i8, i8)> {
2621 let clock = clock.trim().to_lowercase();
2622 let (digits, pm) = clock
2623 .strip_suffix("am")
2624 .map(|d| (d, false))
2625 .or_else(|| clock.strip_suffix("pm").map(|d| (d, true)))?;
2626 let (h, m) = digits.trim().split_once(':')?;
2627 let mut hour: i8 = h.trim().parse().ok()?;
2628 let minute: i8 = m.trim().parse().ok()?;
2629 if !(1..=12).contains(&hour) || !(0..=59).contains(&minute) {
2630 return None;
2631 }
2632 if pm && hour != 12 {
2633 hour += 12;
2634 } else if !pm && hour == 12 {
2635 hour = 0;
2636 }
2637 Some((hour, minute))
2638}
2639
2640/// The Claude CLI's shape: `"H:MMam/pm (Zone)"`, naming only a clock reading
2641/// and a zone, never a date. A clock reading already past today is read as
2642/// tomorrow's: a CLI naming a same-day reset that has already gone by means
2643/// the window rolled over while nothing was watching.
2644fn parse_reset_hint_zoned(text: &str, now: Timestamp) -> Option<Timestamp> {
2645 let open = text.find('(')?;
2646 let close = text.rfind(')')?;
2647 if close <= open {
2648 return None;
2649 }
2650 let zone = text[open + 1..close].trim();
2651 let (hour, minute) = parse_12h_clock(&text[..open])?;
2652 let tz = jiff::tz::TimeZone::get(zone).ok()?;
2653 let candidate = now
2654 .to_zoned(tz)
2655 .with()
2656 .hour(hour)
2657 .minute(minute)
2658 .second(0)
2659 .millisecond(0)
2660 .microsecond(0)
2661 .nanosecond(0)
2662 .build()
2663 .ok()?;
2664 let mut at = candidate.timestamp();
2665 if at <= now {
2666 at += jiff::SignedDuration::from_hours(24);
2667 }
2668 Some(at)
2669}
2670
2671/// The Codex CLI's shape: `"Mon DDth, YYYY H:MMam/pm"` (English month
2672/// abbreviation, an ordinal day, a 4-digit year, a 12-hour clock reading),
2673/// with no zone at all — unlike [`parse_reset_hint_zoned`], so there is no
2674/// "already past today" correction to make: the year already disambiguates
2675/// it. Scanned as a five-word window so it can be pulled out of the middle
2676/// of a full sentence, e.g. Codex's actual wording: "...or try again at Sep
2677/// 19th, 2026 5:10 PM." The result is read as UTC, same as this crate reads
2678/// any other timestamp with no zone attached.
2679fn parse_reset_hint_dated(text: &str) -> Option<Timestamp> {
2680 let words: Vec<&str> = text.split_whitespace().collect();
2681 if words.len() < 5 {
2682 return None;
2683 }
2684 (0..=words.len() - 5)
2685 .find_map(|start| parse_dated_window(&words[start..start + 5], words.get(start + 5)))
2686}
2687
2688/// One five-word window: month, `"DDth,"`, `"YYYY"`, `"H:MM"`, `"am/pm"`. A
2689/// parenthesis right after the window is refused rather than ignored — it
2690/// reads as an explicit zone annotation on a shape that otherwise carries
2691/// none, and guessing UTC anyway would be exactly the silent misread this
2692/// module's parsing otherwise avoids.
2693fn parse_dated_window(window: &[&str], trailing: Option<&&str>) -> Option<Timestamp> {
2694 if trailing.is_some_and(|next| next.starts_with('(')) {
2695 return None;
2696 }
2697 let month = month_number(window[0])?;
2698 let day_token = window[1].strip_suffix(',')?.to_lowercase();
2699 let day_digits = ["st", "nd", "rd", "th"]
2700 .iter()
2701 .find_map(|suffix| day_token.strip_suffix(*suffix))?;
2702 let day: i8 = day_digits.parse().ok()?;
2703 let year_token = window[2];
2704 if year_token.len() != 4 || !year_token.bytes().all(|b| b.is_ascii_digit()) {
2705 return None;
2706 }
2707 let year: i16 = year_token.parse().ok()?;
2708 // The am/pm word carries the sentence's own trailing punctuation, e.g.
2709 // the period ending "...at Sep 19th, 2026 5:10 PM." — strip it before
2710 // reusing the same 12-hour clock reader the bracketed shape uses.
2711 let ampm = window[4].trim_matches(|c: char| !c.is_ascii_alphabetic());
2712 let (hour, minute) = parse_12h_clock(&format!("{}{}", window[3], ampm))?;
2713 let date = jiff::civil::Date::new(year, month, day).ok()?;
2714 let candidate = date
2715 .at(hour, minute, 0, 0)
2716 .to_zoned(jiff::tz::TimeZone::UTC)
2717 .ok()?;
2718 Some(candidate.timestamp())
2719}
2720
2721/// The 3-letter English month abbreviation [`parse_reset_hint_dated`] reads,
2722/// case-insensitively, into a 1-based month number.
2723fn month_number(name: &str) -> Option<i8> {
2724 const NAMES: [&str; 12] = [
2725 "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
2726 ];
2727 let lower = name.to_lowercase();
2728 NAMES
2729 .iter()
2730 .position(|n| *n == lower.as_str())
2731 .map(|i| i as i8 + 1)
2732}
2733
2734/// Resuming a `Blocked` run that already spent every review round its own
2735/// config allowed cannot make progress: `graph::Runner`'s review loop walks
2736/// `(reviews.len()+1)..=max_rounds`, which is empty once `reviews.len()` has
2737/// reached `max_rounds`, so `execute` would settle straight back to
2738/// `Blocked` without asking anyone anything. Read-only against a state this
2739/// build never mutates — `src/graph.rs` stays untouched — but without this
2740/// check, [`unfinished_run`] would keep reporting such a run as still
2741/// "unfinished", and `crate::conduct::Recovery::Requeue` (whose whole
2742/// promise is a fresh competition when a design needs to change) would
2743/// silently resume the exhausted run instead, spending an attempt on a
2744/// cycle that cannot change anything.
2745fn exhausted_review_budget(state: &RunState) -> bool {
2746 state.status == RunStatus::Blocked && state.reviews.len() >= state.config.graph.review_rounds
2747}
2748
2749/// This task's *most recent* run, if resuming it would actually make
2750/// progress. `short` is only for the warning's own message.
2751///
2752/// Only ever `runs.last()` — never a search back through older history.
2753/// `runs` accumulates one entry per fresh `Runner::start`/`Runner::review`
2754/// mint, oldest first, and every entry before the last one was already
2755/// superseded at the moment it was minted: the daemon only ever starts a new
2756/// run when the previous one was not worth resuming (unresumable, exhausted,
2757/// or unreadable), or when `crate::conduct::Recovery::Review` deliberately
2758/// opens a fresh review-only run alongside an older, already-failed
2759/// competition. Searching further back would let an old run that merely
2760/// *looks* resumable — a `Stalled` competition an earlier `Review` pass left
2761/// behind, say — get resumed instead of the fresh competition
2762/// `crate::conduct::Recovery::Requeue` actually promised, reviving history
2763/// nothing asked to revisit.
2764///
2765/// Two runs paid for the "prefer resuming over restarting" half of this
2766/// lesson, which is why this still checks `runs.last()` rather than always
2767/// restarting. Run 01c2 was blocked and the loop started 3cbf on the same
2768/// task a moment later, duplicating two and a half hours of agent work. Then
2769/// b25f stalled on a judge that timed out and one that answered with no JSON
2770/// — `quota: 0`, so nothing the machine was to blame for — and 4043 started
2771/// **one second** later, buying three fresh implementations to reach the
2772/// same panel. `RunStatus::resumable` rather than `!done()` is what catches
2773/// the second case: a stall is terminal, and its cheap recovery re-asks only
2774/// the absent seats. [`exhausted_review_budget`] is the other half: a run
2775/// that is technically `resumable()` but provably cannot progress must not
2776/// count as "unfinished" either, or `Recovery::Requeue` becomes a silent
2777/// no-op instead of the fresh competition it promises.
2778///
2779/// A load failure is warned about rather than silently read as "not
2780/// resumable": the alternative is exactly what let a schema mismatch on run
2781/// `eba2` fall through to a full re-competition with nobody told why.
2782/// `crate::conduct` is what actually offers a better answer than
2783/// `Runner::start` here (see `Recovery::Review`), once this task's next
2784/// failure shows it up as `held`/`failed` with the run state unreadable.
2785fn unfinished_run(runs: &[String], short: &str) -> Option<String> {
2786 unfinished_run_with(runs, short, RunState::load)
2787}
2788
2789/// [`unfinished_run`] with an injected state reader. Tests provide their
2790/// fixtures directly rather than touching the process-global run home.
2791fn unfinished_run_with<F>(runs: &[String], short: &str, load: F) -> Option<String>
2792where
2793 F: FnOnce(&str) -> Result<RunState>,
2794{
2795 let id = runs.last()?;
2796 match load(id) {
2797 Ok(s) if s.status.resumable() && !exhausted_review_budget(&s) => Some(id.clone()),
2798 Ok(_) => None,
2799 Err(e) => {
2800 tracing::warn!("could not read run {id} for task {short}: {e:#}");
2801 None
2802 }
2803 }
2804}
2805
2806/// Which of the three ways [`attempt`] can mint or continue a run this task
2807/// should use.
2808#[derive(Debug, Clone, PartialEq, Eq)]
2809enum Starter {
2810 /// `crate::graph::Runner::review` against a branch `crate::conduct` chose
2811 /// and that still exists.
2812 Review(String),
2813 /// `crate::graph::Runner::resume` on an unfinished run of this task.
2814 Resume(String),
2815 /// `crate::graph::Runner::start`: a fresh competition.
2816 Start,
2817}
2818
2819/// Decide which of [`Runner::review`], [`Runner::resume`] or [`Runner::start`]
2820/// this attempt should use. Pure, and separate from [`attempt`], so the
2821/// routing itself is assertable without spawning a real graph or a git
2822/// process: `attempt`'s own `crate::git::branch_exists` call has already
2823/// happened by the time this is called.
2824///
2825/// `review_branch` wins whenever `branch_exists` confirms it; a `review_branch`
2826/// whose branch is gone falls all the way through to [`Starter::Start`], not
2827/// to [`Starter::Resume`] — `crate::conduct` chose review over resuming the
2828/// old (likely `Blocked`) run in the first place, and a branch that vanished
2829/// out from under that choice is not evidence resuming it would fare better.
2830fn choose_starter(
2831 review_branch: Option<&str>,
2832 branch_exists: bool,
2833 unfinished: Option<&str>,
2834) -> Starter {
2835 match review_branch {
2836 Some(branch) if branch_exists => Starter::Review(branch.to_owned()),
2837 Some(_) => Starter::Start,
2838 None => match unfinished {
2839 Some(id) => Starter::Resume(id.to_owned()),
2840 None => Starter::Start,
2841 },
2842 }
2843}
2844
2845/// Which repository a task runs in. A task that names none — the normal case
2846/// for one filed from a phone — runs in the daemon's own default.
2847fn repo_for(task: &Task, fallback: &Path) -> PathBuf {
2848 if task.repo.as_os_str().is_empty() || task.repo == Path::new(".") {
2849 return fallback.to_path_buf();
2850 }
2851 task.repo.clone()
2852}
2853
2854/// The header [`append_answers`] appends operator answers under. Shared with
2855/// [`strip_answers_block`] so a resumed run's instruction can be refreshed
2856/// rather than grown a new block on every resume.
2857const ANSWERS_HEADER: &str = "\n\n# Operator answers\n\n";
2858
2859/// Render the first `count` answers in the block appended to an instruction.
2860fn answers_block(task: &Task, count: usize) -> String {
2861 let mut s = ANSWERS_HEADER.to_owned();
2862 for a in &task.answers[..count] {
2863 s.push_str(&format!("- {}: {}\n", a.question, a.answer));
2864 }
2865 s
2866}
2867
2868/// Append every answer `crate::conduct` has collected for `task` onto `base`,
2869/// in the shape both [`instruction_for`] and [`resumed_instruction`] use.
2870fn append_answers(base: &str, task: &Task) -> String {
2871 if task.answers.is_empty() {
2872 return base.to_owned();
2873 }
2874 let mut s = base.to_owned();
2875 s.push_str(&answers_block(task, task.answers.len()));
2876 s
2877}
2878
2879/// Drop the prior answer block only when it is exactly the suffix this task
2880/// could have appended on an earlier resume. An `ANSWERS_HEADER` written by
2881/// the task author is ordinary instruction text, not a block to remove.
2882fn strip_answers_block<'a>(instruction: &'a str, task: &Task) -> &'a str {
2883 for count in (1..=task.answers.len()).rev() {
2884 let block = answers_block(task, count);
2885 if let Some(base) = instruction.strip_suffix(&block) {
2886 return base;
2887 }
2888 }
2889 instruction
2890}
2891
2892/// The instruction handed to `Runner::start`: the task's own text, plus any
2893/// operator answers `crate::conduct` collected for it (see
2894/// [`Task::answers`]), so a decision the operator actually made reaches the
2895/// implementers rather than only clearing the block that was waiting on it.
2896///
2897/// Appended rather than merged into [`Task::instruction`] itself, so the
2898/// task's own record stays exactly what its author wrote.
2899fn instruction_for(task: &Task) -> String {
2900 append_answers(&task.instruction, task)
2901}
2902
2903/// The instruction a resumed run should carry on with: whatever it already
2904/// had, refreshed with the task's *current* operator answers.
2905///
2906/// A resumable run's own `RunState::instruction` predates any answer
2907/// `crate::conduct` collects after the run parks, so resuming it unchanged —
2908/// the behaviour before this function existed — silently drops the very
2909/// decision the operator made to unblock it. Re-stripping any block this
2910/// function appended on an earlier resume before re-appending the current
2911/// list (rather than blindly appending again) is what keeps a task resumed
2912/// three times over three answered questions from carrying the same answer
2913/// three times.
2914fn resumed_instruction(old_instruction: &str, task: &Task) -> String {
2915 append_answers(strip_answers_block(old_instruction, task), task)
2916}
2917
2918/// What [`attempt`] should tell a [`Starter`] about `task`'s current operator
2919/// answers before handing it to `Runner` — the actual boundary between
2920/// [`choose_starter`]'s routing and the graph, factored out so it is
2921/// assertable without a real repository, git branch, or agent CLI.
2922///
2923/// `Starter::Review` deliberately answers `None`: `Runner::review` builds its
2924/// instruction from the reviewed branch's own commit log because there is no
2925/// task statement to speak of for hand-written work, and splicing operator
2926/// answers into that text would contradict the very message it sends
2927/// reviewers ("there is no task statement").
2928fn prepare_instruction(
2929 starter: &Starter,
2930 old_instruction: Option<&str>,
2931 task: &Task,
2932) -> Option<String> {
2933 match starter {
2934 Starter::Start => Some(instruction_for(task)),
2935 Starter::Resume(_) => Some(resumed_instruction(
2936 old_instruction.expect("a resumed run always has a prior instruction"),
2937 task,
2938 )),
2939 Starter::Review(_) => None,
2940 }
2941}
2942
2943/// Persist a transition. A queue write failure is logged rather than fatal: the
2944/// run already happened, and taking the daemon down would only add a lost
2945/// backlog to a full disk.
2946fn record(queue: &Queue, task: &mut Task) {
2947 if let Err(e) = queue.put(task) {
2948 tracing::error!("could not record task {}: {e:#}", task.short());
2949 notices::raise(Notice::error(
2950 "loop:record",
2951 "The loop could not save a task's state; check the disk.",
2952 ));
2953 }
2954}
2955
2956/// Every runnable task, in the order the loop should try them.
2957///
2958/// The head of this list is exactly what [`Queue::next_runnable`] offers; the
2959/// tail exists so that a claim somebody else holds costs the loop the next
2960/// candidate rather than a whole poll interval of idleness.
2961fn runnable(queue: &Queue) -> Vec<Task> {
2962 let mut tasks: Vec<Task> = queue
2963 .list()
2964 .into_iter()
2965 .filter(|t| t.status.runnable())
2966 .collect();
2967 tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
2968 tasks
2969}
2970
2971/// Why a run ended where it did, in one line, for [`Task::last_error`].
2972///
2973/// A stalled run names the seats the quota took out: "out of quota" is not
2974/// actionable, while "judge-2, judge-3 hit a limit" tells the operator which
2975/// agent to replace or which plan to top up.
2976///
2977/// Uses [`RunStatus::display_label`] rather than [`label`]/`as_str` on
2978/// purpose: unlike `label`'s other callers (an internal log line, an
2979/// already-a-bug fallback message), this string becomes `Task::last_error`
2980/// verbatim, which the phone renders in the same alarm-styled box an
2981/// ordinary failure gets — see `web::tests` and `assets/ui/app.js`'s
2982/// `.err` styling. A bare `verified_noop` there would read exactly like the
2983/// failure this whole feature exists to tell apart from one.
2984fn describe(state: &RunState) -> String {
2985 let mut detail = if state.status == RunStatus::Stalled {
2986 let mut seats: Vec<&str> = state.quota.iter().map(|q| q.seat.as_str()).collect();
2987 seats.sort_unstable();
2988 seats.dedup();
2989 if seats.is_empty() {
2990 "the judging panel lost its quorum".to_owned()
2991 } else {
2992 format!(
2993 "the judging panel lost its quorum; quota took out {}",
2994 seats.join(", ")
2995 )
2996 }
2997 } else {
2998 format!("run ended {}", state.status.display_label())
2999 };
3000 if let Some(last) = state.events.last() {
3001 detail.push_str(&format!(" ({}: {})", last.node, last.message));
3002 }
3003 detail.push_str(&format!(" [run {}]", state.id));
3004 detail
3005}
3006
3007/// Upper bound on [`Task::diagnostic`]'s length, in bytes.
3008///
3009/// The task file lives in the backlog indefinitely; a diagnostic is an
3010/// excerpt of the run's own `artifacts/`, not a copy of them, so this has to
3011/// stay small regardless of how much a gate command or a candidate printed.
3012const DIAGNOSTIC_MAX: usize = 4_000;
3013
3014/// Tail kept from a single failing command's output inside a diagnostic.
3015/// Smaller than [`crate::graph`]'s own `OUTPUT_TAIL` on purpose: this is a
3016/// pointer for a human deciding whether to go read the full artifact by hand,
3017/// not a replacement for reading it.
3018const DIAGNOSTIC_OUTPUT_TAIL: usize = 800;
3019
3020/// Assemble a bounded diagnostic excerpt from a held task's own run, so
3021/// `magi task show` says more than the one-line reason in [`describe`].
3022///
3023/// The one-liner answers "where did the run stop"; this answers "what would a
3024/// human have found opening `artifacts/` by hand" — the point of the whole
3025/// feature is the case that one-liner actively misleads on: a run held as "no
3026/// candidate produced a change" can mean the implementer actually finished
3027/// the task (opened a PR, merged it, tagged a release) and only left a clean
3028/// local worktree behind, which reads as "nothing happened" unless someone
3029/// goes and reads what the agent actually said. `None` when the run carries
3030/// none of the three shapes this recognises — an ordinary run held for
3031/// something not diagnosable from `RunState` alone still explains itself
3032/// through `Task::last_error`.
3033fn diagnostic(state: &RunState) -> Option<String> {
3034 let mut parts: Vec<String> = Vec::new();
3035
3036 // Gate failure: which check(s), and the tail of what each printed.
3037 for o in state.gate.iter().filter(|o| !o.ok()) {
3038 parts.push(format!(
3039 "gate `{}` failed ({:?}):\n{}",
3040 o.command,
3041 o.code,
3042 crate::run::tail(&o.output_tail, DIAGNOSTIC_OUTPUT_TAIL)
3043 ));
3044 }
3045
3046 // The land loop gave up because the fixer declined while checks were
3047 // still red: the message already names them (see `land::run`).
3048 if let Some(last) = state
3049 .events
3050 .iter()
3051 .rev()
3052 .find(|e| e.node == "land" && e.message.contains("fixer produced no commit"))
3053 {
3054 parts.push(last.message.clone());
3055 }
3056
3057 // No viable candidate: every implementer's own final word, sanitized the
3058 // same way a judge would have read it, so a run that actually finished
3059 // the job does not read as an unexplained failure. A verified no-op is
3060 // called out ahead of its own summary and apart from an ordinary
3061 // failure's `why` — this is the one candidate shape whose diagnostic a
3062 // human is expected to actually judge, not just skim.
3063 if state.viable().is_empty() {
3064 for c in &state.candidates {
3065 if let Some(evidence) = &c.verified_noop {
3066 parts.push(format!(
3067 "candidate {} (agent-verified no-op, unconfirmed by magi): {evidence}",
3068 c.label
3069 ));
3070 } else if !c.summary.trim().is_empty() {
3071 parts.push(format!("candidate {}: {}", c.label, c.summary.trim()));
3072 } else if let Some(why) = &c.failed {
3073 parts.push(format!("candidate {}: {why}", c.label));
3074 }
3075 }
3076 }
3077
3078 if parts.is_empty() {
3079 return None;
3080 }
3081 // `run::tail` prefixes an "N earlier bytes omitted" marker whose own
3082 // length depends on N, so asking it for exactly `DIAGNOSTIC_MAX` can come
3083 // back slightly over. Leave it enough room to always land under the
3084 // limit.
3085 Some(crate::run::tail(
3086 &parts.join("\n\n"),
3087 DIAGNOSTIC_MAX.saturating_sub(100),
3088 ))
3089}
3090
3091/// Stable lower-case name for a run status, for an internal log line and the
3092/// "graph stopped without reaching a terminal status" bug message in
3093/// [`settle`] — never for [`Task::last_error`] itself; see [`describe`]'s own
3094/// doc for why that one reads [`RunStatus::display_label`] instead. One
3095/// definition of a status's name, on the type that owns it: this table used
3096/// to live here as a second copy, and a status renamed in one place would
3097/// have gone on reading correctly in the other.
3098fn label(status: RunStatus) -> &'static str {
3099 status.as_str()
3100}
3101
3102/// Parse a merge mode override.
3103fn merge_mode(mode: &str) -> Result<MergeMode> {
3104 match mode {
3105 "none" => Ok(MergeMode::None),
3106 "local" => Ok(MergeMode::Local),
3107 "pr" => Ok(MergeMode::Pr),
3108 other => bail!("unknown merge mode `{other}`; expected none, local or pr"),
3109 }
3110}
3111
3112/// Take the status lock, recovering from a poisoned one.
3113///
3114/// A panic elsewhere must not silently stop the heartbeat: the status is plain
3115/// data, and the worst a poisoned lock can hold is a stale timestamp.
3116fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
3117 mutex
3118 .lock()
3119 .unwrap_or_else(std::sync::PoisonError::into_inner)
3120}
3121
3122#[cfg(test)]
3123mod tests {
3124 use super::*;
3125 use crate::queue::{Source, TaskStatus};
3126 use crate::run::{Candidate, CommandOutcome};
3127 use pretty_assertions::assert_eq;
3128
3129 fn task() -> Task {
3130 Task::new(
3131 "add retries".to_owned(),
3132 "add retries".to_owned(),
3133 PathBuf::from("/repo"),
3134 Source::Human,
3135 )
3136 }
3137
3138 /// A runnable task marked to interrupt, with an id fixed for assertions
3139 /// rather than the random one [`Task::new`] mints.
3140 fn interrupt_task(id: &str) -> Task {
3141 let mut t = task();
3142 t.id = id.to_owned();
3143 t.interrupt = true;
3144 t
3145 }
3146
3147 /// An ordinary runnable task with an id fixed for assertions.
3148 fn task_with_id(id: &str) -> Task {
3149 let mut t = task();
3150 t.id = id.to_owned();
3151 t
3152 }
3153
3154 /// A runnable task marked `--urgent`, with an id fixed for assertions.
3155 fn urgent_task(id: &str) -> Task {
3156 let mut t = task();
3157 t.id = id.to_owned();
3158 t.urgent = true;
3159 t
3160 }
3161
3162 /// The land-resume exemption wins outright, whether or not the candidate
3163 /// also happens to be marked [`Task::urgent`]: a resume's own "must not
3164 /// queue behind anything" guarantee cannot be weaker just because the
3165 /// same task was also filed with `--urgent`.
3166 #[test]
3167 fn permit_kind_prefers_a_land_resume_over_the_urgent_slot() {
3168 assert_eq!(permit_kind(true, false), PermitKind::None);
3169 assert_eq!(permit_kind(true, true), PermitKind::None);
3170 }
3171
3172 /// The one property this whole feature exists for: `--urgent` draws from
3173 /// its own slot, never the ordinary `max_concurrent_runs` pool - and an
3174 /// ordinary candidate draws from the ordinary pool exactly as before,
3175 /// untouched by the urgent slot's existence.
3176 #[test]
3177 fn permit_kind_separates_urgent_from_ordinary() {
3178 assert_eq!(permit_kind(false, true), PermitKind::Urgent);
3179 assert_eq!(permit_kind(false, false), PermitKind::Ordinary);
3180 }
3181
3182 /// The exact wiring `attempt` runs before minting anything: a config's
3183 /// `min_free_bytes` in, a task-holding reason naming both numbers out.
3184 /// Free space is injected rather than asked of the real disk - the point
3185 /// of [`disk_gate_with`] existing separately from [`disk_gate`] - so this
3186 /// is deterministic on every machine this test runs on, never dependent
3187 /// on how full the CI runner's own disk happens to be.
3188 #[test]
3189 fn disk_gate_with_holds_a_task_below_the_threshold_and_names_both_numbers() {
3190 let cfg = Config::default();
3191 let repo = Path::new("/any/repo/path");
3192
3193 let reason =
3194 disk_gate_with(repo, &cfg, |_| Ok(1024)).expect("must hold below the threshold");
3195 assert!(reason.contains("1024"), "{reason}");
3196 assert!(
3197 reason.contains(&cfg.disk.min_free_bytes.to_string()),
3198 "{reason}"
3199 );
3200
3201 assert_eq!(
3202 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes)),
3203 None,
3204 "exactly at the floor is open"
3205 );
3206 assert_eq!(
3207 disk_gate_with(repo, &cfg, |_| Ok(cfg.disk.min_free_bytes + 1)),
3208 None,
3209 "comfortably above the floor is open"
3210 );
3211 }
3212
3213 #[test]
3214 fn disk_gate_with_opens_unconditionally_when_the_operator_opted_out() {
3215 let mut cfg = Config::default();
3216 cfg.disk.min_free_bytes = 0;
3217 let repo = Path::new("/any/repo/path");
3218 assert_eq!(
3219 disk_gate_with(repo, &cfg, |_| Ok(0)),
3220 None,
3221 "a zero floor never measures at all"
3222 );
3223 }
3224
3225 #[test]
3226 fn disk_gate_with_closes_rather_than_starts_blind_when_it_cannot_measure() {
3227 let cfg = Config::default();
3228 let repo = Path::new("/any/repo/path");
3229 let reason = disk_gate_with(repo, &cfg, |_| Err(anyhow::anyhow!("no df on this box")))
3230 .expect("a measurement failure must close the gate, not open it");
3231 assert!(reason.contains("could not measure"), "{reason}");
3232 }
3233
3234 #[test]
3235 fn no_interrupt_task_leaves_the_sequence_idle_even_with_something_in_flight() {
3236 let ordinary = task();
3237 let next = advance_interrupt(
3238 Interrupt::Idle,
3239 std::slice::from_ref(&ordinary.id),
3240 std::slice::from_ref(&ordinary),
3241 );
3242 assert_eq!(next, Interrupt::Idle);
3243 }
3244
3245 #[test]
3246 fn an_interrupt_task_with_nothing_in_flight_never_starts_a_sequence() {
3247 // Nothing to interrupt - this is just an ordinary candidate, and the
3248 // loop's normal dispatch will pick it up like any other.
3249 let marked = interrupt_task("marked");
3250 let next = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3251 assert_eq!(next, Interrupt::Idle);
3252 }
3253
3254 #[test]
3255 fn an_interrupt_task_with_something_in_flight_starts_parking_it() {
3256 let marked = interrupt_task("marked");
3257 let next = advance_interrupt(
3258 Interrupt::Idle,
3259 &["running".to_owned()],
3260 std::slice::from_ref(&marked),
3261 );
3262 assert_eq!(
3263 next,
3264 Interrupt::Parking {
3265 parked: vec!["running".to_owned()],
3266 interrupt_task: "marked".to_owned(),
3267 }
3268 );
3269 }
3270
3271 /// R1-1-2 / R2-1-2: above the default `max_concurrent_runs`, more than
3272 /// one run can be in flight when a task becomes runnable and marked.
3273 /// Parking all of them would mean `Resuming` later has more than one id
3274 /// to release back to ordinary dispatch, which cannot be made safe
3275 /// against that same setting's own extra concurrency slots letting two
3276 /// of them start together - see `advance_interrupt`'s own `Idle` branch.
3277 /// The simplification the task's own constraints ask for: do not begin
3278 /// a sequence at all until the herd settles back to exactly one.
3279 #[test]
3280 fn more_than_one_run_in_flight_never_starts_an_interrupt_sequence() {
3281 let marked = interrupt_task("marked");
3282
3283 let two = advance_interrupt(
3284 Interrupt::Idle,
3285 &["a".to_owned(), "b".to_owned()],
3286 std::slice::from_ref(&marked),
3287 );
3288 assert_eq!(two, Interrupt::Idle);
3289
3290 let none = advance_interrupt(Interrupt::Idle, &[], std::slice::from_ref(&marked));
3291 assert_eq!(none, Interrupt::Idle, "nothing to interrupt either");
3292 }
3293
3294 #[test]
3295 fn parking_holds_until_every_parked_id_has_actually_left_flight() {
3296 let state = Interrupt::Parking {
3297 parked: vec!["running".to_owned()],
3298 interrupt_task: "marked".to_owned(),
3299 };
3300 // Still in flight: no change.
3301 let still_going = advance_interrupt(state.clone(), &["running".to_owned()], &[]);
3302 assert_eq!(still_going, state);
3303
3304 // Left flight, but the interrupt task has not been dispatched yet on
3305 // this tick - stays `Parking` so `interrupt_gate` can let it through,
3306 // as long as it is still runnable.
3307 let stopped_but_not_yet_dispatched =
3308 advance_interrupt(state.clone(), &[], &[interrupt_task("marked")]);
3309 assert_eq!(stopped_but_not_yet_dispatched, state);
3310
3311 // Left flight, and the interrupt task is now in flight itself.
3312 let dispatched = advance_interrupt(state, &["marked".to_owned()], &[]);
3313 assert_eq!(
3314 dispatched,
3315 Interrupt::Running {
3316 parked: vec!["running".to_owned()],
3317 interrupt_task: "marked".to_owned(),
3318 }
3319 );
3320 }
3321
3322 #[test]
3323 fn the_sequence_moves_to_resuming_the_instant_the_interrupt_tasks_own_run_leaves_flight() {
3324 let state = Interrupt::Running {
3325 parked: vec!["running".to_owned()],
3326 interrupt_task: "marked".to_owned(),
3327 };
3328 let still_running = advance_interrupt(state.clone(), &["marked".to_owned()], &[]);
3329 assert_eq!(still_running, state);
3330
3331 // Whatever it ended as - merged, failed, held - is not this
3332 // function's concern: leaving flight is the only trigger, driven
3333 // straight off the same in-flight list `poll` already reaps. It does
3334 // not go straight to `Idle`: see `Interrupt::Running`'s own doc for
3335 // why that would let an unrelated task start ahead of, or alongside,
3336 // the guaranteed resume.
3337 let ended = advance_interrupt(state, &[], &[task_with_id("running")]);
3338 assert_eq!(
3339 ended,
3340 Interrupt::Resuming {
3341 parked: vec!["running".to_owned()]
3342 }
3343 );
3344 }
3345
3346 #[test]
3347 fn resuming_ends_the_instant_a_parked_task_is_seen_in_flight() {
3348 let state = Interrupt::Resuming {
3349 parked: vec!["running".to_owned()],
3350 };
3351 let still_waiting = advance_interrupt(state.clone(), &[], &[task_with_id("running")]);
3352 assert_eq!(still_waiting, state);
3353
3354 let dispatched = advance_interrupt(state, &["running".to_owned()], &[]);
3355 assert_eq!(dispatched, Interrupt::Idle);
3356 }
3357
3358 /// R1-2-1: an interrupt task that stops being runnable - held, blocked,
3359 /// or otherwise moved on by an operator with no claim standing in the
3360 /// way - must not wedge the sequence (and so the whole loop's dispatch,
3361 /// via `interrupt_gate`) waiting forever for a dispatch that can never
3362 /// come. The parked run still gets its resume.
3363 #[test]
3364 fn an_interrupt_task_that_stops_being_runnable_abandons_the_wait_without_losing_the_parked_run()
3365 {
3366 let state = Interrupt::Parking {
3367 parked: vec!["running".to_owned()],
3368 interrupt_task: "marked".to_owned(),
3369 };
3370 // `marked` has been held/blocked/deleted since the sequence began:
3371 // it no longer appears in `runnable` at all.
3372 let next = advance_interrupt(state, &[], &[]);
3373 assert_eq!(
3374 next,
3375 Interrupt::Resuming {
3376 parked: vec!["running".to_owned()]
3377 },
3378 "abandoning the interrupt must not abandon the resume it owes"
3379 );
3380 }
3381
3382 /// The same abandonment, one step later: `Resuming` itself must not wait
3383 /// forever for a parked task that has since become unrunnable.
3384 #[test]
3385 fn resuming_abandons_a_parked_task_that_stops_being_runnable() {
3386 let state = Interrupt::Resuming {
3387 parked: vec!["running".to_owned()],
3388 };
3389 let next = advance_interrupt(state, &[], &[]);
3390 assert_eq!(
3391 next,
3392 Interrupt::Idle,
3393 "nothing is left to wait for; the loop must not stay wedged"
3394 );
3395 }
3396
3397 #[test]
3398 fn disabled_by_config_the_sequence_can_never_leave_idle() {
3399 let marked = interrupt_task("marked");
3400 let next = advance_interrupt_tick(
3401 false,
3402 Interrupt::Idle,
3403 &["running".to_owned()],
3404 std::slice::from_ref(&marked),
3405 );
3406 assert_eq!(
3407 next,
3408 Interrupt::Idle,
3409 "an unmarked, unconfigured daemon must behave exactly as before"
3410 );
3411 }
3412
3413 #[test]
3414 fn the_gate_blocks_everyone_while_something_parked_is_still_in_flight() {
3415 let state = Interrupt::Parking {
3416 parked: vec!["running".to_owned()],
3417 interrupt_task: "marked".to_owned(),
3418 };
3419 let candidates = vec![interrupt_task("marked"), task()];
3420 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3421 assert!(
3422 allowed.is_empty(),
3423 "nothing may dispatch - not even the interrupt task itself - \
3424 until the parked run has actually stopped"
3425 );
3426 }
3427
3428 /// `interrupt_gate` knows nothing about [`Task::urgent`] and must not
3429 /// grow a special case for it: an urgent candidate that is not the
3430 /// interrupt task withholds exactly like an ordinary one for as long as
3431 /// the parked run it is racing has not actually left flight. A version
3432 /// of this feature once bypassed the gate for urgent candidates, on the
3433 /// theory that a genuinely separate concurrency lane could not collide
3434 /// with 75dd's own; it could, and did - the bypassed task dispatched
3435 /// alongside a run 75dd's own state machine had only *asked* to park,
3436 /// not yet confirmed gone, which is exactly the second run
3437 /// `Interrupt::Parking`'s own doc says must never happen. There is no
3438 /// tick during Parking/Running/Resuming where letting an extra
3439 /// candidate through is safe, urgent or not - the parked run may still
3440 /// be genuinely mid-call.
3441 #[test]
3442 fn urgent_gains_no_exemption_from_an_active_interrupt_sequence() {
3443 for state in [
3444 Interrupt::Parking {
3445 parked: vec!["running".to_owned()],
3446 interrupt_task: "marked".to_owned(),
3447 },
3448 Interrupt::Running {
3449 parked: vec!["running".to_owned()],
3450 interrupt_task: "marked".to_owned(),
3451 },
3452 Interrupt::Resuming {
3453 parked: vec!["running".to_owned()],
3454 },
3455 ] {
3456 let candidates = vec![
3457 interrupt_task("marked"),
3458 urgent_task("hot"),
3459 task_with_id("ordinary"),
3460 ];
3461 let allowed = interrupt_gate(&state, &["running".to_owned()], candidates);
3462 assert!(
3463 !allowed.iter().any(|t| t.id == "hot"),
3464 "an urgent candidate must wait out the same gate as anything \
3465 else while the run it would run alongside has not actually \
3466 left flight, for state {state:?}: {allowed:?}"
3467 );
3468 }
3469 }
3470
3471 /// The one case where marking a task `--urgent` and `interrupt` at once
3472 /// is not redundant: once the interrupt sequence's own guaranteed
3473 /// resume/dispatch actually admits the task, it is unaffected by also
3474 /// carrying `urgent` - `interrupt_gate` decides purely on identity,
3475 /// never on the urgent flag.
3476 #[test]
3477 fn a_task_marked_both_urgent_and_interrupt_is_admitted_once_the_gate_itself_says_so() {
3478 let state = Interrupt::Resuming {
3479 parked: vec!["hot".to_owned()],
3480 };
3481 let candidates = vec![urgent_task("hot"), task()];
3482 let allowed = interrupt_gate(&state, &[], candidates);
3483 assert_eq!(
3484 allowed.iter().filter(|t| t.id == "hot").count(),
3485 1,
3486 "the gate's own decision is unaffected by the urgent flag: {allowed:?}"
3487 );
3488 }
3489
3490 #[test]
3491 fn the_gate_lets_only_the_interrupt_task_through_once_parked_work_has_stopped() {
3492 let state = Interrupt::Parking {
3493 parked: vec!["running".to_owned()],
3494 interrupt_task: "marked".to_owned(),
3495 };
3496 let other = task();
3497 let candidates = vec![interrupt_task("marked"), other.clone()];
3498 let allowed = interrupt_gate(&state, &[], candidates);
3499 assert_eq!(allowed.len(), 1);
3500 assert_eq!(allowed[0].id, "marked");
3501 }
3502
3503 #[test]
3504 fn the_gate_blocks_everyone_while_the_interrupt_task_itself_is_in_flight() {
3505 let state = Interrupt::Running {
3506 parked: vec!["running".to_owned()],
3507 interrupt_task: "marked".to_owned(),
3508 };
3509 let candidates = vec![task(), task()];
3510 let allowed = interrupt_gate(&state, &["marked".to_owned()], candidates);
3511 assert!(allowed.is_empty());
3512 }
3513
3514 /// R1-1-1 / R1-1-2: even when more than one task was in flight when the
3515 /// sequence began (only reachable above the default
3516 /// `max_concurrent_runs = 1`), `Resuming` offers at most one of them -
3517 /// never both in the same tick, which is what "exactly one resume, no
3518 /// simultaneous run" actually requires structurally rather than by
3519 /// coincidence of how many ordinary slots happen to be free.
3520 #[test]
3521 fn the_gate_offers_at_most_one_candidate_while_resuming_even_with_two_parked() {
3522 let state = Interrupt::Resuming {
3523 parked: vec!["a".to_owned(), "c".to_owned()],
3524 };
3525 let candidates = vec![task_with_id("a"), task_with_id("c"), task_with_id("other")];
3526 let allowed = interrupt_gate(&state, &[], candidates);
3527 assert_eq!(
3528 allowed.len(),
3529 1,
3530 "at most one candidate may be offered while resuming: {allowed:?}"
3531 );
3532 assert_eq!(allowed[0].id, "a");
3533 }
3534
3535 #[test]
3536 fn the_gate_offers_nothing_while_resuming_if_no_parked_task_is_runnable() {
3537 let state = Interrupt::Resuming {
3538 parked: vec!["a".to_owned()],
3539 };
3540 let allowed = interrupt_gate(&state, &[], vec![task_with_id("other")]);
3541 assert!(allowed.is_empty());
3542 }
3543
3544 /// The invariant the completion criteria ask for by name: across a whole
3545 /// simulated sequence, there is never a tick where the gate would let
3546 /// through both the parked run's resume and the interrupt task, and
3547 /// exactly one candidate resumes the instant the interrupt task's run
3548 /// ends - never zero, never more than one.
3549 #[test]
3550 fn a_full_sequence_never_gates_two_runs_through_at_once_and_resumes_exactly_one() {
3551 let running = task(); // id: whatever `Task::new` minted
3552 let marked = interrupt_task("marked");
3553
3554 let mut state = Interrupt::Idle;
3555 // Tick 1: `running` is in flight, `marked` becomes runnable.
3556 let in_flight = vec![running.id.clone()];
3557 state = advance_interrupt_tick(true, state, &in_flight, std::slice::from_ref(&marked));
3558 let gated = interrupt_gate(&state, &in_flight, vec![marked.clone(), running.clone()]);
3559 assert!(gated.is_empty(), "still waiting on `running` to park");
3560
3561 // Tick 2: `running` parked and left flight; nothing dispatched yet.
3562 state = advance_interrupt_tick(true, state, &[], &[marked.clone(), running.clone()]);
3563 let gated = interrupt_gate(&state, &[], vec![marked.clone(), running.clone()]);
3564 assert_eq!(
3565 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3566 vec!["marked"],
3567 "only the interrupt task may be offered to the dispatcher now"
3568 );
3569
3570 // Tick 3: `marked` is now in flight (dispatched from tick 2's gate).
3571 state = advance_interrupt_tick(
3572 true,
3573 state,
3574 &["marked".to_owned()],
3575 std::slice::from_ref(&running),
3576 );
3577 let gated = interrupt_gate(
3578 &state,
3579 &["marked".to_owned()],
3580 vec![marked.clone(), running.clone()],
3581 );
3582 assert!(
3583 gated.is_empty(),
3584 "the parked run must not be offered back while the interrupt \
3585 task is still running"
3586 );
3587
3588 // Tick 4: `marked`'s run reached a terminal status and left flight.
3589 // A higher-priority ordinary task `other` is also runnable now - it
3590 // must not be let through instead of, or alongside, `running`.
3591 let other = task_with_id("other");
3592 state = advance_interrupt_tick(true, state, &[], &[running.clone(), other.clone()]);
3593 assert_eq!(
3594 state,
3595 Interrupt::Resuming {
3596 parked: vec![running.id.clone()]
3597 }
3598 );
3599 let gated = interrupt_gate(&state, &[], vec![other.clone(), running.clone()]);
3600 assert_eq!(
3601 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3602 vec![running.id.as_str()],
3603 "exactly the parked run resumes - not the unrelated task, even \
3604 though it was offered first"
3605 );
3606
3607 // Tick 5: `running` is now in flight (dispatched from tick 4's
3608 // gate). Only now does the sequence end and ordinary dispatch fully
3609 // resume.
3610 state = advance_interrupt_tick(
3611 true,
3612 state,
3613 std::slice::from_ref(&running.id),
3614 std::slice::from_ref(&other),
3615 );
3616 assert_eq!(state, Interrupt::Idle);
3617 let gated = interrupt_gate(
3618 &state,
3619 std::slice::from_ref(&running.id),
3620 vec![other.clone()],
3621 );
3622 assert_eq!(
3623 gated.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
3624 vec![other.id.as_str()],
3625 "ordinary dispatch is unrestricted again"
3626 );
3627 }
3628
3629 #[test]
3630 fn every_run_status_settles_the_task_it_came_from() {
3631 // run status, resulting task status, attempts still standing after one
3632 let table = [
3633 (RunStatus::Merged, TaskStatus::Done, 1),
3634 (RunStatus::Ready, TaskStatus::Done, 1),
3635 (RunStatus::Stalled, TaskStatus::Failed, 0),
3636 (RunStatus::Blocked, TaskStatus::Failed, 1),
3637 (RunStatus::Failed, TaskStatus::Failed, 1),
3638 (RunStatus::VerifiedNoop, TaskStatus::Held, 1),
3639 (RunStatus::Prep, TaskStatus::Failed, 1),
3640 (RunStatus::Implementing, TaskStatus::Failed, 1),
3641 (RunStatus::Judging, TaskStatus::Failed, 1),
3642 (RunStatus::Deliberating, TaskStatus::Failed, 1),
3643 (RunStatus::Voting, TaskStatus::Failed, 1),
3644 (RunStatus::Reviewing, TaskStatus::Failed, 1),
3645 (RunStatus::Gating, TaskStatus::Failed, 1),
3646 ];
3647 for (run, want, attempts) in table {
3648 let mut t = task();
3649 t.start("20260902-000000-aaaa".to_owned());
3650 settle(
3651 &mut t,
3652 Verdict {
3653 status: run,
3654 left_pr: false,
3655 parked: false,
3656 quota_hit: matches!(run, RunStatus::Stalled),
3657 no_viable_candidates: false,
3658 },
3659 "why",
3660 2,
3661 );
3662 assert_eq!(t.status, want, "task status after {}", label(run));
3663 assert_eq!(t.attempts, attempts, "attempts after {}", label(run));
3664 }
3665 }
3666
3667 #[test]
3668 fn a_quota_stall_costs_the_task_no_attempt_but_a_block_does() {
3669 let mut stalled = task();
3670 stalled.start("20260902-000000-aaaa".to_owned());
3671 settle(
3672 &mut stalled,
3673 Verdict {
3674 status: RunStatus::Stalled,
3675 left_pr: false,
3676 parked: false,
3677 quota_hit: true,
3678 no_viable_candidates: false,
3679 },
3680 "quota",
3681 1,
3682 );
3683 assert_eq!(stalled.attempts, 0);
3684 assert!(
3685 stalled.status.runnable(),
3686 "a machine problem must leave the task in line"
3687 );
3688
3689 let mut blocked = task();
3690 blocked.start("20260902-000000-aaaa".to_owned());
3691 settle(
3692 &mut blocked,
3693 Verdict {
3694 status: RunStatus::Blocked,
3695 left_pr: false,
3696 parked: false,
3697 quota_hit: false,
3698 no_viable_candidates: false,
3699 },
3700 "findings open",
3701 1,
3702 );
3703 assert_eq!(blocked.attempts, 1);
3704 assert_eq!(
3705 blocked.status,
3706 TaskStatus::Held,
3707 "the last attempt hands the task to a human"
3708 );
3709 }
3710
3711 #[test]
3712 fn a_run_that_opened_a_pull_request_is_never_re_competed() {
3713 // Attempts to spare: without the pull request this task would go
3714 // straight back in line and run the whole competition again.
3715 let mut delivered = task();
3716 delivered.start("20260903-080619-01c2".to_owned());
3717 settle(
3718 &mut delivered,
3719 Verdict {
3720 status: RunStatus::Blocked,
3721 left_pr: true,
3722 parked: false,
3723 quota_hit: false,
3724 no_viable_candidates: false,
3725 },
3726 "no check status",
3727 4,
3728 );
3729 assert_eq!(
3730 delivered.status,
3731 TaskStatus::Held,
3732 "a pull request waiting on CI or a person is not a retryable failure"
3733 );
3734 assert!(
3735 !delivered.status.runnable(),
3736 "the loop must not pick this task up again"
3737 );
3738 assert_eq!(
3739 delivered.last_error.as_deref(),
3740 Some("no check status"),
3741 "the operator needs to be told what the gate was waiting for"
3742 );
3743
3744 // The same status without a pull request is a plain failure, and with
3745 // attempts left it is retried.
3746 let mut empty_handed = task();
3747 empty_handed.start("20260903-080619-01c2".to_owned());
3748 settle(
3749 &mut empty_handed,
3750 Verdict {
3751 status: RunStatus::Blocked,
3752 left_pr: false,
3753 parked: false,
3754 quota_hit: false,
3755 no_viable_candidates: false,
3756 },
3757 "findings open",
3758 4,
3759 );
3760 assert_eq!(empty_handed.status, TaskStatus::Failed);
3761 assert!(empty_handed.status.runnable());
3762 }
3763
3764 #[test]
3765 fn a_verified_noop_run_hands_off_rather_than_closing_or_auto_retrying() {
3766 // Every candidate agreed, with evidence, that nothing belonged in the
3767 // worktree. That is not a confirmed success to close automatically -
3768 // a human still has to check the claim - and it is not an ordinary
3769 // failure either, so this settles exactly like a pull request nobody
3770 // merged yet: `Held`, same as `Blocked` with a PR.
3771 let mut noop = task();
3772 noop.start("20260912-131304-391f".to_owned());
3773 settle(
3774 &mut noop,
3775 Verdict {
3776 status: RunStatus::VerifiedNoop,
3777 left_pr: false,
3778 parked: false,
3779 quota_hit: false,
3780 no_viable_candidates: true,
3781 },
3782 "candidate A: already fixed by b32cfc4, on main",
3783 4,
3784 );
3785 assert_eq!(
3786 noop.status,
3787 TaskStatus::Held,
3788 "an unverified claim is a request for a human, not a failure"
3789 );
3790 assert!(
3791 !noop.status.runnable(),
3792 "the loop must not requeue this on the same unverified claim"
3793 );
3794 // `Task::release` resets attempts to zero the moment a human looks at
3795 // the evidence and lets it run again, so it does not matter here
3796 // whether the one attempt already spent stays spent - what matters is
3797 // that nothing retries this task unattended in the meantime.
3798 assert_eq!(noop.attempts, 1);
3799 }
3800
3801 #[test]
3802 fn parking_costs_the_task_no_attempt_and_leaves_it_in_line() {
3803 // Parking is the operator asking for the process back - to replace the
3804 // binary, most of all. The run's work is intact on disk, so this is
3805 // not a failed attempt, and charging for it would mean a few upgrades
3806 // could exhaust a budget meant for agents that misbehaved.
3807 let mut parked = task();
3808 parked.start("20260903-183634-2d98".to_owned());
3809 settle(
3810 &mut parked,
3811 Verdict {
3812 status: RunStatus::Implementing,
3813 left_pr: false,
3814 quota_hit: false,
3815 parked: true,
3816 no_viable_candidates: false,
3817 },
3818 "parked after `implementing`",
3819 2,
3820 );
3821 assert_eq!(parked.attempts, 0, "a park is refunded");
3822 assert!(
3823 parked.status.runnable(),
3824 "and the task stays in line so the next loop resumes its run"
3825 );
3826 assert_eq!(
3827 parked.last_error.as_deref(),
3828 Some("parked after `implementing`"),
3829 "the card says where it stopped"
3830 );
3831
3832 // Without the park flag the same non-terminal status is what it always
3833 // was: `execute` returning mid-flight, which is a bug and spends an
3834 // attempt so a task cannot loop on it forever.
3835 let mut broken = task();
3836 broken.start("20260903-183634-2d98".to_owned());
3837 settle(
3838 &mut broken,
3839 Verdict {
3840 status: RunStatus::Implementing,
3841 left_pr: false,
3842 quota_hit: false,
3843 parked: false,
3844 no_viable_candidates: false,
3845 },
3846 "returned mid-flight",
3847 2,
3848 );
3849 assert_eq!(broken.attempts, 1);
3850 }
3851
3852 #[test]
3853 fn only_a_rate_limit_buys_the_task_its_attempt_back() {
3854 // Run e633: quorum lost because two judges answered with the wrong
3855 // JSON shape, `quota: []`. Refunding that takes the bound off the
3856 // retry loop, and each retry pays for a fresh hour-long implement
3857 // wave before it can fail the same way.
3858 let mut flaky = task();
3859 flaky.start("20260903-123023-e633".to_owned());
3860 settle(
3861 &mut flaky,
3862 Verdict {
3863 status: RunStatus::Stalled,
3864 left_pr: false,
3865 parked: false,
3866 quota_hit: false,
3867 no_viable_candidates: false,
3868 },
3869 "verdict rests on 1 of 3 judges",
3870 2,
3871 );
3872 assert_eq!(
3873 flaky.attempts, 1,
3874 "flakiness spends an attempt, so `max_attempts` still bounds it"
3875 );
3876 assert!(flaky.status.runnable(), "and it is still worth retrying");
3877
3878 // The same status, lost to a rate limit, is the machine's fault.
3879 let mut limited = task();
3880 limited.start("20260903-123023-e633".to_owned());
3881 settle(
3882 &mut limited,
3883 Verdict {
3884 status: RunStatus::Stalled,
3885 left_pr: false,
3886 parked: false,
3887 quota_hit: true,
3888 no_viable_candidates: false,
3889 },
3890 "judge-2, judge-3 out of quota",
3891 2,
3892 );
3893 assert_eq!(limited.attempts, 0, "a quota window is refunded");
3894 assert!(limited.status.runnable());
3895
3896 // And the bound really binds: a task that keeps stalling on flakiness
3897 // reaches a human instead of running the roster forever.
3898 let mut worn = task();
3899 for _ in 0..2 {
3900 worn.release();
3901 }
3902 worn.start("20260903-123023-e633".to_owned());
3903 worn.attempts = 2;
3904 settle(
3905 &mut worn,
3906 Verdict {
3907 status: RunStatus::Stalled,
3908 left_pr: false,
3909 parked: false,
3910 quota_hit: false,
3911 no_viable_candidates: false,
3912 },
3913 "no quorum again",
3914 2,
3915 );
3916 assert_eq!(worn.status, TaskStatus::Held);
3917 assert!(!worn.status.runnable());
3918 }
3919
3920 #[test]
3921 fn a_quota_wipeout_that_leaves_nothing_to_judge_also_costs_no_attempt() {
3922 // The implement wave loses every seat to the same rate limit and
3923 // `after_implement` bails with nothing viable, which surfaces as
3924 // `Failed` rather than `Stalled`. That is the same machine fact the
3925 // `Stalled`-quota row already refunds, and must be refunded the same
3926 // way, or a quota outage quietly holds every task it touches instead
3927 // of leaving them in line for the reset.
3928 let mut wiped_out = task();
3929 wiped_out.start("20260907-025000-a1b2".to_owned());
3930 settle(
3931 &mut wiped_out,
3932 Verdict {
3933 status: RunStatus::Failed,
3934 left_pr: false,
3935 parked: false,
3936 quota_hit: true,
3937 no_viable_candidates: true,
3938 },
3939 "no candidate produced a change; nothing to judge",
3940 2,
3941 );
3942 assert_eq!(wiped_out.attempts, 0, "a total quota wipeout is refunded");
3943 assert!(
3944 wiped_out.status.runnable(),
3945 "a machine problem must leave the task in line"
3946 );
3947
3948 // This is the exemption that must stay narrow: a candidate that did
3949 // produce a change, and then failed for some other reason, still
3950 // spends the attempt even though a seat elsewhere hit its quota.
3951 // Otherwise every ordinary failure that happens to share a run with
3952 // an unrelated rate limit would be refunded for free.
3953 let mut partial_progress = task();
3954 partial_progress.start("20260907-025500-c3d4".to_owned());
3955 settle(
3956 &mut partial_progress,
3957 Verdict {
3958 status: RunStatus::Failed,
3959 left_pr: false,
3960 parked: false,
3961 quota_hit: true,
3962 no_viable_candidates: false,
3963 },
3964 "gate failed on the winning candidate",
3965 2,
3966 );
3967 assert_eq!(
3968 partial_progress.attempts, 1,
3969 "a candidate that actually produced a change spends the attempt \
3970 even though some other seat hit its quota"
3971 );
3972 assert!(partial_progress.status.runnable());
3973 }
3974
3975 #[test]
3976 fn reclaim_refunds_a_recovered_quota_wipeout_the_same_way_a_live_settle_does() {
3977 // `reclaim` builds its own `Verdict` from a `RunState` it loads off
3978 // disk, and that construction must reach the same conclusion as the
3979 // one `attempt` builds from a live run, or a crash at exactly the
3980 // wrong moment gives a recovered task a different policy than one a
3981 // daemon finished settling itself.
3982 let mut t = task();
3983 t.start("20260907-025000-a1b2".to_owned());
3984 let mut state = run_state(RunStatus::Failed);
3985 state.quota.push(QuotaLoss {
3986 seat: "cand-a".to_owned(),
3987 node: "implement".to_owned(),
3988 at: Timestamp::now(),
3989 reset: None,
3990 });
3991 assert!(
3992 state.viable().is_empty(),
3993 "no candidate was added, so nothing is viable"
3994 );
3995 reclaim(&mut t, Some(state), 2);
3996 assert_eq!(t.attempts, 0, "a recovered quota wipeout is refunded");
3997 assert!(t.status.runnable());
3998 }
3999
4000 #[test]
4001 fn a_held_task_is_never_offered_to_the_loop() {
4002 let dir = tempfile::tempdir().unwrap();
4003 let queue = Queue::at(dir.path().to_path_buf());
4004 for (n, priority) in [(1, 0), (2, 5), (3, 5)] {
4005 let mut t = task();
4006 t.id = format!("2026090{n}-000000-000{n}");
4007 t.priority = priority;
4008 queue.put(&mut t).unwrap();
4009 }
4010 let mut held = task();
4011 held.id = "20260909-000000-9999".to_owned();
4012 held.priority = 99;
4013 held.hold_machine(None);
4014 queue.put(&mut held).unwrap();
4015
4016 let order: Vec<String> = runnable(&queue).into_iter().map(|t| t.id).collect();
4017 assert_eq!(order.len(), 3);
4018 assert!(!order.contains(&held.id));
4019 assert_eq!(
4020 order.first().cloned(),
4021 queue.next_runnable().map(|t| t.id),
4022 "the loop's first candidate is exactly what the queue offers"
4023 );
4024 assert_eq!(
4025 order,
4026 vec![
4027 "20260902-000000-0002".to_owned(),
4028 "20260903-000000-0003".to_owned(),
4029 "20260901-000000-0001".to_owned(),
4030 ],
4031 "priority first, then oldest, so nothing starves"
4032 );
4033 }
4034
4035 #[test]
4036 fn sweep_removes_an_old_unparseable_lock_and_keeps_a_live_one() {
4037 let dir = tempfile::tempdir().unwrap();
4038 let queue = Queue::at(dir.path().to_path_buf());
4039 let mut old = task();
4040 old.id = "20260101-000000-old0".to_owned();
4041 queue.put(&mut old).unwrap();
4042 let mut fresh = task();
4043 fresh.id = "20260101-000000-new0".to_owned();
4044 queue.put(&mut fresh).unwrap();
4045
4046 // No parseable pid at all, so age is the only signal there is to
4047 // check - unlike a real `Queue::claim`, which always names a real,
4048 // and therefore alive, pid this test cannot fake as dead.
4049 std::fs::write(dir.path().join(format!("{}.lock", old.id)), "not a pid").unwrap();
4050 std::thread::sleep(Duration::from_millis(60));
4051 let live = queue.claim(&fresh.id).unwrap();
4052
4053 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4054 assert_eq!(swept, vec![old.id.clone()]);
4055 assert!(
4056 queue.claim(&old.id).is_ok(),
4057 "an unparseable lock older than the threshold is swept"
4058 );
4059 assert!(
4060 queue.claim(&fresh.id).is_err(),
4061 "a live pid protects its lock regardless of age"
4062 );
4063 drop(live);
4064 }
4065
4066 #[test]
4067 fn an_old_lock_whose_pid_is_still_alive_is_never_swept_by_age_alone() {
4068 // The regression this guards: `sweep` now runs concurrently with
4069 // every attempt this daemon itself has spawned (see
4070 // `InFlightGuard`), not only between them the way a single
4071 // sequential loop once did. A run that legitimately outlives
4072 // `older_than` still has this very process's own live pid sitting in
4073 // its own lock file on every later sweep, and deciding by age alone
4074 // would delete that still-valid claim out from under the attempt
4075 // that holds it - which `reclaim_orphaned_running` would then read
4076 // as abandoned and hand to a second, competing attempt.
4077 let dir = tempfile::tempdir().unwrap();
4078 let queue = Queue::at(dir.path().to_path_buf());
4079 let mut t = task();
4080 t.id = "20260101-000000-live".to_owned();
4081 queue.put(&mut t).unwrap();
4082
4083 let claim = queue.claim(&t.id).unwrap();
4084 std::thread::sleep(Duration::from_millis(60));
4085
4086 let swept = sweep_stale_claims(&queue, Duration::from_millis(50));
4087 assert!(
4088 swept.is_empty(),
4089 "a lock naming a live pid must never be swept by age, no matter how old: {swept:?}"
4090 );
4091 assert!(
4092 queue.claim(&t.id).is_err(),
4093 "the lock still protects its task"
4094 );
4095 drop(claim);
4096 }
4097
4098 /// このテストプロセスにはなり得ない決定的なフィクスチャ PID。
4099 /// OS 上の状態は意図的に無関係で、各利用箇所が方針問い合わせを注入する。
4100 fn injected_dead_pid() -> u32 {
4101 std::process::id().checked_add(1).unwrap_or(1)
4102 }
4103
4104 #[test]
4105 fn a_lock_naming_a_dead_pid_is_swept_at_once_regardless_of_age() {
4106 let dir = tempfile::tempdir().unwrap();
4107 let queue = Queue::at(dir.path().to_path_buf());
4108 let mut t = task();
4109 t.id = "20260101-000000-dead".to_owned();
4110 queue.put(&mut t).unwrap();
4111 let dead_pid = injected_dead_pid();
4112
4113 // Written directly rather than through `Queue::claim`, which would
4114 // stamp this test process's own very much alive pid and defeat the
4115 // point: this is what a `.lock` left by a `SIGKILL`ed daemon looks
4116 // like moments after it died, not six hours later.
4117 std::fs::write(
4118 dir.path().join(format!("{}.lock", t.id)),
4119 dead_pid.to_string(),
4120 )
4121 .unwrap();
4122
4123 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4124 pid != dead_pid
4125 });
4126 assert_eq!(
4127 swept,
4128 vec![t.id.clone()],
4129 "a dead owner is reclaimed immediately, not after STALE_CLAIM"
4130 );
4131 assert!(queue.claim(&t.id).is_ok(), "the task is claimable again");
4132 }
4133
4134 #[test]
4135 fn sweeping_on_every_poll_catches_a_lock_that_appears_after_the_first_sweep() {
4136 let dir = tempfile::tempdir().unwrap();
4137 let queue = Queue::at(dir.path().to_path_buf());
4138 let mut t = task();
4139 t.id = "20260101-000000-late".to_owned();
4140 queue.put(&mut t).unwrap();
4141 let dead_pid = injected_dead_pid();
4142
4143 // Tick one, standing in for the sweep `poll` already runs at
4144 // startup: nothing to find yet.
4145 assert!(
4146 sweep_stale_claims(&queue, Duration::from_secs(6 * 60 * 60)).is_empty(),
4147 "nothing has claimed the task yet"
4148 );
4149
4150 // A second daemon claims the task and dies before it ever writes
4151 // `running`, well after this loop's own startup sweep already ran.
4152 std::fs::write(
4153 dir.path().join(format!("{}.lock", t.id)),
4154 dead_pid.to_string(),
4155 )
4156 .unwrap();
4157
4158 // Tick two, standing in for a poll long into this daemon's uptime:
4159 // the same function, called again, notices what only just appeared -
4160 // proving the sweep is not a one-shot startup check.
4161 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4162 pid != dead_pid
4163 });
4164 assert_eq!(swept, vec![t.id.clone()]);
4165 }
4166
4167 #[test]
4168 fn a_running_task_behind_a_dead_daemons_lock_recovers_once_swept_and_keeps_its_history() {
4169 // `reclaim_orphaned_running` looks up the task's last run, which
4170 // touches `run::home()`; the first call anywhere in this binary wins,
4171 // so this is a no-op if another test already pinned one, and either
4172 // way the run id below is never written under it.
4173 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4174 let dir = tempfile::tempdir().unwrap();
4175 let queue = Queue::at(dir.path().to_path_buf());
4176 let mut t = task();
4177 t.id = "20260101-000000-crsh".to_owned();
4178 t.status = TaskStatus::Running;
4179 t.attempts = 1;
4180 // No `run.json` behind this id: standing in for a run this test does
4181 // not need to make readable, since the point is the lock, not the
4182 // recovery table `reclaim` already has its own tests for.
4183 t.runs.push("20260904-000000-4043".to_owned());
4184 queue.put(&mut t).unwrap();
4185 let dead_pid = injected_dead_pid();
4186
4187 // The crashed daemon's own claim, naming a pid nothing on the
4188 // machine holds anymore.
4189 std::fs::write(
4190 dir.path().join(format!("{}.lock", t.id)),
4191 dead_pid.to_string(),
4192 )
4193 .unwrap();
4194
4195 // Before the lock is swept the task looks claimed, and
4196 // `reclaim_orphaned_running` must leave it alone - this is exactly
4197 // the bug: a `running` task stranded behind a dead daemon's lock,
4198 // invisible to the claim-as-proof check because the lock outlived
4199 // the process that wrote it.
4200 assert!(reclaim_orphaned_running(&queue, 2).is_empty());
4201 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
4202
4203 let swept = sweep_stale_claims_with(&queue, Duration::from_secs(6 * 60 * 60), |pid| {
4204 pid != dead_pid
4205 });
4206 assert_eq!(swept, vec![t.id.clone()]);
4207
4208 let reclaimed = reclaim_orphaned_running(&queue, 2);
4209 assert_eq!(reclaimed, vec![t.id.clone()]);
4210 let after = queue.get(&t.id).unwrap();
4211 assert_eq!(
4212 after.status,
4213 TaskStatus::Held,
4214 "no run.json to recover from, so a human is asked"
4215 );
4216 assert_eq!(
4217 after.runs,
4218 vec!["20260904-000000-4043".to_owned()],
4219 "the crashed run's id is kept as evidence, not discarded"
4220 );
4221 }
4222
4223 #[test]
4224 fn a_lock_is_kept_when_the_process_query_is_unavailable() {
4225 let dir = tempfile::tempdir().unwrap();
4226 let queue = Queue::at(dir.path().to_path_buf());
4227 let mut t = task();
4228 t.id = "20260101-000000-unknown".to_owned();
4229 queue.put(&mut t).unwrap();
4230 let dead_pid = injected_dead_pid();
4231 std::fs::write(
4232 dir.path().join(format!("{}.lock", t.id)),
4233 dead_pid.to_string(),
4234 )
4235 .unwrap();
4236
4237 let swept = sweep_stale_claims_with(&queue, Duration::ZERO, |_| true);
4238 assert!(swept.is_empty(), "an unknown pid must keep its lock");
4239 assert!(queue.claim(&t.id).is_err(), "the lock remains protective");
4240 }
4241
4242 fn run_state(status: RunStatus) -> RunState {
4243 let mut state = RunState::new(
4244 PathBuf::from("/repo"),
4245 "main".to_owned(),
4246 "abc1234def".to_owned(),
4247 "add retries".to_owned(),
4248 Config::default(),
4249 );
4250 state.status = status;
4251 state
4252 }
4253
4254 fn candidate(label: char, summary: &str, empty: bool, failed: Option<&str>) -> Candidate {
4255 Candidate {
4256 index: 0,
4257 label,
4258 agent: "claude".to_owned(),
4259 branch: format!("magi/x/{label}"),
4260 worktree: PathBuf::from("/repo"),
4261 summary: summary.to_owned(),
4262 stat: String::new(),
4263 files: 0,
4264 commits: usize::from(!empty),
4265 empty,
4266 failed: failed.map(str::to_owned),
4267 verified_noop: None,
4268 duration_ms: 0,
4269 folded: false,
4270 }
4271 }
4272
4273 #[test]
4274 fn diagnostic_names_the_failing_gate_checks_and_their_output() {
4275 let mut state = run_state(RunStatus::Blocked);
4276 state.gate = vec![
4277 CommandOutcome {
4278 command: "cargo make check".to_owned(),
4279 code: Some(0),
4280 output_tail: "ok".to_owned(),
4281 duration_ms: 0,
4282 resource_blocked: false,
4283 },
4284 CommandOutcome {
4285 command: "cargo test".to_owned(),
4286 code: Some(101),
4287 output_tail: "thread 'x' panicked: assertion failed".to_owned(),
4288 duration_ms: 0,
4289 resource_blocked: false,
4290 },
4291 ];
4292 let d = diagnostic(&state).expect("a failing gate must produce a diagnostic");
4293 assert!(d.contains("cargo test"), "{d}");
4294 assert!(
4295 !d.contains("cargo make check"),
4296 "a passing check is not a diagnostic: {d}"
4297 );
4298 assert!(d.contains("assertion failed"), "{d}");
4299 }
4300
4301 #[test]
4302 fn diagnostic_names_the_checks_the_fixer_gave_up_in_front_of() {
4303 let mut state = run_state(RunStatus::Blocked);
4304 state.event(
4305 "land",
4306 "stopped: the fixer produced no commit while 2 check(s) were failing \
4307 (build, lint); stopping instead of looping on an unchanged tree",
4308 );
4309 let d = diagnostic(&state).expect("a stalled land loop must produce a diagnostic");
4310 assert!(d.contains("build"), "{d}");
4311 assert!(d.contains("lint"), "{d}");
4312 assert!(d.contains("fixer produced no commit"), "{d}");
4313 }
4314
4315 #[test]
4316 fn describe_never_leaves_a_verified_noop_reading_as_a_bare_status_code() {
4317 // `describe`'s output becomes `Task::last_error` verbatim, and the
4318 // phone renders that in the same alarm-styled box an ordinary
4319 // failure gets. A bare `verified_noop` there would read exactly like
4320 // the failure this status exists to be told apart from.
4321 let state = run_state(RunStatus::VerifiedNoop);
4322 let d = describe(&state);
4323 assert!(
4324 d.contains("agent-verified no-op"),
4325 "expected the display label, not the wire spelling: {d}"
4326 );
4327 assert!(!d.contains("verified_noop"), "{d}");
4328 }
4329
4330 #[test]
4331 fn diagnostic_carries_a_candidates_own_final_word_when_none_was_viable() {
4332 // The whole point of the feature: a run held as "no candidate produced
4333 // a change" can mean the implementer actually finished the task and
4334 // only left a clean local tree behind - see AGENTS.md on this exact
4335 // failure mode. The diagnostic has to carry what the agent actually
4336 // said, not just the fact that nothing was there to judge.
4337 let mut state = run_state(RunStatus::Failed);
4338 state.candidates = vec![candidate(
4339 'A',
4340 "opened pull request #42, merged it, tagged v1.2.3 and published the release",
4341 true,
4342 None,
4343 )];
4344 let d = diagnostic(&state).expect("an empty candidate with a summary must be surfaced");
4345 assert!(d.contains("candidate A"), "{d}");
4346 assert!(d.contains("tagged v1.2.3"), "{d}");
4347 }
4348
4349 #[test]
4350 fn diagnostic_falls_back_to_a_candidates_failure_reason_when_it_has_no_summary() {
4351 let mut state = run_state(RunStatus::Failed);
4352 state.candidates = vec![candidate('A', "", true, Some("agent timed out"))];
4353 let d = diagnostic(&state).expect("a candidate's own failure reason must be surfaced");
4354 assert!(d.contains("candidate A"), "{d}");
4355 assert!(d.contains("agent timed out"), "{d}");
4356 }
4357
4358 #[test]
4359 fn diagnostic_is_none_when_nothing_recognisable_explains_the_hold() {
4360 // A viable candidate existed, the gate never ran, and nothing land
4361 // said matches - `Task::last_error` is left to explain this one alone.
4362 let mut state = run_state(RunStatus::Failed);
4363 state.candidates = vec![candidate('A', "did the work", false, None)];
4364 assert!(diagnostic(&state).is_none());
4365 }
4366
4367 #[test]
4368 fn diagnostic_is_bounded_however_much_a_run_printed() {
4369 let mut state = run_state(RunStatus::Blocked);
4370 state.gate = vec![
4371 CommandOutcome {
4372 command: "cargo test".to_owned(),
4373 code: Some(101),
4374 output_tail: "x".repeat(50_000),
4375 duration_ms: 0,
4376 resource_blocked: false,
4377 },
4378 CommandOutcome {
4379 command: "cargo clippy".to_owned(),
4380 code: Some(1),
4381 output_tail: "y".repeat(50_000),
4382 duration_ms: 0,
4383 resource_blocked: false,
4384 },
4385 ];
4386 state.candidates = vec![
4387 candidate('A', &"z".repeat(50_000), true, None),
4388 candidate('B', &"w".repeat(50_000), true, None),
4389 ];
4390 let d = diagnostic(&state).expect("plenty here to diagnose");
4391 assert!(
4392 d.len() <= DIAGNOSTIC_MAX,
4393 "diagnostic grew to {} bytes, unbounded",
4394 d.len()
4395 );
4396 }
4397
4398 #[test]
4399 fn settle_and_diagnose_attaches_a_diagnostic_only_once_the_task_is_held() {
4400 let mut state = run_state(RunStatus::Blocked);
4401 state.gate = vec![CommandOutcome {
4402 command: "cargo test".to_owned(),
4403 code: Some(101),
4404 output_tail: "assertion failed".to_owned(),
4405 duration_ms: 0,
4406 resource_blocked: false,
4407 }];
4408 let verdict = Verdict {
4409 status: RunStatus::Blocked,
4410 left_pr: false,
4411 quota_hit: false,
4412 parked: false,
4413 no_viable_candidates: false,
4414 };
4415
4416 // Attempt one of two still has a retry coming: no diagnostic yet, the
4417 // task is going to run again and this run's evidence would go stale.
4418 let mut t = task();
4419 t.start("run-1".to_owned());
4420 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4421 assert_eq!(t.status, TaskStatus::Failed);
4422 assert!(t.diagnostic.is_none());
4423
4424 // Attempt two exhausts the budget: now it is held, and the
4425 // diagnostic is what `magi task show` has to say more than one line.
4426 t.start("run-2".to_owned());
4427 settle_and_diagnose(&mut t, verdict, "gate failed", 2, &state);
4428 assert_eq!(t.status, TaskStatus::Held);
4429 let d = t.diagnostic.expect("a held task must carry its diagnostic");
4430 assert!(d.contains("cargo test"), "{d}");
4431 }
4432
4433 fn approval_question(run: &str) -> ask::Question {
4434 ask::Question::new(
4435 run.to_owned(),
4436 land::APPROVAL_NODE.to_owned(),
4437 "land".to_owned(),
4438 "merge?".to_owned(),
4439 String::new(),
4440 vec!["merge".to_owned(), "hold".to_owned()],
4441 )
4442 }
4443
4444 #[test]
4445 fn land_resume_state_leaves_a_fresh_open_question_waiting() {
4446 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4447 let mut state = run_state(RunStatus::Landing);
4448 state.id = "20260101-000000-fre1".to_owned();
4449 state.parked = true;
4450 state.save().unwrap();
4451 ask::Questions::open()
4452 .put(&mut approval_question(&state.id))
4453 .unwrap();
4454
4455 let mut t = task();
4456 t.runs.push(state.id.clone());
4457 assert_eq!(
4458 land_resume_state(&t),
4459 LandResume::StillWaiting,
4460 "nobody has answered and the timeout has not passed"
4461 );
4462 }
4463
4464 #[test]
4465 fn land_resume_state_abandons_a_question_that_outlived_answer_timeout() {
4466 // `ask::ask_and_wait`'s own deadline used to retire a question
4467 // nobody answered; land's approval bypasses that wait (see
4468 // `land::approval_gate`), so this is now the only place
4469 // `graph.answer_timeout` is enforced for a land approval at all.
4470 crate::run::set_home(std::env::temp_dir().join("magi-daemon-test-home"));
4471 let mut state = run_state(RunStatus::Landing);
4472 state.id = "20260101-000000-exp1".to_owned();
4473 state.parked = true;
4474 state.config.graph.answer_timeout = 60;
4475 state.save().unwrap();
4476
4477 let store = ask::Questions::open();
4478 let mut q = approval_question(&state.id);
4479 q.asked_at = Timestamp::now() - jiff::SignedDuration::from_secs(120);
4480 store.put(&mut q).unwrap();
4481
4482 let mut t = task();
4483 t.runs.push(state.id.clone());
4484 assert_eq!(
4485 land_resume_state(&t),
4486 LandResume::Ready,
4487 "an expired question must not be waited on forever"
4488 );
4489
4490 let after = store.get(&q.id).unwrap();
4491 assert!(
4492 !after.status.open(),
4493 "the question is abandoned, not silently ignored"
4494 );
4495 assert!(
4496 after.resolution().is_none(),
4497 "an abandoned question is not read as a decision"
4498 );
4499 }
4500
4501 #[test]
4502 fn reclaim_settles_a_running_task_against_its_last_run() {
4503 let mut t = task();
4504 t.start("20260904-000000-4043".to_owned());
4505 reclaim(&mut t, Some(run_state(RunStatus::Ready)), 2);
4506 assert_eq!(
4507 t.status,
4508 TaskStatus::Done,
4509 "a run that actually finished must not stay `running` forever"
4510 );
4511 }
4512
4513 #[test]
4514 fn reclaim_reuses_the_same_retry_policy_as_a_live_settle() {
4515 // A blocked run with attempts left goes back to `Failed`, exactly as
4516 // it would from `attempt` itself - `reclaim` must not invent a second
4517 // policy for a task a daemon merely stopped without reporting.
4518 let mut t = task();
4519 t.start("20260904-000000-4043".to_owned());
4520 reclaim(&mut t, Some(run_state(RunStatus::Blocked)), 2);
4521 assert_eq!(t.status, TaskStatus::Failed);
4522 assert!(t.status.runnable());
4523 }
4524
4525 #[test]
4526 fn reclaim_holds_a_running_task_whose_run_cannot_be_found() {
4527 let mut t = task();
4528 t.start("20260904-000000-4043".to_owned());
4529 reclaim(&mut t, None, 2);
4530 assert_eq!(t.status, TaskStatus::Held);
4531 assert!(
4532 t.last_error
4533 .as_deref()
4534 .is_some_and(|e| e.contains("running")),
4535 "the operator needs to know why this task was held"
4536 );
4537 }
4538
4539 #[test]
4540 fn orphaned_running_tasks_are_reclaimed_but_live_ones_are_left_alone() {
4541 let dir = tempfile::tempdir().unwrap();
4542 let queue = Queue::at(dir.path().to_path_buf());
4543
4544 // No run recorded, so this never has to touch `RunState::load`.
4545 let mut orphaned = task();
4546 orphaned.id = "20260904-000000-orph".to_owned();
4547 orphaned.status = TaskStatus::Running;
4548 orphaned.attempts = 1;
4549 queue.put(&mut orphaned).unwrap();
4550
4551 let mut alive = task();
4552 alive.id = "20260904-000000-live".to_owned();
4553 alive.status = TaskStatus::Running;
4554 alive.attempts = 1;
4555 queue.put(&mut alive).unwrap();
4556 let _held_by_a_live_daemon = queue.claim(&alive.id).unwrap();
4557
4558 let mut queued = task();
4559 queued.id = "20260904-000000-wait".to_owned();
4560 queue.put(&mut queued).unwrap();
4561
4562 let reclaimed = reclaim_orphaned_running(&queue, 2);
4563 assert_eq!(reclaimed, vec![orphaned.id.clone()]);
4564
4565 assert_eq!(
4566 queue.get(&orphaned.id).unwrap().status,
4567 TaskStatus::Held,
4568 "nothing was driving it and there was no run to recover"
4569 );
4570 assert_eq!(
4571 queue.get(&alive.id).unwrap().status,
4572 TaskStatus::Running,
4573 "a live claim must protect the task it belongs to"
4574 );
4575 assert_eq!(queue.get(&queued.id).unwrap().status, TaskStatus::Queued);
4576 }
4577
4578 /// Read a run.json back from an explicit `home`, the same way
4579 /// `reclaim_abandoned_runs` itself does - never through the
4580 /// process-global `RunState::load`, which this test's own `home` (an
4581 /// isolated tempdir, never pinned into the shared `OnceLock`) does not
4582 /// use at all.
4583 fn read_run_under(home: &Path, id: &str) -> RunState {
4584 let body = std::fs::read_to_string(home.join("runs").join(id).join("run.json")).unwrap();
4585 serde_json::from_str(&body).unwrap()
4586 }
4587
4588 #[test]
4589 fn reclaim_abandoned_runs_fails_a_run_whose_active_seats_are_all_provably_dead() {
4590 let dir = tempfile::tempdir().unwrap();
4591 let home = dir.path().to_path_buf();
4592 let now = Timestamp::now();
4593 let overrun_seat = || crate::run::ActiveSeat {
4594 node: "implement".to_owned(),
4595 started_at: now - jiff::SignedDuration::new(21_000, 0),
4596 timeout_secs: 3_600,
4597 attempt: 0,
4598 task: None,
4599 command: None,
4600 index: None,
4601 total: None,
4602 };
4603
4604 let mut dead = run_state(RunStatus::Implementing);
4605 dead.id = "20260101-000000-dead".to_owned();
4606 dead.active.insert("impl-A".to_owned(), overrun_seat());
4607 // A `driver_pid` the injected query below confirms gone outright —
4608 // `liveness` reads this as `Dead`, not merely "no daemon claims it".
4609 dead.driver_pid = Some(4242);
4610 dead.save_under(&home).unwrap();
4611
4612 // Same shape, but a live daemon's heartbeat names it: must be left
4613 // exactly alone, however far past its own timeout the seat sits.
4614 let mut alive = run_state(RunStatus::Implementing);
4615 alive.id = "20260101-000000-aliv".to_owned();
4616 alive.active.insert("impl-A".to_owned(), overrun_seat());
4617 alive.save_under(&home).unwrap();
4618 let mut status = Status::new();
4619 status.current = vec![Current {
4620 task: "20260101-000000-task".to_owned(),
4621 run: alive.id.clone(),
4622 }];
4623 write_status_to(&home.join("daemon.json"), &status).unwrap();
4624
4625 // The abandoned seat left an open question behind: nobody is left to
4626 // read an answer once the run is failed, and this must not wait for
4627 // some later daemon startup's own sweep to notice that.
4628 let questions = Questions::at(home.join("questions"));
4629 let mut q = ask::Question::new(
4630 dead.id.clone(),
4631 "implement".to_owned(),
4632 "impl-A".to_owned(),
4633 "Which storage backend?".to_owned(),
4634 String::new(),
4635 vec!["SQLite".to_owned(), "Redis".to_owned()],
4636 );
4637 questions.put(&mut q).unwrap();
4638
4639 let abandoned = reclaim_abandoned_runs_with(
4640 &home,
4641 now,
4642 |pid| if pid == 4242 { Some(false) } else { None },
4643 |_| panic!("a query answering Dead outright needs no identity corroboration"),
4644 );
4645 assert_eq!(abandoned, vec![dead.id.clone()]);
4646
4647 let reloaded = read_run_under(&home, &dead.id);
4648 assert_eq!(reloaded.status, RunStatus::Failed);
4649 assert!(reloaded.active.is_empty());
4650 assert!(
4651 !questions.get(&q.id).unwrap().status.open(),
4652 "the failed run's own open question must be settled in the same pass"
4653 );
4654
4655 let still_alive = read_run_under(&home, &alive.id);
4656 assert_eq!(
4657 still_alive.status,
4658 RunStatus::Implementing,
4659 "a live daemon's claim protects it"
4660 );
4661 assert!(!still_alive.active.is_empty());
4662 }
4663
4664 /// The exact shape a review round flagged as broken: `magi serve` running
4665 /// in this same `home` scans *every* run on disk, including a manual
4666 /// `magi review` / `magi run` this daemon never started and that
4667 /// therefore claims no heartbeat of its own. Before this scan asked
4668 /// `liveness` rather than just `is_working_on`, a manual run whose active
4669 /// seat merely ran a little past its own timeout — the CLI finishing up,
4670 /// its result still being collected — got wiped and failed by a daemon
4671 /// that had nothing to do with it, out from under a process that was
4672 /// still very much running.
4673 #[test]
4674 fn reclaim_abandoned_runs_leaves_a_live_manual_run_alone_even_though_no_daemon_claims_it() {
4675 let dir = tempfile::tempdir().unwrap();
4676 let home = dir.path().to_path_buf();
4677 let now = Timestamp::now();
4678
4679 let mut manual = run_state(RunStatus::Reviewing);
4680 manual.id = "20260101-000000-manl".to_owned();
4681 manual.active.insert(
4682 "review-1".to_owned(),
4683 crate::run::ActiveSeat {
4684 node: "review".to_owned(),
4685 started_at: now - jiff::SignedDuration::new(21_000, 0),
4686 timeout_secs: 3_600,
4687 attempt: 0,
4688 task: None,
4689 command: None,
4690 index: None,
4691 total: None,
4692 },
4693 );
4694 // Not claimed by any daemon (no `daemon.json` at all in this `home`),
4695 // but a real, still-running process: `liveness` must corroborate this
4696 // as `Live`, not read the missing daemon claim as death.
4697 manual.driver_pid = Some(4242);
4698 manual.driver_started_at = Some("2026-09-22T10:00:00Z".to_owned());
4699 manual.save_under(&home).unwrap();
4700
4701 let abandoned = reclaim_abandoned_runs_with(
4702 &home,
4703 now,
4704 |pid| if pid == 4242 { Some(true) } else { None },
4705 |pid| {
4706 if pid == 4242 {
4707 Some("2026-09-22T10:00:00Z".to_owned())
4708 } else {
4709 None
4710 }
4711 },
4712 );
4713 assert!(
4714 abandoned.is_empty(),
4715 "a manual run a real process is still driving must never be reclaimed: {abandoned:?}"
4716 );
4717
4718 let reloaded = read_run_under(&home, &manual.id);
4719 assert_eq!(reloaded.status, RunStatus::Reviewing);
4720 assert!(!reloaded.active.is_empty());
4721 }
4722
4723 #[test]
4724 fn an_already_claimed_task_is_skipped_rather_than_failed() {
4725 let dir = tempfile::tempdir().unwrap();
4726 let queue = Queue::at(dir.path().to_path_buf());
4727 let mut only = task();
4728 queue.put(&mut only).unwrap();
4729
4730 let _elsewhere = queue.claim(&only.id).unwrap();
4731 let candidates = runnable(&queue);
4732 assert_eq!(candidates.len(), 1, "the task is still runnable");
4733 assert!(
4734 queue.claim(&candidates[0].id).is_err(),
4735 "the loop cannot take a claim somebody else holds"
4736 );
4737
4738 let after = queue.get(&only.id).unwrap();
4739 assert_eq!(after.status, TaskStatus::Queued);
4740 assert_eq!(
4741 after.attempts, 0,
4742 "losing the race is not an attempt at the task"
4743 );
4744 assert_eq!(after.last_error, None);
4745 }
4746
4747 #[test]
4748 fn the_status_file_round_trips_and_its_heartbeat_advances() {
4749 let dir = tempfile::tempdir().unwrap();
4750 let path = dir.path().join("daemon.json");
4751
4752 let mut status = Status::new();
4753 status.idle = false;
4754 status.completed = 7;
4755 status.current = vec![Current {
4756 task: "20260902-000000-t111".to_owned(),
4757 run: "20260902-000001-r111".to_owned(),
4758 }];
4759 write_status_to(&path, &status).unwrap();
4760 let first: Status = serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4761 assert_eq!(first.schema, SCHEMA);
4762 assert_eq!(first.pid, std::process::id());
4763 assert!(!first.idle);
4764 assert_eq!(first.completed, 7);
4765 assert_eq!(first.current, status.current);
4766 assert!(
4767 !path.with_extension("json.tmp").exists(),
4768 "the temp file is renamed, not left behind"
4769 );
4770
4771 std::thread::sleep(Duration::from_millis(5));
4772 status.updated_at = Timestamp::now();
4773 status.polls = 3;
4774 write_status_to(&path, &status).unwrap();
4775 let second: Status =
4776 serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
4777 assert!(
4778 second.updated_at > first.updated_at,
4779 "a reader can only detect staleness if the heartbeat moves"
4780 );
4781 assert_eq!(
4782 second.started_at, first.started_at,
4783 "the start time is not a heartbeat"
4784 );
4785 assert_eq!(second.polls, 3);
4786 }
4787
4788 #[test]
4789 fn reading_counts_as_running_only_while_its_heartbeat_is_fresh() {
4790 let dir = tempfile::tempdir().unwrap();
4791
4792 assert!(read_status(dir.path()).is_none(), "no file, no daemon");
4793
4794 let mut status = Status::new();
4795 status.updated_at = Timestamp::now() - jiff::SignedDuration::from_secs(60);
4796 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
4797 let stale = read_status(dir.path()).unwrap();
4798 assert!(
4799 !stale.running(Timestamp::now()),
4800 "a minute without a heartbeat is a dead daemon, not a busy one"
4801 );
4802 assert!(stale.age_secs(Timestamp::now()).is_some_and(|s| s >= 55));
4803
4804 status.updated_at = Timestamp::now();
4805 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
4806 let fresh = read_status(dir.path()).unwrap();
4807 assert!(fresh.running(Timestamp::now()));
4808 }
4809
4810 #[test]
4811 fn only_a_live_daemon_on_this_very_run_counts_as_working_on_it() {
4812 let dir = tempfile::tempdir().unwrap();
4813 let now = Timestamp::now();
4814 let mine = "20260903-080619-01c2";
4815
4816 assert!(
4817 !is_working_on(dir.path(), mine, now),
4818 "no status file means nobody is working on anything"
4819 );
4820
4821 let mut status = Status::new();
4822 status.current = vec![Current {
4823 task: "20260903-080340-0167".to_owned(),
4824 run: mine.to_owned(),
4825 }];
4826 status.updated_at = now;
4827 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
4828 assert!(is_working_on(dir.path(), mine, now));
4829 assert!(
4830 !is_working_on(dir.path(), "20260903-105039-3cbf", now),
4831 "a daemon busy with one run is not working on another"
4832 );
4833
4834 // A killed daemon stops writing heartbeats but leaves the file behind
4835 // naming the run it died in. That run must not be undeletable forever.
4836 status.updated_at = now - jiff::SignedDuration::from_secs(600);
4837 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
4838 assert!(
4839 !is_working_on(dir.path(), mine, now),
4840 "a stale heartbeat is a dead daemon, so its run is a leftover"
4841 );
4842 }
4843
4844 #[test]
4845 fn is_working_on_short_matches_by_the_worktree_bays_own_name() {
4846 let dir = tempfile::tempdir().unwrap();
4847 let now = Timestamp::now();
4848
4849 assert!(
4850 !is_working_on_short(dir.path(), "01c2", now),
4851 "no status file means nobody is working on anything"
4852 );
4853
4854 let mut status = Status::new();
4855 status.current = vec![Current {
4856 task: "20260903-080340-0167".to_owned(),
4857 run: "20260903-080619-01c2".to_owned(),
4858 }];
4859 status.updated_at = now;
4860 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
4861 assert!(
4862 is_working_on_short(dir.path(), "01c2", now),
4863 "the run's short id is the last block of its full id"
4864 );
4865 assert!(
4866 !is_working_on_short(dir.path(), "3cbf", now),
4867 "a daemon busy with one worktree bay is not working on another"
4868 );
4869 }
4870
4871 #[test]
4872 fn a_newer_status_file_still_yields_a_reading() {
4873 let dir = tempfile::tempdir().unwrap();
4874 // A field this build has never heard of must not turn the reading into
4875 // nothing at all; that is the whole reason the reader is permissive.
4876 std::fs::write(
4877 dir.path().join("daemon.json"),
4878 serde_json::json!({
4879 "schema": 2,
4880 "updated_at": Timestamp::now().to_string(),
4881 "idle": true,
4882 "surprise": { "nested": [1, 2, 3] },
4883 })
4884 .to_string(),
4885 )
4886 .unwrap();
4887
4888 let reading = read_status(dir.path()).expect("a forward-compatible read");
4889 assert!(reading.running(Timestamp::now()));
4890 assert!(reading.idle);
4891 assert!(reading.current.is_empty());
4892 }
4893
4894 #[test]
4895 fn an_older_daemons_single_object_current_still_reads_as_a_one_item_list() {
4896 // A daemon started before `current` became a list keeps writing this
4897 // shape on every heartbeat until it is restarted. A rolling upgrade
4898 // - a newer `magi web` or `magi doctor` reading an older `magi
4899 // serve`'s heartbeat - must still see the run it is on, not "no
4900 // daemon" from a type mismatch failing the whole struct.
4901 let dir = tempfile::tempdir().unwrap();
4902 std::fs::write(
4903 dir.path().join("daemon.json"),
4904 serde_json::json!({
4905 "schema": 1,
4906 "pid": 4242,
4907 "updated_at": Timestamp::now().to_string(),
4908 "idle": false,
4909 "current": {"task": "20260902-140501-aaaa", "run": "20260902-140502-bbbb"},
4910 "completed": 3,
4911 "polls": 9,
4912 })
4913 .to_string(),
4914 )
4915 .unwrap();
4916
4917 let reading = read_status(dir.path()).expect("an older shape must still parse");
4918 assert!(reading.running(Timestamp::now()));
4919 assert_eq!(
4920 reading.current,
4921 vec![Current {
4922 task: "20260902-140501-aaaa".to_owned(),
4923 run: "20260902-140502-bbbb".to_owned(),
4924 }]
4925 );
4926 }
4927
4928 #[test]
4929 fn an_absent_or_null_current_reads_as_idle_not_a_parse_failure() {
4930 let dir = tempfile::tempdir().unwrap();
4931 std::fs::write(
4932 dir.path().join("daemon.json"),
4933 serde_json::json!({
4934 "schema": 1,
4935 "updated_at": Timestamp::now().to_string(),
4936 "idle": true,
4937 "current": null,
4938 })
4939 .to_string(),
4940 )
4941 .unwrap();
4942 let with_null = read_status(dir.path()).expect("null must still parse");
4943 assert!(with_null.current.is_empty());
4944
4945 std::fs::write(
4946 dir.path().join("daemon.json"),
4947 serde_json::json!({
4948 "schema": 1,
4949 "updated_at": Timestamp::now().to_string(),
4950 "idle": true,
4951 })
4952 .to_string(),
4953 )
4954 .unwrap();
4955 let absent = read_status(dir.path()).expect("a missing field must still parse");
4956 assert!(absent.current.is_empty());
4957 }
4958
4959 #[test]
4960 fn a_task_without_a_repository_runs_in_the_daemons_default() {
4961 let fallback = Path::new("/default");
4962 let mut blank = task();
4963 blank.repo = PathBuf::new();
4964 assert_eq!(repo_for(&blank, fallback), PathBuf::from("/default"));
4965 let mut dot = task();
4966 dot.repo = PathBuf::from(".");
4967 assert_eq!(repo_for(&dot, fallback), PathBuf::from("/default"));
4968 assert_eq!(
4969 repo_for(&task(), fallback),
4970 PathBuf::from("/repo"),
4971 "a task that names a repository keeps it"
4972 );
4973 }
4974
4975 #[test]
4976 fn a_solo_task_runs_with_one_candidate_and_a_plain_task_keeps_the_configs() {
4977 // Three seats said out loud. What `solo` promises is one candidate
4978 // *whatever the config asks for*, so the contrast has to be a number
4979 // this test owns - it used to be `Config::default()`'s, which became
4980 // 1 when one implementation became the default and left the two
4981 // halves of this test asserting the same thing.
4982 let mut solo_cfg = Config::default();
4983 solo_cfg.graph.candidates = 3;
4984 let mut solo_task = task();
4985 solo_task.solo = true;
4986 apply_solo(&mut solo_cfg, &solo_task);
4987 assert_eq!(solo_cfg.graph.candidates, 1);
4988
4989 let mut plain_cfg = Config::default();
4990 plain_cfg.graph.candidates = 3;
4991 let plain_task = task();
4992 assert!(!plain_task.solo);
4993 apply_solo(&mut plain_cfg, &plain_task);
4994 assert_eq!(
4995 plain_cfg.graph.candidates, 3,
4996 "a task that did not ask to run alone keeps the config's candidates"
4997 );
4998 }
4999
5000 fn loss(seat: &str, at: &str, reset: Option<&str>) -> QuotaLoss {
5001 QuotaLoss {
5002 seat: seat.into(),
5003 node: "judge".into(),
5004 at: at.parse().unwrap(),
5005 reset: reset.map(str::to_string),
5006 }
5007 }
5008
5009 #[test]
5010 fn a_resumed_run_with_only_old_quota_losses_arms_no_cooldown() {
5011 let old: Vec<QuotaLoss> = (1..=4)
5012 .map(|i| {
5013 loss(
5014 &format!("judge-{i}"),
5015 "2026-09-23T05:23:00Z",
5016 Some("2:40pm (Asia/Tokyo)"),
5017 )
5018 })
5019 .collect();
5020 let fresh = losses_this_attempt(&old, &old);
5021 assert!(fresh.is_empty());
5022 assert_eq!(cooldown_until(&fresh, Timestamp::now()), None);
5023 // And it is not a `quota_hit` either: that is `!fresh.is_empty()`.
5024 }
5025
5026 #[test]
5027 fn a_new_quota_loss_during_the_attempt_still_arms_the_cooldown() {
5028 let old = vec![loss("judge-1", "2026-09-23T05:23:00Z", None)];
5029 let now = Timestamp::now();
5030 let mut after = old.clone();
5031 after.push(loss("judge-2", &now.to_string(), None));
5032 let fresh = losses_this_attempt(&old, &after);
5033 assert_eq!(fresh, vec![after[1].clone()]);
5034 let until = cooldown_until(&fresh, now).expect("a fresh loss arms the cooldown");
5035 assert_eq!(
5036 until,
5037 now + jiff::SignedDuration::from_secs(QUOTA_WAIT_FALLBACK.as_secs() as i64)
5038 );
5039 }
5040
5041 #[test]
5042 fn a_recovered_seat_dropping_out_of_the_history_does_not_hide_a_new_loss() {
5043 // `recover_stall` removes judge-1's loss and the retry then hits quota
5044 // again: the vector is the same length, so an index diff sees nothing.
5045 let before = vec![
5046 loss("judge-1", "2026-09-23T05:23:00Z", None),
5047 loss("judge-2", "2026-09-23T05:24:00Z", None),
5048 ];
5049 let after = vec![
5050 loss("judge-2", "2026-09-23T05:24:00Z", None),
5051 loss("judge-1", "2026-09-24T01:00:00Z", None),
5052 ];
5053 assert_eq!(losses_this_attempt(&before, &after), vec![after[1].clone()]);
5054 }
5055
5056 #[test]
5057 fn merge_overrides_are_parsed_or_refused() {
5058 assert_eq!(merge_mode("none").unwrap(), MergeMode::None);
5059 assert_eq!(merge_mode("local").unwrap(), MergeMode::Local);
5060 assert_eq!(merge_mode("pr").unwrap(), MergeMode::Pr);
5061 assert!(merge_mode("squash").is_err());
5062 }
5063
5064 #[test]
5065 fn quota_wait_uses_a_future_reset_time_capped_and_falls_back_otherwise() {
5066 let now = Timestamp::now();
5067 let fallback = Duration::from_secs(300);
5068 let cap = Duration::from_secs(1800);
5069
5070 // No reset hint at all: the fallback.
5071 assert_eq!(quota_wait(None, now, fallback, cap), fallback);
5072
5073 // A reset ten minutes out, well inside the cap: waited for exactly.
5074 let soon = now + jiff::SignedDuration::from_secs(600);
5075 assert_eq!(
5076 quota_wait(Some(soon), now, fallback, cap),
5077 Duration::from_secs(600)
5078 );
5079
5080 // A reset already in the past is not trusted: the fallback, not a
5081 // zero or negative wait that would spin the loop right back around.
5082 let past = now - jiff::SignedDuration::from_secs(60);
5083 assert_eq!(quota_wait(Some(past), now, fallback, cap), fallback);
5084
5085 // A reset further out than the cap is trusted for direction but not
5086 // for magnitude: a parsing slip must not sleep the loop for a day.
5087 let far = now + jiff::SignedDuration::from_secs(3 * 3600);
5088 assert_eq!(quota_wait(Some(far), now, fallback, cap), cap);
5089 }
5090
5091 #[test]
5092 fn parse_reset_hint_reads_the_claude_cli_shape_and_rolls_a_past_clock_to_tomorrow() {
5093 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5094
5095 let at = parse_reset_hint("4:50am (UTC)", now, now).expect("a recognised shape parses");
5096 assert_eq!(at.to_string(), "2026-09-07T04:50:00Z");
5097
5098 // Same clock reading, but it has already gone by today: read as
5099 // tomorrow's, since the CLI would not still be reporting a limit past
5100 // its own stated reset.
5101 let already_past =
5102 parse_reset_hint("1:00am (UTC)", now, now).expect("a recognised shape parses");
5103 assert_eq!(already_past.to_string(), "2026-09-08T01:00:00Z");
5104
5105 assert!(
5106 parse_reset_hint("session limit reached", now, now).is_none(),
5107 "free text with no recognised shape is not guessed at"
5108 );
5109 assert!(
5110 parse_reset_hint("4:50am (Nowhere/Fake)", now, now).is_none(),
5111 "an unresolvable zone name is not guessed at either"
5112 );
5113 }
5114
5115 #[test]
5116 fn parse_reset_hint_reads_the_codex_cli_shape_with_no_year_rollover_needed() {
5117 let now = "2026-09-07T02:50:00Z".parse::<Timestamp>().unwrap();
5118
5119 let at = parse_reset_hint(
5120 "You've hit your usage limit. Visit \
5121 https://chatgpt.com/codex/settings/usage to purchase more \
5122 credits or try again at Sep 19th, 2026 5:10 PM.",
5123 now,
5124 now,
5125 )
5126 .expect("the codex reset wording is a recognised shape");
5127 assert_eq!(at.to_string(), "2026-09-19T17:10:00Z");
5128
5129 // The month is explicit, so a date already earlier in the same
5130 // sentence-implied year than `now` is trusted as written rather than
5131 // rolled forward a year the way the bracketed shape rolls a
5132 // same-day clock reading to tomorrow.
5133 let earlier = parse_reset_hint("try again at Jan 2nd, 2026 1:00 AM.", now, now)
5134 .expect("an explicit year needs no rollover");
5135 assert_eq!(earlier.to_string(), "2026-01-02T01:00:00Z");
5136
5137 assert!(
5138 parse_reset_hint("try again at Sep 19th, 26 5:10 PM.", now, now).is_none(),
5139 "a two-digit year is not the documented shape and is not guessed at"
5140 );
5141 assert!(
5142 parse_reset_hint("try again at Sept 19th, 2026 5:10 PM.", now, now).is_none(),
5143 "a four-letter month name is not the documented three-letter abbreviation"
5144 );
5145 assert!(
5146 parse_reset_hint("try again at Sep 19th, 2026 5:10 PM (UTC).", now, now).is_none(),
5147 "an explicit zone on the dated shape is a format nobody has \
5148 documented, and is refused rather than guessed at as UTC"
5149 );
5150 }
5151
5152 #[test]
5153 fn parse_reset_hint_reads_agys_relative_shape_from_when_the_loss_was_recorded() {
5154 let now = "2026-09-24T12:00:00Z".parse::<Timestamp>().unwrap();
5155 let recorded = "2026-09-24T08:00:00Z".parse::<Timestamp>().unwrap();
5156
5157 let at = parse_reset_hint("in 1h2m49s", now, recorded).expect("agy's shape parses");
5158 assert_eq!(at.as_second() - recorded.as_second(), 3769);
5159
5160 let partial = parse_reset_hint("in 45m", now, recorded).expect("units are optional");
5161 assert_eq!(partial.as_second() - recorded.as_second(), 45 * 60);
5162
5163 for bad in ["in ", "in 45", "in 3x", "in m", "in 1h junk", "1h2m"] {
5164 assert!(
5165 parse_reset_hint(bad, now, recorded).is_none(),
5166 "{bad:?} must not be guessed at"
5167 );
5168 }
5169 }
5170
5171 /// A loop whose queue lives in a temp tree and whose poll interval is far
5172 /// longer than the test's patience, so anything that waits out a poll
5173 /// instead of noticing the stop fails rather than merely being slow.
5174 fn idle_loop(dir: &Path) -> (Opts, Queue, PathBuf, PathBuf, PathBuf) {
5175 let config = dir.join("magi.toml");
5176 std::fs::write(
5177 &config,
5178 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = 0\n",
5179 )
5180 .unwrap();
5181 let opts = Opts {
5182 poll: Duration::from_secs(30),
5183 config: Some(config),
5184 // The explicit fixture config keeps startup cleanup from reading
5185 // machine configuration. This fictional repository likewise
5186 // keeps any best-effort git cleanup away from this checkout.
5187 repo: dir.join("repo"),
5188 ..Opts::default()
5189 };
5190 // The status file goes in a directory that does not exist yet, so its
5191 // creation is itself evidence the loop published one. `worktrees`
5192 // must be just as fictional: the janitor reclaims worktrees under it
5193 // for real, and a test that let it fall through to
5194 // `crate::run::default_worktree_root()` would have it reclaim
5195 // worktrees out of the operator's real `~/wt/<repo>`, not a fixture -
5196 // which is exactly what happened before this function took the
5197 // parameter at all.
5198 let home = dir.join("home");
5199 let worktrees = dir.join("wt");
5200 (
5201 opts,
5202 Queue::at(dir.join("queue")),
5203 home.join("daemon.json"),
5204 home,
5205 worktrees,
5206 )
5207 }
5208
5209 #[test]
5210 fn a_stop_is_idempotent_and_once_set_stays_set() {
5211 let stop = Stop::new();
5212 assert!(!stop.stopped());
5213
5214 stop.stop();
5215 assert!(stop.stopped());
5216 stop.stop();
5217 assert!(stop.stopped(), "a second stop is not a toggle");
5218
5219 let shared = stop.clone();
5220 assert!(
5221 shared.stopped(),
5222 "a clone is the same stop; that is how the loop and its caller share one"
5223 );
5224 }
5225
5226 #[test]
5227 fn only_a_stop_with_a_run_in_flight_reads_as_finishing() {
5228 let stop = Stop::new();
5229 stop.enter();
5230 assert!(
5231 !stop.finishing(),
5232 "a busy loop nobody has asked to stop is just running"
5233 );
5234
5235 stop.stop();
5236 assert!(
5237 stop.finishing(),
5238 "a stop asked for mid-run has not landed until the run is settled"
5239 );
5240
5241 stop.exit();
5242 assert!(
5243 !stop.finishing(),
5244 "once the run is settled the stop has landed and there is nothing to finish"
5245 );
5246 }
5247
5248 #[test]
5249 fn finishing_stays_true_until_the_last_of_several_runs_exits() {
5250 let stop = Stop::new();
5251 stop.enter();
5252 stop.enter();
5253 stop.stop();
5254 assert!(stop.finishing(), "two runs still in flight");
5255
5256 stop.exit();
5257 assert!(
5258 stop.finishing(),
5259 "one run finished, but a sibling is still working"
5260 );
5261
5262 stop.exit();
5263 assert!(
5264 !stop.finishing(),
5265 "the last run out is what actually lands the stop"
5266 );
5267 }
5268
5269 #[tokio::test]
5270 async fn a_loop_already_asked_to_stop_returns_without_waiting_out_a_poll() {
5271 let dir = tempfile::tempdir().unwrap();
5272 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5273 let stop = Stop::new();
5274 stop.stop();
5275
5276 let began = std::time::Instant::now();
5277 tokio::time::timeout(
5278 Duration::from_secs(2),
5279 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5280 )
5281 .await
5282 .expect("a stopped loop must return, not sit out its poll interval")
5283 .expect("the loop's own setup and teardown must not fail");
5284 assert!(
5285 began.elapsed() < opts.poll,
5286 "returned only after {:?}, which is a poll interval, not a stop",
5287 began.elapsed()
5288 );
5289 }
5290
5291 #[tokio::test]
5292 async fn a_stop_while_idle_wakes_the_wait_instead_of_sleeping_it_out() {
5293 let dir = tempfile::tempdir().unwrap();
5294 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5295 let stop = Stop::new();
5296
5297 // Asked for after the loop is already parked on its empty queue, which
5298 // is the case an operator tapping stop on a phone actually hits.
5299 let asker = {
5300 let stop = stop.clone();
5301 tokio::spawn(async move {
5302 tokio::time::sleep(Duration::from_millis(20)).await;
5303 stop.stop();
5304 })
5305 };
5306
5307 let began = std::time::Instant::now();
5308 tokio::time::timeout(
5309 Duration::from_secs(2),
5310 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5311 )
5312 .await
5313 .expect("a stop asked for while idle must wake the wait")
5314 .expect("the loop's own setup and teardown must not fail");
5315 asker.await.unwrap();
5316 assert!(
5317 began.elapsed() < opts.poll,
5318 "returned only after {:?}, so the stop waited on the sleep",
5319 began.elapsed()
5320 );
5321 }
5322
5323 #[tokio::test]
5324 async fn a_stopped_loop_leaves_no_status_file_claiming_it_is_running() {
5325 let dir = tempfile::tempdir().unwrap();
5326 let (opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5327 let stop = Stop::new();
5328 stop.stop();
5329
5330 tokio::time::timeout(
5331 Duration::from_secs(2),
5332 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5333 )
5334 .await
5335 .expect("a stopped loop must return")
5336 .expect("the loop's own setup and teardown must not fail");
5337
5338 assert!(
5339 home.is_dir(),
5340 "the loop did publish a status file, so its removal is the teardown and not an absence"
5341 );
5342 assert!(
5343 !status_file.exists(),
5344 "a stopped loop clears its status file"
5345 );
5346 assert!(
5347 read_status(&home).is_none(),
5348 "a reader must see no daemon at all, not a heartbeat that merely stopped"
5349 );
5350 }
5351
5352 #[tokio::test]
5353 async fn once_runs_startup_housekeeping_before_an_empty_queue_exits() {
5354 let dir = tempfile::tempdir().unwrap();
5355 let (mut opts, queue, status_file, home, worktrees) = idle_loop(dir.path());
5356 opts.once = true;
5357
5358 let mut settled = RunState::new(
5359 dir.path().join("repo"),
5360 "main".to_owned(),
5361 "abc1234".to_owned(),
5362 "fixture".to_owned(),
5363 Config::default(),
5364 );
5365 settled.status = RunStatus::Ready;
5366 let run_dir = home.join("runs").join(&settled.id);
5367 std::fs::create_dir_all(&run_dir).unwrap();
5368 std::fs::write(
5369 run_dir.join("run.json"),
5370 serde_json::to_string_pretty(&settled).unwrap(),
5371 )
5372 .unwrap();
5373 let questions = Questions::at(home.join("questions"));
5374 let mut question = ask::Question::new(
5375 settled.id.clone(),
5376 "review".to_owned(),
5377 "reviewer-1".to_owned(),
5378 "Continue?".to_owned(),
5379 String::new(),
5380 Vec::new(),
5381 );
5382 questions.put(&mut question).unwrap();
5383
5384 drive(&opts, &queue, &status_file, &home, &worktrees, &Stop::new())
5385 .await
5386 .unwrap();
5387
5388 assert_eq!(
5389 questions.get(&question.id).unwrap().status,
5390 ask::QuestionStatus::Abandoned,
5391 "an empty --once drain still performs startup question cleanup"
5392 );
5393 }
5394
5395 #[test]
5396 fn cache_check_due_fires_immediately_then_waits_out_its_own_interval() {
5397 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5398
5399 assert!(
5400 cache_check_due(None, t0, CACHE_CHECK_INTERVAL_SECS),
5401 "never checked before: due at once"
5402 );
5403
5404 let one_sec_later = t0 + jiff::SignedDuration::from_secs(1);
5405 assert!(
5406 !cache_check_due(Some(t0), one_sec_later, CACHE_CHECK_INTERVAL_SECS),
5407 "well inside the interval: not due yet"
5408 );
5409
5410 let at_the_edge = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64);
5411 assert!(
5412 !cache_check_due(Some(t0), at_the_edge, CACHE_CHECK_INTERVAL_SECS),
5413 "exactly at the edge: not yet due, same convention as `clean::due`"
5414 );
5415
5416 let past_it = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5417 assert!(
5418 cache_check_due(Some(t0), past_it, CACHE_CHECK_INTERVAL_SECS),
5419 "past the interval: due again"
5420 );
5421 }
5422
5423 /// A `magi.toml` whose `[verify] gate` names `cache_dir` as its shared
5424 /// `CARGO_TARGET_DIR`, capped at `limit_bytes`, plus a repository path
5425 /// that is never created - the fixtures [`maybe_prune_cache_between_runs`]
5426 /// and the congestion test below both need, and must not drift apart.
5427 fn cache_check_opts(dir: &Path, cache_dir: &Path, limit_bytes: u64) -> Opts {
5428 let config = dir.join("magi.toml");
5429 // A literal (single-quoted) TOML string, not a basic one: the cache
5430 // path is a Windows path full of backslashes, and a basic string
5431 // would have TOML try to interpret `\U` (from `\Users\...`) as a
5432 // Unicode escape and fail to parse - the same trap `magi.toml`'s own
5433 // `{{ vars.cache }}` rendering documents.
5434 std::fs::write(
5435 &config,
5436 format!(
5437 "[disk]\nmin_free_bytes = 0\nauto_fold = false\ncache_limit_bytes = {limit_bytes}\n\n\
5438 [verify]\ngate = ['CARGO_TARGET_DIR={} cargo make check']\n",
5439 cache_dir.display()
5440 ),
5441 )
5442 .unwrap();
5443 Opts {
5444 config: Some(config),
5445 repo: dir.join("repo"),
5446 ..Opts::default()
5447 }
5448 }
5449
5450 #[tokio::test]
5451 async fn maybe_prune_cache_between_runs_reprunes_only_once_its_own_interval_elapses() {
5452 let dir = tempfile::tempdir().unwrap();
5453 let home = dir.path().join("home");
5454 let cache_dir = dir.path().join("cache");
5455 std::fs::create_dir_all(&cache_dir).unwrap();
5456 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
5457 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
5458
5459 // Nobody has asked this daemon to stop, which is the ordinary case;
5460 // the skip that a stop buys is asserted by its own test below.
5461 let running = Stop::new();
5462 let mut last_checked = None;
5463 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5464 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &running, &mut last_checked, t0)
5465 .await;
5466 assert_eq!(
5467 crate::disk::dir_size(&cache_dir),
5468 0,
5469 "over the cap on the first check ever: pruned at once, no idle queue required"
5470 );
5471 assert_eq!(last_checked, Some(t0));
5472
5473 // A fresh oversized file lands, but the next check is not due yet.
5474 std::fs::write(cache_dir.join("b"), vec![0u8; 10]).unwrap();
5475 let too_soon = t0 + jiff::SignedDuration::from_secs(1);
5476 maybe_prune_cache_between_runs(
5477 &opts.repo,
5478 &opts,
5479 &home,
5480 &running,
5481 &mut last_checked,
5482 too_soon,
5483 )
5484 .await;
5485 assert_eq!(
5486 crate::disk::dir_size(&cache_dir),
5487 10,
5488 "too soon since the last check: left alone rather than rescanned every call"
5489 );
5490 assert_eq!(
5491 last_checked,
5492 Some(t0),
5493 "an idle check does not reset the clock"
5494 );
5495
5496 // Once the interval elapses, the same oversized cache is caught again.
5497 let due_again = t0 + jiff::SignedDuration::from_secs(CACHE_CHECK_INTERVAL_SECS as i64 + 1);
5498 maybe_prune_cache_between_runs(
5499 &opts.repo,
5500 &opts,
5501 &home,
5502 &running,
5503 &mut last_checked,
5504 due_again,
5505 )
5506 .await;
5507 assert_eq!(
5508 crate::disk::dir_size(&cache_dir),
5509 0,
5510 "due again: pruned back under the cap"
5511 );
5512 }
5513
5514 /// A stop must not queue behind housekeeping. The prune below is a
5515 /// synchronous walk of the whole cache with no await point in it, so a
5516 /// loop that entered it could not get back to its own `stopped()` test
5517 /// until the walk finished - and because no run is in flight at this
5518 /// boundary, `Stop::finishing` would meanwhile tell the operator's screen
5519 /// the stop had already landed. The idle branch has always made this same
5520 /// check before reaching `janitor`; the between-runs path makes it too.
5521 #[tokio::test]
5522 async fn a_stop_already_asked_for_skips_the_between_runs_cache_walk() {
5523 let dir = tempfile::tempdir().unwrap();
5524 let home = dir.path().join("home");
5525 let cache_dir = dir.path().join("cache");
5526 std::fs::create_dir_all(&cache_dir).unwrap();
5527 std::fs::write(cache_dir.join("a"), vec![0u8; 10]).unwrap();
5528 let opts = cache_check_opts(dir.path(), &cache_dir, 1);
5529
5530 let stop = Stop::new();
5531 stop.stop();
5532 assert!(
5533 !stop.finishing(),
5534 "no run is in flight at a between-runs boundary, so nothing else \
5535 would tell the operator this stop had not taken effect yet"
5536 );
5537
5538 let mut last_checked = None;
5539 let t0 = "2026-09-15T00:00:00Z".parse::<Timestamp>().unwrap();
5540 maybe_prune_cache_between_runs(&opts.repo, &opts, &home, &stop, &mut last_checked, t0)
5541 .await;
5542 assert_eq!(
5543 crate::disk::dir_size(&cache_dir),
5544 10,
5545 "over its cap, and due for the first check ever, but a stop outranks \
5546 it: the cap is a standing policy the next start measures again"
5547 );
5548 assert_eq!(
5549 last_checked, None,
5550 "a check that never happened must not claim the interval"
5551 );
5552 }
5553
5554 /// The regression this whole change exists for: gate timeouts on runs
5555 /// 52da/2f7f/5991/0915 traced back to the shared cache sitting at 81.8
5556 /// GiB against a 10 GiB cap, because the operator's queue never had a
5557 /// quiet moment for `poll`'s fully-idle branch to reach the ordinary
5558 /// `janitor` pass.
5559 ///
5560 /// Reproduced here with a task whose repository is never created:
5561 /// `Runner::start` fails at `git::toplevel` in a few milliseconds,
5562 /// spawning no agent CLI, so the task keeps failing and re-queuing
5563 /// (`Task::fail` with attempts still under the budget leaves it
5564 /// `Failed`, which `TaskStatus::runnable` still offers) for as long as
5565 /// the loop keeps polling - exactly the "queue with no idle moment"
5566 /// this task describes, produced without a real competition.
5567 #[tokio::test]
5568 async fn cache_prune_reaches_a_queue_that_never_goes_idle() {
5569 let dir = tempfile::tempdir().unwrap();
5570 let cache_dir = dir.path().join("cache");
5571 std::fs::create_dir_all(&cache_dir).unwrap();
5572 std::fs::write(cache_dir.join("stale"), vec![0u8; 4096]).unwrap();
5573
5574 let mut opts = cache_check_opts(dir.path(), &cache_dir, 1);
5575 opts.poll = Duration::from_millis(20);
5576 opts.max_attempts = 1_000;
5577
5578 let queue = Queue::at(dir.path().join("queue"));
5579 let mut t = Task::new(
5580 "x".to_owned(),
5581 "x".to_owned(),
5582 opts.repo.clone(),
5583 Source::Human,
5584 );
5585 queue.put(&mut t).unwrap();
5586
5587 let home = dir.path().join("home");
5588 let worktrees = dir.path().join("wt");
5589 let status_file = home.join("daemon.json");
5590 let stop = Stop::new();
5591 let stopper = {
5592 let stop = stop.clone();
5593 tokio::spawn(async move {
5594 tokio::time::sleep(Duration::from_millis(400)).await;
5595 stop.stop();
5596 })
5597 };
5598
5599 tokio::time::timeout(
5600 Duration::from_secs(10),
5601 drive(&opts, &queue, &status_file, &home, &worktrees, &stop),
5602 )
5603 .await
5604 .expect("the loop must not hang on a queue that keeps producing failing work")
5605 .expect("the loop's own setup and teardown must not fail");
5606 stopper.await.unwrap();
5607
5608 let after = queue.get(&t.id).unwrap();
5609 assert!(
5610 after.attempts >= 2,
5611 "the harness must actually have retried more than once, or this is not \
5612 exercising a busy queue at all (got {} attempt(s))",
5613 after.attempts
5614 );
5615 assert!(
5616 after.status.runnable(),
5617 "still under its attempt budget: the queue never reached a natural idle \
5618 on its own, only the external stop ended the test"
5619 );
5620
5621 assert_eq!(
5622 crate::disk::dir_size(&cache_dir),
5623 0,
5624 "an oversized cache must not be left to grow unboundedly just because the \
5625 queue kept the loop busy the whole time"
5626 );
5627 }
5628
5629 #[test]
5630 fn task_question_reconciliation_keeps_references_and_retires_manual_releases() {
5631 let dir = tempfile::tempdir().unwrap();
5632 let queue = Queue::at(dir.path().join("queue"));
5633 let questions = Questions::at(dir.path().join("questions"));
5634 let mut task = task();
5635 queue.put(&mut task).unwrap();
5636
5637 let mut task_question = ask::Question::new(
5638 task.id.clone(),
5639 crate::conduct::NODE.to_owned(),
5640 "conduct".to_owned(),
5641 "Which backend?".to_owned(),
5642 String::new(),
5643 Vec::new(),
5644 );
5645 questions.put(&mut task_question).unwrap();
5646 task.block(vec![task_question.id.clone()], None);
5647 queue.put(&mut task).unwrap();
5648
5649 let mut run_question = ask::Question::new(
5650 "20260101-000000-run1".to_owned(),
5651 "review".to_owned(),
5652 "reviewer-1".to_owned(),
5653 "Run question".to_owned(),
5654 String::new(),
5655 Vec::new(),
5656 );
5657 questions.put(&mut run_question).unwrap();
5658
5659 // A question from another node whose `run` happens to equal this
5660 // task's id — the same field, filled in for an unrelated reason. Only
5661 // `crate::conduct::NODE` questions use `run` as a task id; this one
5662 // must never be touched by this reconciliation, even after release.
5663 let mut coincidental = ask::Question::new(
5664 task.id.clone(),
5665 "review".to_owned(),
5666 "reviewer-1".to_owned(),
5667 "Unrelated review question".to_owned(),
5668 String::new(),
5669 Vec::new(),
5670 );
5671 questions.put(&mut coincidental).unwrap();
5672
5673 reconcile_task_questions(&queue, &questions);
5674 assert!(questions.get(&task_question.id).unwrap().status.open());
5675 assert!(questions.get(&run_question.id).unwrap().status.open());
5676 assert!(questions.get(&coincidental.id).unwrap().status.open());
5677
5678 task.release();
5679 queue.put(&mut task).unwrap();
5680 reconcile_task_questions(&queue, &questions);
5681 assert_eq!(
5682 questions.get(&task_question.id).unwrap().status,
5683 ask::QuestionStatus::Abandoned
5684 );
5685 assert!(
5686 questions.get(&run_question.id).unwrap().status.open(),
5687 "run questions remain the run janitor's responsibility"
5688 );
5689 assert!(
5690 questions.get(&coincidental.id).unwrap().status.open(),
5691 "a non-conductor question must not be abandoned just because its \
5692 run id coincides with a task id"
5693 );
5694 }
5695
5696 #[test]
5697 fn a_freshly_started_running_task_is_never_stalled() {
5698 let dir = tempfile::tempdir().unwrap();
5699 let mut t = task();
5700 t.start("run-1".to_owned());
5701 // `updated_at` is `Timestamp::now()`, left alone: no live daemon
5702 // named in `dir`, but nowhere near `STALLED_RUNNING` yet.
5703 assert!(!is_stalled(&t, dir.path(), Timestamp::now()));
5704 }
5705
5706 #[test]
5707 fn a_long_running_task_with_no_live_daemon_is_stalled() {
5708 let dir = tempfile::tempdir().unwrap();
5709 let mut t = task();
5710 t.start("run-1".to_owned());
5711 t.updated_at = Timestamp::now()
5712 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
5713 assert!(is_stalled(&t, dir.path(), Timestamp::now()));
5714 assert_eq!(
5715 stalled_tasks(
5716 &Queue::at(dir.path().join("q")),
5717 dir.path(),
5718 Timestamp::now()
5719 )
5720 .len(),
5721 0,
5722 "the task was never written to this queue"
5723 );
5724 }
5725
5726 #[test]
5727 fn a_long_running_task_a_live_daemon_still_names_is_not_stalled() {
5728 let dir = tempfile::tempdir().unwrap();
5729 let mut t = task();
5730 t.id = "20260903-080340-0167".to_owned();
5731 t.start("20260903-080619-01c2".to_owned());
5732 t.updated_at = Timestamp::now()
5733 - jiff::SignedDuration::from_secs(STALLED_RUNNING.as_secs() as i64 + 60);
5734
5735 let mut status = Status::new();
5736 status.current = vec![Current {
5737 task: t.id.clone(),
5738 run: "20260903-080619-01c2".to_owned(),
5739 }];
5740 write_status_to(&dir.path().join("daemon.json"), &status).unwrap();
5741
5742 assert!(
5743 !is_stalled(&t, dir.path(), Timestamp::now()),
5744 "a live daemon's own heartbeat rules out stalled, however long the task has run"
5745 );
5746 }
5747
5748 /// Rewrite a task's `updated_at` on disk directly, bypassing
5749 /// `Queue::put`'s own `Timestamp::now()` stamping - the only way to make
5750 /// a fixture look like it has genuinely been `running` for a while.
5751 fn backdate_task(queue: &Queue, id: &str, seconds_ago: i64) {
5752 let path = queue.path_of(id);
5753 let body = std::fs::read_to_string(&path).unwrap();
5754 let mut v: serde_json::Value = serde_json::from_str(&body).unwrap();
5755 let old = Timestamp::now() - jiff::SignedDuration::from_secs(seconds_ago);
5756 v["updated_at"] = serde_json::Value::String(old.to_string());
5757 std::fs::write(&path, serde_json::to_string_pretty(&v).unwrap()).unwrap();
5758 }
5759
5760 #[test]
5761 fn stalled_tasks_still_reaches_a_task_reclaim_could_not_claim_yet() {
5762 // The realistic `poll()` ordering, not `is_stalled` in isolation:
5763 // `reclaim_orphaned_running` runs first, on every poll, and settles
5764 // any `running` task whose claim it can actually take. For most
5765 // crashes that is immediate - a dead pid is proof enough for
5766 // `sweep_stale_claims` to drop the lock the same tick, and the very
5767 // next claim attempt succeeds. But a lock whose pid cannot be parsed
5768 // at all falls back to `STALE_CLAIM`'s six-hour age instead (see
5769 // `sweep_stale_claims`'s own doc), so the lock - and the claim
5770 // failure behind it - can legitimately outlive many polls. This is
5771 // exactly the gap `stalled_tasks` exists to surface well before that
5772 // six-hour sweep would: reclaim leaves the task `running`, and it
5773 // must still reach the conductor as stalled.
5774 let dir = tempfile::tempdir().unwrap();
5775 let queue = Queue::at(dir.path().join("queue"));
5776 let home = dir.path().join("home");
5777
5778 let mut t = task();
5779 t.id = "20260101-000001-lock".to_owned();
5780 t.start("run-1".to_owned());
5781 queue.put(&mut t).unwrap();
5782 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
5783 std::fs::write(
5784 dir.path().join("queue").join(format!("{}.lock", t.id)),
5785 "not a pid",
5786 )
5787 .unwrap();
5788
5789 let now = Timestamp::now();
5790 assert!(
5791 reclaim_orphaned_running(&queue, 2).is_empty(),
5792 "the unparseable lock is still well within STALE_CLAIM, so the claim fails \
5793 and reclaim must leave the task alone"
5794 );
5795 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Running);
5796
5797 let stalled = stalled_tasks(&queue, &home, now);
5798 assert_eq!(
5799 stalled.len(),
5800 1,
5801 "reclaim's inability to claim it yet must not hide it from the conductor"
5802 );
5803 assert_eq!(stalled[0].id, t.id);
5804 }
5805
5806 #[test]
5807 fn ordinary_dead_daemon_task_is_shown_stalled_before_reclaim_and_can_be_requeued() {
5808 let dir = tempfile::tempdir().unwrap();
5809 crate::run::set_home(dir.path().join("run-home"));
5810 let queue = Queue::at(dir.path().join("queue"));
5811 let home = dir.path().join("home");
5812 let questions = Questions::at(dir.path().join("questions"));
5813
5814 let mut t = task();
5815 t.id = "20260101-000003-dead".to_owned();
5816 t.start("missing-run".to_owned());
5817 queue.put(&mut t).unwrap();
5818 backdate_task(&queue, &t.id, STALLED_RUNNING.as_secs() as i64 + 60);
5819
5820 // This is the real poll ordering: retain the deterministic stalled
5821 // input before a claim proves the owner is gone and reclaims it.
5822 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
5823 assert_eq!(
5824 stalled.iter().map(|task| &task.id).collect::<Vec<_>>(),
5825 [&t.id]
5826 );
5827 assert_eq!(reclaim_orphaned_running(&queue, 2), [t.id.clone()]);
5828 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Held);
5829
5830 // Reclaim drops its guard before conductor decisions are applied, so
5831 // the decision for the captured stalled input has a real write path.
5832 crate::conduct::apply(
5833 &queue,
5834 &questions,
5835 &crate::conduct::Verdict {
5836 decisions: vec![crate::conduct::Decision {
5837 id: t.id.clone(),
5838 recovery: Some(crate::conduct::Recovery::Requeue),
5839 ..crate::conduct::Decision::default()
5840 }],
5841 },
5842 )
5843 .unwrap();
5844 assert_eq!(queue.get(&t.id).unwrap().status, TaskStatus::Queued);
5845 }
5846
5847 #[test]
5848 fn stalled_tasks_reports_exactly_the_tasks_is_stalled_agrees_on() {
5849 let dir = tempfile::tempdir().unwrap();
5850 let queue = Queue::at(dir.path().join("queue"));
5851 let home = dir.path().join("home");
5852
5853 let mut fresh = task();
5854 fresh.id = "20260101-000001-aaaa".to_owned();
5855 fresh.start("run-1".to_owned());
5856 queue.put(&mut fresh).unwrap();
5857
5858 let mut old = task();
5859 old.id = "20260101-000002-bbbb".to_owned();
5860 old.start("run-2".to_owned());
5861 queue.put(&mut old).unwrap();
5862 backdate_task(&queue, &old.id, STALLED_RUNNING.as_secs() as i64 + 60);
5863
5864 let stalled = stalled_tasks(&queue, &home, Timestamp::now());
5865 assert_eq!(stalled.len(), 1);
5866 assert_eq!(stalled[0].id, old.id);
5867 }
5868
5869 #[test]
5870 fn queued_and_finished_task_views_partition_by_status() {
5871 let dir = tempfile::tempdir().unwrap();
5872 let queue = Queue::at(dir.path().join("queue"));
5873
5874 let mut queued = task();
5875 queued.id = "20260101-000001-aaaa".to_owned();
5876 queue.put(&mut queued).unwrap();
5877
5878 let mut failed = task();
5879 failed.id = "20260101-000002-bbbb".to_owned();
5880 failed.start("run-1".to_owned());
5881 failed.fail("gate red", 5);
5882 queue.put(&mut failed).unwrap();
5883
5884 let mut held = task();
5885 held.id = "20260101-000003-cccc".to_owned();
5886 held.hold_machine(None);
5887 queue.put(&mut held).unwrap();
5888
5889 let mut running = task();
5890 running.id = "20260101-000004-dddd".to_owned();
5891 running.start("run-2".to_owned());
5892 queue.put(&mut running).unwrap();
5893
5894 let queued_ids: Vec<String> = queued_tasks(&queue).into_iter().map(|t| t.id).collect();
5895 assert_eq!(queued_ids, [queued.id.clone()]);
5896
5897 let mut finished_ids: Vec<String> =
5898 finished_tasks(&queue).into_iter().map(|t| t.id).collect();
5899 finished_ids.sort_unstable();
5900 let mut want = vec![failed.id.clone(), held.id.clone()];
5901 want.sort_unstable();
5902 assert_eq!(finished_ids, want);
5903 }
5904
5905 #[test]
5906 fn resolve_blockers_clears_a_done_dependency_and_keeps_an_unresolved_one() {
5907 let dir = tempfile::tempdir().unwrap();
5908 let queue = Queue::at(dir.path().join("queue"));
5909 let questions = ask::Questions::at(dir.path().join("questions"));
5910
5911 let mut dep = task();
5912 dep.id = "20260101-000001-dep0".to_owned();
5913 dep.succeed();
5914 queue.put(&mut dep).unwrap();
5915
5916 let mut still_going = task();
5917 still_going.id = "20260101-000002-dep1".to_owned();
5918 queue.put(&mut still_going).unwrap();
5919
5920 let mut blocked = task();
5921 blocked.id = "20260101-000003-main".to_owned();
5922 blocked.block(
5923 vec![dep.id.clone(), still_going.id.clone()],
5924 Some("waits on both".to_owned()),
5925 );
5926 queue.put(&mut blocked).unwrap();
5927
5928 resolve_blockers(&queue, &questions);
5929
5930 let after = queue.get(&blocked.id).unwrap();
5931 assert_eq!(
5932 after.status,
5933 TaskStatus::Blocked,
5934 "one dependency is still outstanding"
5935 );
5936 assert_eq!(after.blocked_by, [still_going.id.clone()]);
5937 }
5938
5939 #[test]
5940 fn resolve_blockers_carries_an_answers_content_onto_the_task_and_unblocks_it() {
5941 let dir = tempfile::tempdir().unwrap();
5942 let queue = Queue::at(dir.path().join("queue"));
5943 let questions = ask::Questions::at(dir.path().join("questions"));
5944
5945 let mut q = crate::ask::Question::new(
5946 "20260101-000001-main".to_owned(),
5947 crate::conduct::NODE.to_owned(),
5948 "conduct".to_owned(),
5949 "Which backend?".to_owned(),
5950 String::new(),
5951 Vec::new(),
5952 );
5953 questions.put(&mut q).unwrap();
5954 q.answer(crate::ask::Answer::Text("SQLite".to_owned()))
5955 .unwrap();
5956 questions.put(&mut q).unwrap();
5957
5958 let mut blocked = task();
5959 blocked.id = "20260101-000001-main".to_owned();
5960 blocked.block(vec![q.id.clone()], Some("which backend?".to_owned()));
5961 queue.put(&mut blocked).unwrap();
5962
5963 resolve_blockers(&queue, &questions);
5964
5965 let after = queue.get(&blocked.id).unwrap();
5966 assert_eq!(
5967 after.status,
5968 TaskStatus::Queued,
5969 "the only blocker resolved"
5970 );
5971 assert_eq!(after.answers.len(), 1);
5972 assert_eq!(after.answers[0].question, "Which backend?");
5973 assert_eq!(after.answers[0].answer, "SQLite");
5974
5975 // And the run this task starts next is told about it.
5976 let instruction = instruction_for(&after);
5977 assert!(instruction.contains("Which backend?"));
5978 assert!(instruction.contains("SQLite"));
5979 }
5980
5981 #[test]
5982 fn resolve_blockers_restores_a_held_task_to_held_instead_of_queuing_it() {
5983 // Reproduces the reported bug (task 3958): a task held out of
5984 // attempts, blocked on a `crate::conduct` follow-up question, must
5985 // come back `held` once that question is answered - never `queued`,
5986 // whatever the answer said - or it silently re-enters the
5987 // competition queue with its attempts already exhausted.
5988 let dir = tempfile::tempdir().unwrap();
5989 let queue = Queue::at(dir.path().join("queue"));
5990 let questions = ask::Questions::at(dir.path().join("questions"));
5991
5992 let mut q = crate::ask::Question::new(
5993 "20260101-000001-main".to_owned(),
5994 crate::conduct::NODE.to_owned(),
5995 "conduct".to_owned(),
5996 "How should this be handled?".to_owned(),
5997 String::new(),
5998 Vec::new(),
5999 );
6000 questions.put(&mut q).unwrap();
6001 q.answer(crate::ask::Answer::Text(
6002 "leave it held, a human will look at it later".to_owned(),
6003 ))
6004 .unwrap();
6005 questions.put(&mut q).unwrap();
6006
6007 let mut held = task();
6008 held.id = "20260101-000001-main".to_owned();
6009 held.hold_machine(Some("out of attempts".to_owned()));
6010 held.block(vec![q.id.clone()], Some("what now?".to_owned()));
6011 queue.put(&mut held).unwrap();
6012
6013 resolve_blockers(&queue, &questions);
6014
6015 let after = queue.get(&held.id).unwrap();
6016 assert_eq!(after.status, TaskStatus::Held);
6017 assert_eq!(after.hold_reason.as_deref(), Some("out of attempts"));
6018 assert_eq!(
6019 after.answers[0].answer,
6020 "leave it held, a human will look at it later"
6021 );
6022 }
6023
6024 #[test]
6025 fn resolve_blockers_holds_a_task_whose_dependency_was_deleted() {
6026 // Reproduces the reported bug: a task blocked on a task id that was
6027 // removed (`magi task rm`, or deleted by hand) can never see that id
6028 // reach `Done`, so the ordinary per-id loop has nothing to notice and
6029 // would otherwise leave the task `blocked` forever with no way for an
6030 // operator to find out why.
6031 let dir = tempfile::tempdir().unwrap();
6032 let queue = Queue::at(dir.path().join("queue"));
6033 let questions = ask::Questions::at(dir.path().join("questions"));
6034
6035 let mut still_going = task();
6036 still_going.id = "20260101-000002-dep1".to_owned();
6037 queue.put(&mut still_going).unwrap();
6038
6039 let mut blocked = task();
6040 blocked.id = "20260101-000003-main".to_owned();
6041 blocked.block(
6042 vec!["20260101-000001-gone".to_owned(), still_going.id.clone()],
6043 Some("waits on both".to_owned()),
6044 );
6045 queue.put(&mut blocked).unwrap();
6046
6047 resolve_blockers(&queue, &questions);
6048
6049 let after = queue.get(&blocked.id).unwrap();
6050 assert_eq!(
6051 after.status,
6052 TaskStatus::Held,
6053 "a missing dependency must not leave the task blocked forever"
6054 );
6055 assert_eq!(after.hold_source, Some(crate::queue::HoldSource::Machine));
6056 assert!(after.blocked_by.is_empty());
6057 let reason = after.hold_reason.as_deref().unwrap_or_default();
6058 assert!(
6059 reason.contains("20260101-000001-gone"),
6060 "the missing id must be named so an operator can tell what happened: {reason}"
6061 );
6062 assert!(
6063 reason.contains(&still_going.id),
6064 "the still-valid dependency must not silently vanish from the record: {reason}"
6065 );
6066 }
6067
6068 #[test]
6069 fn instruction_for_is_unchanged_without_any_answers() {
6070 let t = task();
6071 assert_eq!(instruction_for(&t), t.instruction);
6072 }
6073
6074 #[test]
6075 fn resumed_instruction_is_unchanged_without_any_answers() {
6076 let t = task();
6077 assert_eq!(resumed_instruction(&t.instruction, &t), t.instruction);
6078 }
6079
6080 #[test]
6081 fn resumed_instruction_carries_a_new_answer_onto_the_old_run() {
6082 let mut t = task();
6083 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6084 // The run's own instruction on disk predates the answer: it is the
6085 // plain original text `Runner::start` saved before the operator was
6086 // ever asked anything.
6087 let old = t.instruction.clone();
6088
6089 let refreshed = resumed_instruction(&old, &t);
6090 assert!(refreshed.starts_with(&old), "the original text is kept");
6091 assert!(refreshed.contains("Which backend?"));
6092 assert!(refreshed.contains("SQLite"));
6093 }
6094
6095 #[test]
6096 fn resumed_instruction_keeps_an_original_answers_heading() {
6097 let mut t = task();
6098 t.instruction = "Context\n\n# Operator answers\n\nThis is part of the task.".to_owned();
6099 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6100
6101 let refreshed = resumed_instruction(&t.instruction, &t);
6102
6103 assert!(
6104 refreshed.starts_with(&t.instruction),
6105 "an answers heading in the original instruction is not the appended block"
6106 );
6107 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 2);
6108 assert!(refreshed.contains("Which backend?"));
6109 assert!(refreshed.contains("SQLite"));
6110
6111 let repeated = resumed_instruction(&refreshed, &t);
6112 assert_eq!(
6113 repeated, refreshed,
6114 "only the final appended block is refreshed"
6115 );
6116 }
6117
6118 #[test]
6119 fn resumed_instruction_does_not_duplicate_across_repeated_resumes() {
6120 let mut t = task();
6121 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6122
6123 // A first resume appends the block; a second resume of the same run,
6124 // with no new answer in between, must reproduce exactly the same
6125 // text rather than appending the block a second time.
6126 let once = resumed_instruction(&t.instruction, &t);
6127 let twice = resumed_instruction(&once, &t);
6128 assert_eq!(once, twice);
6129 assert_eq!(once.matches("Which backend?").count(), 1);
6130
6131 // A later answer replaces the block wholesale rather than growing it.
6132 t.record_answer("Which cache?".to_owned(), "Redis".to_owned());
6133 let refreshed = resumed_instruction(&once, &t);
6134 assert_eq!(refreshed.matches(ANSWERS_HEADER).count(), 1);
6135 assert!(refreshed.contains("Which backend?"));
6136 assert!(refreshed.contains("Which cache?"));
6137 }
6138
6139 #[test]
6140 fn prepare_instruction_covers_all_three_starters() {
6141 let mut t = task();
6142 t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6143
6144 // Start: a fresh run gets the task text plus every answer so far —
6145 // exactly `instruction_for`.
6146 assert_eq!(
6147 prepare_instruction(&Starter::Start, None, &t),
6148 Some(instruction_for(&t))
6149 );
6150
6151 // Resume: the run's prior instruction is refreshed with the answer,
6152 // not discarded and not left stale.
6153 let old = t.instruction.clone();
6154 assert_eq!(
6155 prepare_instruction(&Starter::Resume("some-run".to_owned()), Some(&old), &t),
6156 Some(resumed_instruction(&old, &t))
6157 );
6158
6159 // Review: a review-only pass builds its own instruction from the
6160 // branch's history in `crate::graph`, with no task statement at all -
6161 // this boundary must leave it alone.
6162 assert_eq!(
6163 prepare_instruction(&Starter::Review("magi/eba2/A".to_owned()), Some(&old), &t),
6164 None
6165 );
6166 }
6167
6168 #[test]
6169 fn choose_starter_prefers_review_over_resume_when_the_branch_survived() {
6170 assert_eq!(
6171 choose_starter(Some("magi/eba2/A"), true, Some("some-run")),
6172 Starter::Review("magi/eba2/A".to_owned())
6173 );
6174 }
6175
6176 #[test]
6177 fn choose_starter_falls_back_to_start_when_the_review_branch_is_gone() {
6178 assert_eq!(
6179 choose_starter(Some("magi/eba2/A"), false, Some("some-run")),
6180 Starter::Start,
6181 "a vanished review branch must not fall back to resuming the old run either"
6182 );
6183 }
6184
6185 #[test]
6186 fn choose_starter_resumes_or_starts_when_there_is_no_review_choice_at_all() {
6187 assert_eq!(
6188 choose_starter(None, false, Some("some-run")),
6189 Starter::Resume("some-run".to_owned())
6190 );
6191 assert_eq!(choose_starter(None, false, None), Starter::Start);
6192 }
6193
6194 #[test]
6195 fn an_explicit_release_forces_a_fresh_competition_even_with_a_resumable_run() {
6196 let mut released = task();
6197 released.start("stalled-run".to_owned());
6198 released.requeue();
6199 let unfinished = (!released.fresh_start)
6200 .then(|| Some("stalled-run".to_owned()))
6201 .flatten();
6202 assert_eq!(
6203 choose_starter(None, false, unfinished.as_deref()),
6204 Starter::Start,
6205 "release keeps run history but must not resume it"
6206 );
6207 assert_eq!(released.runs, ["stalled-run"]);
6208 }
6209
6210 #[test]
6211 fn an_ordinary_release_keeps_a_resumable_run_available() {
6212 let mut released = task();
6213 released.start("stalled-run".to_owned());
6214 released.release();
6215 let unfinished = (!released.fresh_start)
6216 .then(|| Some("stalled-run".to_owned()))
6217 .flatten();
6218 assert_eq!(
6219 choose_starter(None, false, unfinished.as_deref()),
6220 Starter::Resume("stalled-run".to_owned()),
6221 "manual release must preserve the normal resume path"
6222 );
6223 }
6224
6225 #[test]
6226 fn a_blocked_run_that_spent_every_review_round_has_exhausted_its_budget() {
6227 let mut state = run_state(RunStatus::Blocked);
6228 state.config.graph.review_rounds = 3;
6229 state.reviews = vec![review_round(1), review_round(2), review_round(3)];
6230 assert!(exhausted_review_budget(&state));
6231
6232 // One round still unused: resuming can still ask a reviewer something.
6233 state.reviews.pop();
6234 assert!(!exhausted_review_budget(&state));
6235
6236 // Exhausted rounds on a non-`Blocked` status (a stall, say) do not
6237 // count: only a `Blocked` run re-enters the review loop on resume.
6238 let mut stalled = run_state(RunStatus::Stalled);
6239 stalled.config.graph.review_rounds = 1;
6240 stalled.reviews = vec![review_round(1)];
6241 assert!(!exhausted_review_budget(&stalled));
6242 }
6243
6244 fn review_round(round: usize) -> crate::run::ReviewRound {
6245 crate::run::ReviewRound {
6246 round,
6247 head: "deadbeef".to_owned(),
6248 verified_head: None,
6249 verified_at: None,
6250 reviews: Vec::new(),
6251 e2e: Vec::new(),
6252 verify_retried: false,
6253 e2e_deferred: false,
6254 e2e_defer_reason: None,
6255 fix: None,
6256 blocking: 0,
6257 answered: 1,
6258 expected: 1,
6259 clean: false,
6260 progressed: true,
6261 vote_split: false,
6262 reconsideration: Vec::new(),
6263 verdict: None,
6264 }
6265 }
6266
6267 #[test]
6268 fn unfinished_run_skips_a_round_exhausted_blocked_run_so_requeue_means_a_fresh_competition() {
6269 // Mirrors the failure this exists to close: a task's last run ended
6270 // `Blocked` with the review budget spent, `crate::conduct` chose
6271 // `Recovery::Requeue` (`Task::release`, which keeps `runs` as
6272 // evidence), and without this check `attempt` would go on treating
6273 // that exhausted run as "unfinished" and resume it - `graph::Runner`'s
6274 // review loop iterates zero times over an already-spent budget, so
6275 // the resumed run settles right back to `Blocked` having asked nobody
6276 // anything, and `Requeue`'s promised fresh competition never happens.
6277 let mut exhausted = RunState::new(
6278 PathBuf::from("/repo"),
6279 "main".to_owned(),
6280 "abc1234def".to_owned(),
6281 "add retries".to_owned(),
6282 Config::default(),
6283 );
6284 exhausted.status = RunStatus::Blocked;
6285 exhausted.config.graph.review_rounds = 1;
6286 exhausted.reviews = vec![review_round(1)];
6287
6288 assert_eq!(
6289 unfinished_run_with(&[exhausted.id.clone()], "t", |_| Ok(exhausted.clone())),
6290 None,
6291 "an exhausted `Blocked` run must not be offered as resumable"
6292 );
6293
6294 // A `Blocked` run with rounds still unused is genuinely worth
6295 // resuming, and must still be found.
6296 let mut has_budget_left = RunState::new(
6297 PathBuf::from("/repo"),
6298 "main".to_owned(),
6299 "abc1234def".to_owned(),
6300 "add retries".to_owned(),
6301 Config::default(),
6302 );
6303 has_budget_left.status = RunStatus::Blocked;
6304 has_budget_left.config.graph.review_rounds = 3;
6305 has_budget_left.reviews = vec![review_round(1)];
6306
6307 assert_eq!(
6308 unfinished_run_with(&[has_budget_left.id.clone()], "t", |_| {
6309 Ok(has_budget_left.clone())
6310 }),
6311 Some(has_budget_left.id.clone())
6312 );
6313 }
6314
6315 #[test]
6316 fn unfinished_run_never_falls_back_to_an_older_resumable_run() {
6317 // A task whose history holds an *older* run that still looks
6318 // resumable (say, a competition `Runner::review` was started
6319 // alongside after that older run went `Stalled`) and a *newest* run
6320 // that is `Blocked` with its review budget spent. `Recovery::Requeue`
6321 // on this task must mean a fresh competition — falling back to the
6322 // stale, superseded `Stalled` run instead would resurrect history
6323 // nothing asked to revisit and silently defeat the requeue.
6324 let mut older_stalled = RunState::new(
6325 PathBuf::from("/repo"),
6326 "main".to_owned(),
6327 "abc1234def".to_owned(),
6328 "add retries".to_owned(),
6329 Config::default(),
6330 );
6331 older_stalled.status = RunStatus::Stalled;
6332
6333 let mut newest_exhausted = RunState::new(
6334 PathBuf::from("/repo"),
6335 "main".to_owned(),
6336 "abc1234def".to_owned(),
6337 "add retries".to_owned(),
6338 Config::default(),
6339 );
6340 newest_exhausted.status = RunStatus::Blocked;
6341 newest_exhausted.config.graph.review_rounds = 1;
6342 newest_exhausted.reviews = vec![review_round(1)];
6343
6344 assert_eq!(
6345 unfinished_run_with(
6346 &[older_stalled.id.clone(), newest_exhausted.id.clone()],
6347 "t",
6348 |_| Ok(newest_exhausted.clone())
6349 ),
6350 None,
6351 "the newest run is exhausted, so nothing here is worth resuming - \
6352 least of all the older, already-superseded run"
6353 );
6354 }
6355
6356 #[test]
6357 fn unfinished_run_warns_and_skips_a_run_it_cannot_read() {
6358 assert_eq!(
6359 unfinished_run_with(&["20260101-000000-gone".to_owned()], "t", |_| {
6360 Err(anyhow::anyhow!("fixture is absent"))
6361 }),
6362 None
6363 );
6364 }
6365}