Skip to main content

magi/
queue.rs

1//! The task queue: what magi should do next, and who asked for it.
2//!
3//! The queue is what lets magi run unattended. `magi serve` takes the next
4//! task, runs the graph on it, records the outcome, and takes the next one.
5//!
6//! It is also the reason an agent can ask for work. `magi task add` is the
7//! whole interface, and it is the same command whether a human types it at a
8//! prompt, a phone posts it through the web UI, or an implementer inside a run
9//! shells out to it because it noticed something worth doing but out of scope.
10//! magi's CLI is the operating surface for both kinds of user; the queue is
11//! where their intentions meet.
12//!
13//! One task is one JSON file under [`Queue`]'s root. Files rather than a
14//! database because the operator has to be able to read, edit, and delete the
15//! backlog with the tools already on the machine, and because a crashed daemon
16//! must leave a queue the next one can pick up without recovery ceremony.
17//!
18//! # Shape
19//!
20//! [`Task`] is data plus *pure* state transitions - [`Task::fail`] decides
21//! whether an attempt was the last one, and touches no disk. [`Queue`] owns all
22//! I/O and is constructed with its root, so a test drives a real queue in a
23//! temp directory without setting a process-global home. Splitting them this
24//! way is why the retry policy below can be asserted directly.
25//!
26//! # Bounded by construction
27//!
28//! An autonomous loop that retries forever is a way to spend money on a task
29//! that cannot succeed. Every claim increments [`Task::attempts`]; a task that
30//! has burned its attempts becomes [`TaskStatus::Held`] and waits for a human
31//! rather than for another agent.
32
33use std::collections::HashMap;
34use std::path::{Path, PathBuf};
35
36use anyhow::{Context, Result, bail};
37use jiff::Timestamp;
38use serde::{Deserialize, Serialize};
39
40use crate::ask::Questions;
41
42/// On-disk format for a queued task. Bumped when a field's meaning changes.
43///
44/// 6: added [`Task::resume_override`] (a field only; `#[serde(default)]`, so
45/// an older record reads as `None` and [`read_path`] still accepts it).
46///
47/// 5: added [`Task::triage_applied`], the ids of triage questions whose
48/// answer has already been applied to this task. A "resume" answer used to
49/// leave no trace ([`Task::release`] clears [`Task::hold_reason`], which was
50/// the only place the applied marker lived), so when the released task failed
51/// its attempts and went back to `held`, the next idle pass found the same
52/// answered question "not applied" and released it again with `attempts` reset
53/// to 0 - the `max_attempts` bound never held. `#[serde(default)]` so an older
54/// record reads as empty. A task already looping when this build arrives has
55/// no record, so it is released once more, recorded, and then stays held.
56///
57/// 4: added [`Task::blocked_from`], the status a task had the moment it
58/// became [`TaskStatus::Blocked`], so [`Task::unblock`] restores it instead
59/// of always landing on [`TaskStatus::Queued`]. Without it, a task a human
60/// or `crate::triage` had deliberately left [`TaskStatus::Held`] — machine
61/// or manual — would lose that the instant `crate::conduct` blocked it on a
62/// follow-up question, and come back `Queued` the moment the question was
63/// answered, regardless of what the answer said: exactly the loop where a
64/// task the operator told to stay held instead re-enters the competition
65/// queue every time someone answers a question about it. `#[serde(default)]`
66/// so an older record reads as `None`; [`Task::unblock`] then falls back to
67/// inferring `Held` from surviving hold evidence ([`Task::hold_reason`] /
68/// [`Task::hold_source`], never cleared by [`Task::block`]) rather than
69/// guessing `Queued` outright — see [`Task::unblock`]'s own doc.
70///
71/// 3: added [`HoldSource`] so conductor recovery cannot release a hold an
72/// operator deliberately placed. Old records default to `None` and are
73/// protected as operator-held until an explicit release; the safe direction
74/// when their author was never recorded.
75///
76/// 2: added [`TaskStatus::Blocked`], [`Task::blocked_by`] and
77/// [`Task::block_reason`] (`crate::conduct`'s decisions) and
78/// [`Task::answers`] (operator answers carried forward to the next
79/// conductor prompt and the next run's instruction). All three are
80/// `#[serde(default)]`, so [`read_path`] accepts anything up to and
81/// including this schema rather than only an exact match — a task written
82/// by a build that only knew about schema 1 has nothing to say about
83/// blocking or answers, and defaulting those fields is exactly as good a
84/// reading as a value that build never had a chance to write.
85pub const SCHEMA: u32 = 6;
86
87/// Who placed the current hold.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
89#[serde(rename_all = "lowercase")]
90pub enum HoldSource {
91    /// An operator used the CLI or web UI.
92    Manual,
93    /// The daemon or conductor placed the hold as part of its own recovery.
94    Machine,
95}
96
97impl HoldSource {
98    /// Short human-facing label for reports and the CLI.
99    pub fn label(self) -> &'static str {
100        match self {
101            Self::Manual => "manual",
102            Self::Machine => "machine",
103        }
104    }
105}
106
107/// Where a task came from. Recorded because "who asked for this" is the first
108/// question about an autonomous run, and the answer is not recoverable later.
109#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(tag = "kind", rename_all = "lowercase")]
111pub enum Source {
112    /// A person, at a terminal or through the web UI.
113    Human,
114    /// An agent inside a run, via `magi task add`. Both ids are recorded so a
115    /// task can be traced back to the exact seat that asked for it.
116    Agent {
117        /// Run the asking agent belonged to.
118        run: String,
119        /// Node it was working in, e.g. `implement` or `review`.
120        node: String,
121    },
122    /// A GitHub issue, imported by number.
123    Issue {
124        /// Issue number.
125        number: u64,
126        /// `owner/repo`, as `gh` reports it.
127        repo: String,
128    },
129}
130
131impl Source {
132    /// Short human-facing label, for lists and the web UI.
133    pub fn label(&self) -> String {
134        match self {
135            Self::Human => "human".to_owned(),
136            Self::Agent { run, node } => format!("{node}@{}", short(run)),
137            Self::Issue { number, .. } => format!("issue #{number}"),
138        }
139    }
140}
141
142/// Where a task is in its life.
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
144#[serde(rename_all = "lowercase")]
145pub enum TaskStatus {
146    /// Waiting to be claimed.
147    Queued,
148    /// Claimed by a daemon; a run is in flight.
149    Running,
150    /// A run finished and its gate passed.
151    Done,
152    /// A run finished without passing, and attempts remain.
153    Failed,
154    /// Out of attempts, or held by hand. The loop will not pick it up.
155    Held,
156    /// Waiting on another task or an unanswered question. See
157    /// [`Task::blocked_by`]. Set and cleared by `crate::conduct` and
158    /// `crate::daemon`'s deterministic resolver, never by hand.
159    Blocked,
160}
161
162impl TaskStatus {
163    /// Is this task eligible for a daemon to claim?
164    pub fn runnable(self) -> bool {
165        matches!(self, Self::Queued | Self::Failed)
166    }
167
168    /// Lowercase name, as it appears on disk and in the API.
169    pub fn as_str(self) -> &'static str {
170        match self {
171            Self::Queued => "queued",
172            Self::Running => "running",
173            Self::Done => "done",
174            Self::Failed => "failed",
175            Self::Held => "held",
176            Self::Blocked => "blocked",
177        }
178    }
179}
180
181/// How many tasks sit in each [`TaskStatus`], for a dashboard tile — never a
182/// per-task view, so it carries no ids.
183#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
184pub struct TaskCounts {
185    /// Waiting to be claimed.
186    pub queued: usize,
187    /// Claimed; a run is in flight.
188    pub running: usize,
189    /// A run finished and its gate passed.
190    pub done: usize,
191    /// A run finished without passing, and attempts remain.
192    pub failed: usize,
193    /// Out of attempts, or held by hand.
194    pub held: usize,
195    /// Waiting on another task or an unanswered question.
196    pub blocked: usize,
197}
198
199impl TaskCounts {
200    /// Tally `tasks` by status. A pure function over whatever [`Queue::list`]
201    /// already read, so it needs no root of its own and stays trivially
202    /// testable against a hand-built slice.
203    pub fn of(tasks: &[Task]) -> Self {
204        let mut counts = Self::default();
205        for t in tasks {
206            match t.status {
207                TaskStatus::Queued => counts.queued += 1,
208                TaskStatus::Running => counts.running += 1,
209                TaskStatus::Done => counts.done += 1,
210                TaskStatus::Failed => counts.failed += 1,
211                TaskStatus::Held => counts.held += 1,
212                TaskStatus::Blocked => counts.blocked += 1,
213            }
214        }
215        counts
216    }
217}
218
219/// One unit of work.
220#[derive(Debug, Clone, Serialize, Deserialize)]
221#[serde(deny_unknown_fields)]
222pub struct Task {
223    /// On-disk format version.
224    pub schema: u32,
225    /// Task id, e.g. `20260902-140501-a1b2`.
226    pub id: String,
227    /// One line, for lists and notifications.
228    pub title: String,
229    /// The task itself, handed to the graph verbatim.
230    pub instruction: String,
231    /// Repository to work in.
232    pub repo: PathBuf,
233    /// Who asked.
234    pub source: Source,
235    /// Higher runs first; ties break oldest-first so nothing starves.
236    #[serde(default)]
237    pub priority: i32,
238    /// Run this task alone: one implementer, no panel of judges to convince.
239    ///
240    /// `#[serde(default)]` so a queue file written before this field existed
241    /// still reads, as `false` - the ordinary multi-candidate competition,
242    /// unchanged. A task set to `solo` still runs the whole graph; only the
243    /// candidate count the daemon builds it with changes, and
244    /// [`crate::graph::Runner`] already collapses a single-candidate run to
245    /// implement → review → gate → merge on its own (see
246    /// [`crate::graph::Runner::review`]'s doc), so nothing about judging,
247    /// deliberation or voting had to change to support this.
248    #[serde(default)]
249    pub solo: bool,
250    /// Current state.
251    pub status: TaskStatus,
252    /// How many times this task has been claimed.
253    #[serde(default)]
254    pub attempts: usize,
255    /// Runs this task has produced, oldest first.
256    #[serde(default)]
257    pub runs: Vec<String>,
258    /// Why the last attempt did not land.
259    #[serde(default)]
260    pub last_error: Option<String>,
261    /// What a human hold is waiting on.
262    ///
263    /// `None` covers both the ordinary cases: a hold the loop makes itself
264    /// (out of attempts, or the disk gate closed) explains itself through
265    /// [`Task::last_error`] instead, and a human hold nobody bothered to
266    /// explain is still a valid hold. The queue has no way to express a
267    /// dependency between two tasks, so on the occasions a hold really is
268    /// "wait for that other task first", this is the only place that reason
269    /// survives - see [`Task::hold_manual`] and [`Task::release`].
270    ///
271    /// `#[serde(default)]` so a queue file written before this field existed
272    /// still reads, with no reason recorded rather than a parse error.
273    #[serde(default)]
274    pub hold_reason: Option<String>,
275    /// Who placed [`Task::hold_reason`].  `None` is a compatible old record;
276    /// see [`Task::operator_held`] for its deliberately conservative meaning.
277    #[serde(default)]
278    pub hold_source: Option<HoldSource>,
279    /// Diagnostic detail excerpted from the run that led to a hold - what a
280    /// human would have found opening `artifacts/` by hand, not the one-line
281    /// reason in [`Task::last_error`]. Set only when a run's own attempts are
282    /// exhausted and the task becomes [`TaskStatus::Held`]; `daemon` computes
283    /// it from the run's own record, since this module has no notion of a
284    /// run's internals. Bounded in length by the writer - see
285    /// `daemon::diagnostic` - so a verbose run cannot make this file grow
286    /// without limit.
287    ///
288    /// `#[serde(default)]` so a queue file written before this field existed
289    /// still reads, with no diagnostic recorded rather than a parse error.
290    #[serde(default)]
291    pub diagnostic: Option<String>,
292    /// What this task is waiting on: other task ids, unanswered
293    /// `crate::ask::Question` ids, or both. Non-empty exactly when
294    /// [`TaskStatus::Blocked`]; emptying it — see [`Task::unblock`] — is what
295    /// puts the task back at [`TaskStatus::Queued`].
296    ///
297    /// Set by `crate::conduct`'s decisions and cleared deterministically by
298    /// `crate::daemon` as each dependency resolves, never by a person. Never
299    /// `#[serde(default)]` is skipped: a queue file from before this field
300    /// existed has nothing to report here, and an empty list is exactly that.
301    #[serde(default)]
302    pub blocked_by: Vec<String>,
303    /// One line explaining the current [`Task::blocked_by`], written by
304    /// `crate::conduct`. Cleared whenever `blocked_by` empties.
305    #[serde(default)]
306    pub block_reason: Option<String>,
307    /// The status this task had the moment [`Task::block`] most recently
308    /// moved it to [`TaskStatus::Blocked`] — what [`Task::unblock`] restores
309    /// once nothing is left in `blocked_by`, instead of always landing on
310    /// [`TaskStatus::Queued`]. See [`SCHEMA`]'s doc for schema 4 on why this
311    /// exists: an answer to a question `crate::conduct` filed about a
312    /// [`TaskStatus::Held`] task must not itself be what puts the task back
313    /// in the competition queue.
314    ///
315    /// `#[serde(default)]` so a queue file written before this field existed
316    /// reads as `None`; [`Task::unblock`] treats that the same as a task
317    /// blocked straight from `Queued`, unless surviving hold evidence says
318    /// otherwise.
319    #[serde(default)]
320    pub blocked_from: Option<TaskStatus>,
321    /// Questions `crate::conduct` asked about this task that the operator has
322    /// since answered, oldest first — what was asked, and what they said.
323    ///
324    /// A blocking question's id leaves [`Task::blocked_by`] the moment
325    /// [`crate::ask::QuestionStatus::Answered`] is observed, but the id alone
326    /// tells nobody what was decided. This is what carries the answer's
327    /// *content* forward: into the next conductor prompt for this task, and
328    /// into the instruction handed to the next run — see `crate::daemon`'s
329    /// deterministic blocker resolution. Kept for the task's whole life, the
330    /// same as [`Task::runs`]: a release resets attempts, not evidence.
331    #[serde(default)]
332    pub answers: Vec<AnsweredQuestion>,
333    /// Ids of the `crate::triage` questions whose answer has been applied to
334    /// this task. Unlike [`Task::hold_reason`], [`Task::release`] and every
335    /// hold transition leave it alone, so an answer is applied at most once
336    /// however many times the task is held again. See [`SCHEMA`]'s doc for
337    /// schema 5. `#[serde(default)]` so an older record reads as empty.
338    #[serde(default)]
339    pub triage_applied: Vec<String>,
340    /// The operator's "resume" answer to a triage question, kept until the
341    /// task actually runs (or is done) so `crate::conduct` cannot silently
342    /// undo it and `crate::triage` can tell that a hold it sees now came
343    /// *after* the answer. See [`OperatorResume`]. `#[serde(default)]`.
344    #[serde(default)]
345    pub resume_override: Option<OperatorResume>,
346    /// Set by `crate::conduct` when it chooses `Review` recovery for a task
347    /// whose branch survived a blocked run: the branch to reopen with
348    /// `crate::graph::Runner::review` instead of competing from scratch.
349    ///
350    /// Requeues the task the same way [`Task::release`] does, so it is
351    /// picked up by the ordinary loop; `crate::daemon` reads this field once,
352    /// when it actually starts the run, and clears it either way — consumed
353    /// on success, dropped if the branch no longer exists by then. Never set
354    /// from the conductor's own words: `crate::daemon` derives the branch
355    /// name itself from the task's last run, so a hallucinated branch can
356    /// never reach here.
357    #[serde(default)]
358    pub review_branch: Option<String>,
359    /// A release deliberately starts a new competition instead of resuming
360    /// the prior run. History remains as evidence in `runs`.
361    #[serde(default)]
362    pub fresh_start: bool,
363    /// Marked by an operator (`magi task interrupt`) to ask `magi serve` to
364    /// run this one ahead of whatever it already has in flight, once
365    /// `[daemon] pause_for_interrupts` is on - see
366    /// `crate::daemon::advance_interrupt`. Never set by the loop itself, and
367    /// deliberately a different operation from [`Task::set_priority`]: a
368    /// priority only reorders the queue a claim has not reached yet, while
369    /// this asks a run already in flight to park at its next safe boundary
370    /// and step aside. `#[serde(default)]` so a queue file written before
371    /// this field existed still reads, as `false` - no task interrupts
372    /// anything unless asked to, exactly as before.
373    #[serde(default)]
374    pub interrupt: bool,
375    /// Marked by `magi task add --urgent`: `crate::daemon::poll` dispatches
376    /// this task through its own one-slot `urgent_sem` the moment it is
377    /// runnable, in addition to whatever is already running under the
378    /// ordinary `[daemon] max_concurrent_runs` pool - never instead of it,
379    /// and never by pausing or otherwise touching that run. This is the
380    /// opposite direction from [`Task::interrupt`]: that one asks a run
381    /// already in flight to step aside; this one never asks anything to
382    /// step aside, it only spends one additional, temporary concurrency
383    /// slot. The two are independent and may both be set on the same task,
384    /// but this exemption stops at `[daemon] pause_for_interrupts`'s own
385    /// park/resume handoff (75dd): while an interrupt sequence is actively
386    /// parking, running, or resuming - its own, or an unrelated task's -
387    /// `crate::daemon::interrupt_gate` withholds an urgent candidate exactly
388    /// like an ordinary one, never exempted. 75dd's "at most one run, ever,
389    /// at once" guarantee takes precedence, because the alternative is a run
390    /// still genuinely in flight (only *asked* to park, not yet gone) ending
391    /// up alongside a second one this feature let through - the very thing
392    /// that guarantee exists to rule out.
393    ///
394    /// `#[serde(default)]` so a queue file written before this field existed
395    /// still reads, as `false` - no task claims the urgent slot unless asked
396    /// to, exactly as before.
397    #[serde(default)]
398    pub urgent: bool,
399    /// When the task was filed.
400    pub created_at: Timestamp,
401    /// Last change to this file.
402    pub updated_at: Timestamp,
403}
404
405/// A triage "resume" answer and what became of it. See
406/// [`Task::resume_override`].
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
408pub struct OperatorResume {
409    /// The triage question the operator answered.
410    pub question_id: String,
411    /// When the answer was applied.
412    pub at: Timestamp,
413    /// The reason `crate::conduct` gave for holding the task again after the
414    /// answer, if it did. The conductor may do this once.
415    #[serde(default)]
416    pub conductor_rehold: Option<String>,
417    /// The operator answered "resume" a second time, to the question about
418    /// that contradiction: the conductor may no longer hold this task.
419    #[serde(default)]
420    pub forced: bool,
421}
422
423/// One question `crate::conduct` asked about a task, and what the operator
424/// said back. See [`Task::answers`].
425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
426pub struct AnsweredQuestion {
427    /// The question as asked, e.g. [`crate::ask::Question::summary`].
428    pub question: String,
429    /// What the operator answered.
430    pub answer: String,
431}
432
433impl Task {
434    /// File a new task. Persist it with [`Queue::put`].
435    pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
436        let now = Timestamp::now();
437        Self {
438            schema: SCHEMA,
439            id: new_id(),
440            title,
441            instruction,
442            repo,
443            source,
444            priority: 0,
445            solo: false,
446            status: TaskStatus::Queued,
447            attempts: 0,
448            runs: Vec::new(),
449            last_error: None,
450            hold_reason: None,
451            hold_source: None,
452            diagnostic: None,
453            blocked_by: Vec::new(),
454            block_reason: None,
455            blocked_from: None,
456            answers: Vec::new(),
457            triage_applied: Vec::new(),
458            resume_override: None,
459            review_branch: None,
460            fresh_start: false,
461            interrupt: false,
462            urgent: false,
463            created_at: now,
464            updated_at: now,
465        }
466    }
467
468    /// Short form used in reports, matching a run's short id.
469    pub fn short(&self) -> &str {
470        short(&self.id)
471    }
472
473    /// Record that triage question `question_id`'s answer has been applied.
474    pub fn mark_triage_applied(&mut self, question_id: &str) {
475        if !self.triage_applied(question_id) {
476            self.triage_applied.push(question_id.to_owned());
477        }
478    }
479
480    /// Has triage question `question_id`'s answer already been applied?
481    pub fn triage_applied(&self, question_id: &str) -> bool {
482        self.triage_applied.iter().any(|id| id == question_id)
483    }
484
485    /// Record that a run has started for this task.
486    ///
487    /// Clears [`Task::interrupt`]: a mark to run ahead of whatever else is
488    /// in flight is fulfilled the moment this task actually gets its turn,
489    /// dispatched same as any other. Without this, a task whose run fails
490    /// and requeues - still `runnable`, still carrying the mark from its
491    /// first attempt - would keep re-triggering `crate::daemon`'s interrupt
492    /// scheduler and re-parking whatever it interrupted on every later
493    /// boundary, for as long as its attempts hold out, instead of the
494    /// one-shot "let this go next" the mark is meant to be.
495    pub fn start(&mut self, run: String) {
496        self.status = TaskStatus::Running;
497        self.attempts += 1;
498        self.runs.push(run);
499        self.last_error = None;
500        self.fresh_start = false;
501        self.interrupt = false;
502        // The answer has been honoured: the task got its turn.
503        self.resume_override = None;
504    }
505
506    /// Record a successful run.
507    ///
508    /// Both `magi task done` and `POST /api/queue/{id}/done` can close a held
509    /// *or blocked* task directly, with no release in between, so this clears
510    /// `hold_reason` and `blocked_by`/`block_reason` the same way
511    /// [`Task::release`] does. Otherwise a task held for "waiting on 3ed9", or
512    /// blocked on a dependency that never actually finished, and then closed
513    /// as done without ever being released would still read as waiting on
514    /// something in `magi task show` and on its card, after it no longer is.
515    pub fn succeed(&mut self) {
516        self.status = TaskStatus::Done;
517        self.resume_override = None;
518        self.last_error = None;
519        self.hold_reason = None;
520        self.hold_source = None;
521        self.diagnostic = None;
522        self.blocked_by.clear();
523        self.block_reason = None;
524        self.blocked_from = None;
525    }
526
527    /// Earlier attempts at this task that a later one has since made moot —
528    /// empty unless the task is [`TaskStatus::Done`] *and* `last_run_succeeded`
529    /// says `runs.last()` is actually why.
530    ///
531    /// `runs` is oldest first, and [`Task::start`] is the only thing that
532    /// pushes to it, always right before the attempt it names either succeeds
533    /// or fails; `succeed` itself never touches `runs`. So whenever `status`
534    /// is `Done` *because* the loop itself saw that last attempt land
535    /// (`Merged`/`Ready`), everything before it in the same list is a retry
536    /// this task no longer needs. But `succeed` is also reachable directly —
537    /// `magi task done`, the web UI's equivalent, and the conductor's
538    /// `Recovery::Done` all call it on a task in *any* status, including one
539    /// whose last recorded attempt never landed at all (closed by hand after
540    /// a merge magi's own loop never saw). `runs.last()` alone cannot tell
541    /// those two cases apart — that requires the caller to have actually
542    /// looked at that run's own `status`, which this module has no way to
543    /// do — so `last_run_succeeded` is the caller's answer to exactly that
544    /// question, not something this function can derive from `Task` alone.
545    ///
546    /// Deliberately narrower than [`Queue::superseded`]'s "every earlier
547    /// attempt has a later one" walk, which fires the moment a retry starts
548    /// even though the retry itself might still fail: that reading is right
549    /// for the web UI's "a newer attempt exists, go look at that one
550    /// instead" note, but wrong for deciding a run no longer needs a human's
551    /// attention, which is only true once the task's story has actually
552    /// ended well. Two Blocked runs sitting side by side while a third
553    /// attempt is still in flight must not be touched by this — see
554    /// `daemon::supersede_prior_runs`, the caller that turns this list into
555    /// rewritten `run.json` files.
556    pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
557        if self.status != TaskStatus::Done || !last_run_succeeded || self.runs.len() < 2 {
558            return &[];
559        }
560        &self.runs[..self.runs.len() - 1]
561    }
562
563    /// Record a failed attempt. Out of attempts means held for a human, rather
564    /// than retried until the money runs out.
565    ///
566    /// Clears [`Task::diagnostic`] unconditionally: it belongs to whatever run
567    /// produced it, and a caller that has one for *this* attempt sets it
568    /// itself right after calling this, once it knows the task actually ended
569    /// up [`TaskStatus::Held`] - see `daemon::diagnostic`. Without the clear, a
570    /// task released after a diagnosed hold and then failed again for an
571    /// unrelated, undiagnosed reason (a config error, say) would go on
572    /// showing the previous run's diagnostic as if it explained the new one.
573    ///
574    /// Also records `why` into [`Task::hold_reason`] when this ends up
575    /// [`TaskStatus::Held`], so the notification and `magi task show` say the
576    /// same thing as [`Task::last_error`] instead of leaving the hold's own
577    /// reason blank.
578    pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
579        let why = why.into();
580        self.diagnostic = None;
581        self.status = if self.attempts >= max_attempts {
582            self.hold_source = Some(HoldSource::Machine);
583            self.hold_reason = Some(why.clone());
584            TaskStatus::Held
585        } else {
586            TaskStatus::Failed
587        };
588        self.last_error = Some(why);
589    }
590
591    /// Record an attempt that failed for a reason the task is not responsible
592    /// for - the agent CLIs ran out of quota and the judging panel collapsed.
593    ///
594    /// This refunds the attempt on purpose. A quota window closing at 4am must
595    /// not spend the backlog's retry budget: the operator would come back to a
596    /// queue of held tasks that were never actually judged, and would have to
597    /// release every one by hand to find out which had a real problem. The task
598    /// goes back to `Failed`, which the loop retries, so a reset quota picks the
599    /// work up where it stopped.
600    pub fn stall(&mut self, why: impl Into<String>) {
601        self.last_error = Some(why.into());
602        self.diagnostic = None;
603        self.attempts = self.attempts.saturating_sub(1);
604        self.status = TaskStatus::Failed;
605    }
606
607    /// Whether this held task may only be released by an operator.
608    ///
609    /// Old files did not record a source. Preserve every such hold rather
610    /// than guessing that it was automatic and risking duplicate work. New
611    /// automatic holds record [`HoldSource::Machine`] and remain recoverable.
612    pub fn operator_held(&self) -> bool {
613        self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
614    }
615
616    /// Take this task out of the loop's reach by an operator action.
617    ///
618    /// Clears `blocked_by`/`block_reason` unconditionally, the same as
619    /// [`Task::release`] and for the same reason its own comment already
620    /// gives: a human choosing to hold a *blocked* task overrides its wait
621    /// outright, the same as it overrides an ordinary hold. Without this, a
622    /// task held straight out of [`TaskStatus::Blocked`] - the web UI's "Hold"
623    /// button is reachable on a blocked task, same as "Mark done" - kept
624    /// reading as still waiting on a dependency it no longer had any claim on.
625    pub fn hold_manual(&mut self, reason: Option<String>) {
626        self.status = TaskStatus::Held;
627        if reason.is_some() {
628            self.hold_reason = reason;
629        }
630        self.hold_source = Some(HoldSource::Manual);
631        self.blocked_by.clear();
632        self.block_reason = None;
633        self.blocked_from = None;
634    }
635
636    /// Take this task out of the loop's reach during automatic recovery.
637    ///
638    /// Clears `blocked_by`/`block_reason` for the same reason
639    /// [`Task::hold_manual`] does.
640    pub fn hold_machine(&mut self, reason: Option<String>) {
641        self.status = TaskStatus::Held;
642        if reason.is_some() {
643            self.hold_reason = reason;
644        }
645        self.hold_source = Some(HoldSource::Machine);
646        self.blocked_by.clear();
647        self.block_reason = None;
648        self.blocked_from = None;
649    }
650
651    /// Block this task on other task ids and/or open question ids, chosen by
652    /// `crate::conduct`. Pure: the caller still owns writing it back with
653    /// [`Queue::put`].
654    ///
655    /// Records [`Task::blocked_from`] the first time this moves the task into
656    /// [`TaskStatus::Blocked`], and leaves it alone on a later call that adds
657    /// or replaces `blocked_by` while the task is already `Blocked` - a
658    /// second question about an already-blocked task must not overwrite the
659    /// status it should eventually return to with `Blocked` itself.
660    pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
661        if self.status != TaskStatus::Blocked {
662            self.blocked_from = Some(self.status);
663        }
664        self.status = TaskStatus::Blocked;
665        self.blocked_by = blocked_by;
666        self.block_reason = reason;
667    }
668
669    /// Remove one resolved dependency (a task id that became [`TaskStatus::Done`],
670    /// or a question id that became [`crate::ask::QuestionStatus::Answered`]).
671    /// Once nothing is left in [`Task::blocked_by`], the task returns to
672    /// whatever [`Task::blocked_from`] recorded - deciding *why* a task was
673    /// blocked was `crate::conduct`'s job, but noticing a dependency resolved
674    /// needs no model at all, and restoring the status it interrupted needs
675    /// nothing more than what `block` already wrote down.
676    ///
677    /// A task blocked while `Running` restores to [`TaskStatus::Queued`]
678    /// instead: whatever process was running it is gone by the time this
679    /// runs, so there is nothing left to resume. A task with no recorded
680    /// `blocked_from` - a pre-schema-4 record, or one blocked before this
681    /// field existed - falls back to [`TaskStatus::Held`] when it still
682    /// carries hold evidence ([`Task::hold_reason`] or [`Task::hold_source`],
683    /// neither ever cleared by `block`), and to `Queued` otherwise: the same
684    /// choice `block` itself would have recorded, reconstructed from what
685    /// survived.
686    ///
687    /// A no-op, on purpose, for a task that is not [`TaskStatus::Blocked`]:
688    /// `crate::daemon`'s deterministic resolver runs over every task on every
689    /// poll, and a task that moved on for some other reason must not be
690    /// dragged back by a stale id it still happens to carry.
691    pub fn unblock(&mut self, resolved_id: &str) {
692        if self.status != TaskStatus::Blocked {
693            return;
694        }
695        self.blocked_by.retain(|id| id != resolved_id);
696        if self.blocked_by.is_empty() {
697            self.status = match self.blocked_from {
698                Some(TaskStatus::Running) => TaskStatus::Queued,
699                Some(other) => other,
700                None if self.hold_reason.is_some() || self.hold_source.is_some() => {
701                    TaskStatus::Held
702                }
703                None => TaskStatus::Queued,
704            };
705            self.block_reason = None;
706            self.blocked_from = None;
707        }
708    }
709
710    /// Record that a question `crate::conduct` asked about this task has been
711    /// answered, so the answer's content — not just the fact that the
712    /// question is gone — reaches the next conductor prompt and the next
713    /// run's instruction. See [`Task::answers`].
714    pub fn record_answer(&mut self, question: String, answer: String) {
715        self.answers.push(AnsweredQuestion { question, answer });
716    }
717
718    /// Requeue this task to reopen its last run as a review-only pass against
719    /// `branch` (`crate::graph::Runner::review`) rather than competing from
720    /// scratch. See [`Task::review_branch`].
721    pub fn request_review(&mut self, branch: String) {
722        self.release();
723        self.review_branch = Some(branch);
724    }
725
726    /// Requeue after a conductor chose a new competition. Unlike an ordinary
727    /// operator release, this deliberately does not resume the old run.
728    pub fn requeue(&mut self) {
729        self.release();
730        self.fresh_start = true;
731    }
732
733    /// Change how urgently this task should run next.
734    ///
735    /// Refused once the task is `running`: priority only feeds the sort
736    /// [`Queue::next_runnable`] does over tasks waiting to be claimed, and a
737    /// running task has already left that pool. Accepting the write anyway
738    /// would look like it worked while changing nothing until - and unless -
739    /// this attempt fails and the task becomes runnable again, which is a
740    /// surprise the phone should not hand back as a success.
741    pub fn set_priority(&mut self, priority: i32) -> Result<()> {
742        if self.status == TaskStatus::Running {
743            bail!(
744                "task {} is running; its priority cannot be changed until \
745                 this attempt finishes",
746                self.short()
747            );
748        }
749        self.priority = priority;
750        Ok(())
751    }
752
753    /// Mark (or unmark) this task to interrupt whatever `magi serve` already
754    /// has in flight, once `[daemon] pause_for_interrupts` is on. See
755    /// [`Task::interrupt`].
756    ///
757    /// Setting it is restricted to a task the loop could pick up on its own
758    /// right now - [`TaskStatus::runnable`] - for the same reason as
759    /// [`Task::set_priority`]: a task already `running` has been claimed, and
760    /// a task that is `done`, `held`, or `blocked` is not going to compete
761    /// for the daemon's attention regardless of this flag. Unlike priority,
762    /// this is never silently inert while `running` - it is refused outright,
763    /// because the entire feature this flag drives (`crate::daemon`'s
764    /// interrupt scheduler) is scoped to tasks still waiting to be claimed.
765    /// Clearing it back to `false` carries no such risk and is always
766    /// allowed, including on a task that moved on since it was set.
767    pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
768        if interrupt && !self.status.runnable() {
769            bail!(
770                "task {} is {}; only a queued or failed task can be marked \
771                 to interrupt",
772                self.short(),
773                self.status.as_str()
774            );
775        }
776        self.interrupt = interrupt;
777        Ok(())
778    }
779
780    /// Replace this task's title and instruction wholesale.
781    ///
782    /// Restricted to `queued` and `held`. A `running` task's instruction has
783    /// already been handed to the graph, so a run in flight and the file on
784    /// disk must not be allowed to disagree about what was asked; a `done` or
785    /// `failed` task is a record of what actually happened and editing it
786    /// after the fact would falsify that record. `id`, `created_at`,
787    /// `source`, and `runs` are left untouched on purpose - an edit stands in
788    /// for "delete and refile", and keeping the id, the timestamp, the
789    /// attribution, and the run history is the entire reason it exists
790    /// instead.
791    pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
792        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
793            bail!(
794                "task {} is {}; only a queued or held task's instruction can \
795                 be edited",
796                self.short(),
797                self.status.as_str()
798            );
799        }
800        self.title = title;
801        self.instruction = instruction;
802        Ok(())
803    }
804
805    /// Record a run that produced a pull request without merging it.
806    ///
807    /// The task is held rather than retried, and it costs no further attempt
808    /// either way. The work the task asked for exists: it is sitting on a
809    /// branch, in a pull request, waiting for CI or for a person. Retrying
810    /// would spend the whole competition budget a second time and then race a
811    /// second branch against the pull request the first one opened - which is
812    /// exactly what happened to run 01c2, whose finished and green pull request
813    /// was re-competed from scratch four seconds after it opened.
814    ///
815    /// A pull request nobody merged is a request for a person, not a failure.
816    ///
817    /// Records `why` into [`Task::hold_reason`] as well as
818    /// [`Task::last_error`], so the notification centre and `magi task show`
819    /// say why the task is held rather than "no reason recorded". This is
820    /// also the path a verified no-op with an outstanding `magi ask` question
821    /// settles through - see `daemon::settle` and `daemon::settle_and_diagnose`,
822    /// which append the question id to `hold_reason` when one is still open
823    /// for the run.
824    pub fn handed_off(&mut self, why: impl Into<String>) {
825        let why = why.into();
826        self.diagnostic = None;
827        self.status = TaskStatus::Held;
828        self.hold_source = Some(HoldSource::Machine);
829        self.hold_reason = Some(why.clone());
830        self.last_error = Some(why);
831    }
832
833    /// Put a held or finished task back in line, with its attempt count reset
834    /// so a release is a real second chance rather than an instant re-hold.
835    /// The run history is kept: attempts reset, evidence does not.
836    pub fn release(&mut self) {
837        self.status = TaskStatus::Queued;
838        self.attempts = 0;
839        self.last_error = None;
840        // Otherwise the next person who holds this task reads a reason that
841        // belonged to whatever it was waiting on last time.
842        self.hold_reason = None;
843        self.hold_source = None;
844        self.diagnostic = None;
845        // A release also un-blocks: the dependency or question `blocked_by`
846        // named may still be unresolved, but a human (or `crate::conduct`)
847        // choosing to release the task overrides that wait outright, the same
848        // as it overrides an ordinary hold.
849        self.blocked_by.clear();
850        self.block_reason = None;
851        self.blocked_from = None;
852        self.review_branch = None;
853        self.fresh_start = false;
854    }
855}
856
857/// A queue on disk.
858#[derive(Debug, Clone)]
859pub struct Queue {
860    root: PathBuf,
861}
862
863impl Queue {
864    /// The operator's queue, `<home>/queue`.
865    pub fn open() -> Self {
866        Self::at(crate::run::home().join("queue"))
867    }
868
869    /// A queue at an explicit root. Tests use this; so could an operator who
870    /// wants a queue per project.
871    pub fn at(root: PathBuf) -> Self {
872        Self { root }
873    }
874
875    /// Directory holding the task files.
876    pub fn root(&self) -> &Path {
877        &self.root
878    }
879
880    /// Path for one task id.
881    pub fn path_of(&self, id: &str) -> PathBuf {
882        self.root.join(format!("{id}.json"))
883    }
884
885    /// Write a task, atomically, so a daemon killed mid-write leaves the
886    /// previous state readable rather than a truncated file.
887    pub fn put(&self, task: &mut Task) -> Result<()> {
888        task.updated_at = Timestamp::now();
889        std::fs::create_dir_all(&self.root)
890            .with_context(|| format!("create {}", self.root.display()))?;
891        let body = serde_json::to_string_pretty(task).context("serialize task")?;
892        let path = self.path_of(&task.id);
893        let tmp = path.with_extension("json.tmp");
894        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
895        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
896        // A machine hold is news for the notification centre, filed beside
897        // this queue (`<home>/queue` -> `<home>/notifications`) rather than
898        // through a process-global, so a queue in a temp directory notifies
899        // into that directory.
900        if let (Some(notice), Some(home)) = (
901            crate::notices::task_held(task),
902            self.root.parent().filter(|p| !p.as_os_str().is_empty()),
903        ) {
904            crate::notices::raise_in(home, notice);
905        }
906        Ok(())
907    }
908
909    /// Load a task by id or unambiguous id prefix.
910    pub fn get(&self, id: &str) -> Result<Task> {
911        let resolved = self.resolve_id(id)?;
912        read_path(&self.path_of(&resolved))
913    }
914
915    /// Remove a task, and the claim lock that belongs to it.
916    ///
917    /// `in_flight` comes from the caller — a live daemon's heartbeat naming
918    /// this task — because the task's own `running` status cannot answer the
919    /// question. A daemon killed mid-competition leaves the status at
920    /// `running` and an orphaned `.lock` behind, and a guard that trusted
921    /// either would make the task undeletable for good: the phone showed
922    /// exactly that, refusing a task whose daemon had been gone for an hour.
923    ///
924    /// So the lock is removed with the task rather than respected. Any lock
925    /// still there once no live daemon claims the task is by definition stale,
926    /// and leaving it would make a deleted task look claimed to
927    /// [`Queue::claim`] and to whoever reads the directory.
928    ///
929    /// Anything still `blocked` on the id just deleted is quarantined to a
930    /// machine hold in the same call - see [`Removal::quarantined`] - rather
931    /// than left to wait on a dependency that no longer exists. Best-effort:
932    /// a dependent claimed by something else right now, or one whose write
933    /// fails, is simply left for `crate::daemon::resolve_blockers`'s own poll
934    /// (or `crate::triage::run_once`) to catch on its own next pass, and does
935    /// not fail this removal.
936    ///
937    /// `questions` is the store [`missing_blockers`] checks a `blocked_by` id
938    /// against before calling it gone - the same store the caller already
939    /// resolves `id`'s own home from, passed in rather than reopened here so
940    /// a test queue at an explicit root is never quarantined against the
941    /// operator's real questions directory.
942    pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
943        let resolved = self.resolve_id(id)?;
944        if in_flight {
945            bail!("task {resolved} is being run by a live daemon right now");
946        }
947        let path = self.path_of(&resolved);
948        std::fs::remove_file(&path).with_context(|| format!("remove {}", path.display()))?;
949        let lock = self.lock_path(&resolved);
950        if let Err(e) = std::fs::remove_file(&lock) {
951            if e.kind() != std::io::ErrorKind::NotFound {
952                return Err(e).with_context(|| format!("remove {}", lock.display()));
953            }
954        }
955        let quarantined = self.quarantine_dependents_of(&resolved, questions);
956        Ok(Removal {
957            id: resolved,
958            quarantined,
959        })
960    }
961
962    /// Move every `blocked` task naming `dependency` in its own `blocked_by`
963    /// to a machine hold, now that `dependency`'s own file is gone. See
964    /// [`Queue::remove`]'s own doc for why this is best-effort.
965    fn quarantine_dependents_of(&self, dependency: &str, questions: &Questions) -> Vec<String> {
966        let mut quarantined = Vec::new();
967        for listed in self.list() {
968            if listed.status != TaskStatus::Blocked
969                || !listed.blocked_by.iter().any(|b| b == dependency)
970            {
971                continue;
972            }
973            let Ok(_claim) = self.claim(&listed.id) else {
974                continue;
975            };
976            let Ok(mut task) = self.get(&listed.id) else {
977                continue;
978            };
979            if task.status != TaskStatus::Blocked
980                || !task.blocked_by.iter().any(|b| b == dependency)
981            {
982                continue;
983            }
984            let missing = missing_blockers(self, questions, &task.blocked_by);
985            task.hold_machine(Some(missing_blocker_hold_reason(
986                &task.blocked_by,
987                &missing,
988            )));
989            if self.put(&mut task).is_ok() {
990                quarantined.push(task.id.clone());
991            }
992        }
993        quarantined
994    }
995
996    /// Path of the claim lock for a task. One definition, so `claim` and
997    /// `remove` cannot end up naming different files.
998    fn lock_path(&self, id: &str) -> PathBuf {
999        self.root.join(format!("{id}.lock"))
1000    }
1001
1002    /// Every task on disk, highest priority first and newest first within a
1003    /// priority. This is what `magi task list` and `GET /api/queue` print, so
1004    /// a raised priority has to move a task here the moment it is saved, not
1005    /// only in [`Queue::next_runnable`]'s own ordering - the operator reading
1006    /// the backlog and the loop about to drain it must agree on what "first"
1007    /// means. Every existing task defaults to priority 0, so this is a no-op
1008    /// change from the old newest-first order for a queue nobody has
1009    /// reprioritised.
1010    ///
1011    /// Unreadable files are skipped rather than fatal: one corrupt task must
1012    /// not take the queue - or the web UI, or an unattended daemon - down
1013    /// with it.
1014    pub fn list(&self) -> Vec<Task> {
1015        let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
1016            .into_iter()
1017            .flatten()
1018            .flatten()
1019            .map(|e| e.path())
1020            .filter(|p| p.extension().is_some_and(|x| x == "json"))
1021            .filter_map(|p| read_path(&p).ok())
1022            .collect();
1023        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
1024        tasks
1025    }
1026
1027    /// Runs that a later attempt at the same task replaced, mapped to the id
1028    /// of the attempt that replaced them.
1029    ///
1030    /// A task keeps its attempts in order, and the deck showed them as two
1031    /// cards with the same title and no hint which was which: yukimemi asked
1032    /// why `stalled` and `blocked` appeared twice for one task, and the
1033    /// answer - "those are two tries, and the second one exists because of a
1034    /// bug since fixed" - was not on the screen anywhere.
1035    ///
1036    /// Read from the queue rather than stored on the run, because the
1037    /// ordering is the queue's fact: a `RunState` has no idea another attempt
1038    /// happened after it.
1039    pub fn superseded(&self) -> HashMap<String, String> {
1040        let mut by = HashMap::new();
1041        for task in self.list() {
1042            for pair in task.runs.windows(2) {
1043                if let [earlier, later] = pair {
1044                    by.insert(earlier.clone(), later.clone());
1045                }
1046            }
1047        }
1048        by
1049    }
1050
1051    /// Whether `run` is an earlier attempt a later one replaced, and if so
1052    /// the id of that later attempt.
1053    ///
1054    /// Same walk as [`Queue::superseded`], narrowed to one run: a run detail
1055    /// page asks about exactly one run at a time, and this keeps that call
1056    /// site from building (and discarding) the whole map's `HashMap` just to
1057    /// read one entry out of it.
1058    pub fn superseded_by(&self, run: &str) -> Option<String> {
1059        for task in self.list() {
1060            if let Some(pos) = task.runs.iter().position(|r| r == run) {
1061                return task.runs.get(pos + 1).cloned();
1062            }
1063        }
1064        None
1065    }
1066
1067    /// The task's own most recent attempt, when `run` belongs to that task
1068    /// but is not already that attempt.
1069    ///
1070    /// Distinct from [`Queue::superseded_by`], which names only the very
1071    /// next attempt: a chain of retries (A superseded by B superseded by C)
1072    /// leaves an older run pointing at an intermediate one that may itself
1073    /// be unresolved, and a run's own detail page needs to know where the
1074    /// task's story currently stands - the chain's current head, C - not an
1075    /// attempt in the middle of it that a client would otherwise have to
1076    /// walk to by hand.
1077    pub fn latest_attempt(&self, run: &str) -> Option<String> {
1078        for task in self.list() {
1079            if task.runs.iter().any(|r| r == run) {
1080                return task.runs.last().filter(|last| **last != run).cloned();
1081            }
1082        }
1083        None
1084    }
1085
1086    /// The task a daemon should run next, or `None` when the queue is idle.
1087    ///
1088    /// Highest priority first, oldest first within a priority, so a burst of
1089    /// agent-filed work cannot starve the task a human filed this morning.
1090    pub fn next_runnable(&self) -> Option<Task> {
1091        let mut runnable: Vec<Task> = self
1092            .list()
1093            .into_iter()
1094            .filter(|t| t.status.runnable())
1095            .collect();
1096        runnable.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)));
1097        runnable.into_iter().next()
1098    }
1099
1100    /// Take exclusive ownership of a task.
1101    ///
1102    /// The lock is a `create_new` file next to the task, which is atomic on
1103    /// every platform magi targets. It exists so two daemons - or a daemon and
1104    /// a human running `magi run` - cannot drive one task into two competing
1105    /// runs. The returned guard releases on drop, including on panic.
1106    pub fn claim(&self, id: &str) -> Result<Claim> {
1107        std::fs::create_dir_all(&self.root)
1108            .with_context(|| format!("create {}", self.root.display()))?;
1109        let path = self.lock_path(id);
1110        match std::fs::OpenOptions::new()
1111            .write(true)
1112            .create_new(true)
1113            .open(&path)
1114        {
1115            Ok(mut f) => {
1116                use std::io::Write as _;
1117                // Best effort: the pid is for the human looking at a stale lock.
1118                let _ = writeln!(f, "{}", std::process::id());
1119                Ok(Claim { path })
1120            }
1121            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
1122                bail!("task {id} is already claimed ({} exists)", path.display())
1123            }
1124            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
1125        }
1126    }
1127
1128    /// Expand an id prefix to exactly one task id.
1129    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
1130        if self.path_of(prefix).is_file() {
1131            return Ok(prefix.to_owned());
1132        }
1133        let hits: Vec<String> = self
1134            .list()
1135            .into_iter()
1136            .map(|t| t.id)
1137            .filter(|id| id.starts_with(prefix) || id.ends_with(prefix))
1138            .collect();
1139        match hits.len() {
1140            1 => Ok(hits.into_iter().next().expect("exactly one hit")),
1141            0 => bail!("no task matches `{prefix}`"),
1142            _ => bail!(
1143                "`{prefix}` matches {} tasks: {}",
1144                hits.len(),
1145                hits.join(", ")
1146            ),
1147        }
1148    }
1149
1150    /// Change detection token for the queue.
1151    ///
1152    /// Combines file names and modification times of all task files in the
1153    /// queue, so adding, modifying, or deleting any task — even an older one —
1154    /// moves the revision and notifies connected clients via the change stream.
1155    /// Returns 0 when the queue is completely empty.
1156    pub fn revision(&self) -> u64 {
1157        use std::hash::{Hash as _, Hasher as _};
1158
1159        let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
1160            .into_iter()
1161            .flatten()
1162            .flatten()
1163            .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
1164            .filter_map(|e| {
1165                let name = e.file_name().to_string_lossy().into_owned();
1166                let mtime = e
1167                    .metadata()
1168                    .ok()?
1169                    .modified()
1170                    .ok()?
1171                    .duration_since(std::time::UNIX_EPOCH)
1172                    .ok()?
1173                    .as_millis() as u64;
1174                Some((name, mtime))
1175            })
1176            .collect();
1177
1178        if entries.is_empty() {
1179            return 0;
1180        }
1181
1182        entries.sort_unstable();
1183        let mut hasher = std::hash::DefaultHasher::new();
1184        for (name, mtime) in &entries {
1185            name.hash(&mut hasher);
1186            mtime.hash(&mut hasher);
1187        }
1188        let h = hasher.finish();
1189        if h == 0 { 1 } else { h }
1190    }
1191}
1192
1193/// What [`Queue::remove`] did, beyond deleting the named task's own file.
1194#[derive(Debug, Clone)]
1195pub struct Removal {
1196    /// The id actually removed - `id` expanded from a prefix, if it was one.
1197    pub id: String,
1198    /// Every `blocked` task that named [`Removal::id`] in its own
1199    /// `blocked_by` and was moved to a machine hold as a result, rather than
1200    /// left waiting on a dependency this call just erased.
1201    pub quarantined: Vec<String>,
1202}
1203
1204/// Exclusive ownership of a task, released on drop.
1205#[derive(Debug)]
1206pub struct Claim {
1207    path: PathBuf,
1208}
1209
1210impl Drop for Claim {
1211    fn drop(&mut self) {
1212        let _ = std::fs::remove_file(&self.path);
1213    }
1214}
1215
1216/// The first line of a task, trimmed to a title. Used when the caller gives a
1217/// body but no title, which is the normal case for an agent piping a file in.
1218pub fn title_from(instruction: &str, max: usize) -> String {
1219    // The first non-blank line, whatever it is. A markdown heading is the
1220    // task's own summary - agents pipe in `# Rework the config loader` and mean
1221    // exactly that - so it is preferred over the prose beneath it rather than
1222    // skipped as decoration. Leading list and heading markers are stripped
1223    // because they are syntax, not words.
1224    let line = instruction
1225        .lines()
1226        .map(str::trim)
1227        .find(|l| !l.is_empty())
1228        .unwrap_or("(empty task)")
1229        .trim_start_matches(['#', '-', '*', '>', ' '])
1230        .trim();
1231    if line.is_empty() {
1232        return "(empty task)".to_owned();
1233    }
1234    if line.chars().count() <= max {
1235        return line.to_owned();
1236    }
1237    let head: String = line.chars().take(max.saturating_sub(1)).collect();
1238    format!("{head}…")
1239}
1240
1241fn read_path(path: &Path) -> Result<Task> {
1242    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
1243    let task: Task =
1244        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
1245    // Greater-than, not not-equal: every field added since schema 1 carries
1246    // `#[serde(default)]`, so an older task has nothing to say about it and
1247    // defaulting is exactly as good a reading as a value that build never had
1248    // a chance to write. Only a schema *ahead* of this build - a meaning it
1249    // cannot possibly know - is refused rather than guessed at.
1250    if task.schema > SCHEMA {
1251        bail!(
1252            "task {} was written by a different magi (schema {}, this build \
1253             speaks {SCHEMA})",
1254            task.id,
1255            task.schema
1256        );
1257    }
1258    Ok(task)
1259}
1260
1261/// Ids inside a `blocked_by` list that name neither an existing task file nor
1262/// an existing question file - a dependency deleted (`magi task rm`, or by
1263/// hand) while something was still waiting on it.
1264///
1265/// Existence is decided by [`Queue::path_of`]/[`Questions::path_of`]
1266/// `is_file()` alone, never by [`Queue::get`]/[`Questions::get`] succeeding:
1267/// those also fail on a merely unreadable file - mid-write, corrupt, or from
1268/// a schema ahead of this build (see [`read_path`]) - and misreading "cannot
1269/// read it right now" as "it was deleted" would quarantine a task over a
1270/// transient failure. `blocked_by` always carries a full id, written by
1271/// `crate::conduct` or `crate::triage` from a real task's or question's own
1272/// `id`/`short`, never a prefix a caller typed - so the exact-path check is
1273/// complete on its own, with no [`Queue::resolve_id`] fallback needed.
1274pub fn missing_blockers(
1275    queue: &Queue,
1276    questions: &Questions,
1277    blocked_by: &[String],
1278) -> Vec<String> {
1279    blocked_by
1280        .iter()
1281        .filter(|id| !queue.path_of(id).is_file() && !questions.path_of(id).is_file())
1282        .cloned()
1283        .collect()
1284}
1285
1286/// The `hold_reason` text for a task quarantined because one or more of its
1287/// `blocked_by` ids no longer exist. Shared by `crate::daemon::resolve_blockers`,
1288/// `crate::triage::run_once`, and [`Queue::remove`]'s own dependent
1289/// quarantine, so the three call sites read as the same event to an operator
1290/// looking at `magi task show` rather than three different wordings for it.
1291///
1292/// Names the full original `blocked_by` list, not just `missing` - a task
1293/// quarantined here can also have named a dependency that was still
1294/// perfectly valid, and [`Task::hold_machine`] clears `blocked_by` on the way
1295/// in, so this text is the only place that information survives for an
1296/// operator deciding whether to release the task outright.
1297pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
1298    format!(
1299        "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
1300        blocked_by.join(", "),
1301        missing.join(", "),
1302    )
1303}
1304
1305fn short(id: &str) -> &str {
1306    id.split('-').next_back().unwrap_or(id)
1307}
1308
1309fn new_id() -> String {
1310    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
1311    let seed = crate::rng::entropy();
1312    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
1313}
1314
1315#[cfg(test)]
1316mod tests {
1317    use super::*;
1318
1319    #[test]
1320    fn triage_applied_survives_release_and_old_records_read_as_empty() {
1321        let mut t = Task::new(
1322            "t".to_owned(),
1323            "i".to_owned(),
1324            PathBuf::from("r"),
1325            Source::Human,
1326        );
1327        t.mark_triage_applied("q1");
1328        t.mark_triage_applied("q1");
1329        t.hold_machine(Some("x".to_owned()));
1330        t.release();
1331        assert_eq!(t.triage_applied, ["q1"]);
1332        assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
1333
1334        let mut v = serde_json::to_value(&t).unwrap();
1335        v.as_object_mut().unwrap().remove("triage_applied");
1336        let old: Task = serde_json::from_value(v).unwrap();
1337        assert!(old.triage_applied.is_empty());
1338    }
1339
1340    #[test]
1341    fn task_counts_of_empty_is_all_zero() {
1342        assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
1343    }
1344
1345    #[test]
1346    fn task_counts_of_tallies_every_status() {
1347        let mut queued = Task::new(
1348            "q".to_owned(),
1349            "i".to_owned(),
1350            PathBuf::from("."),
1351            Source::Human,
1352        );
1353        queued.status = TaskStatus::Queued;
1354        let mut running = queued.clone();
1355        running.status = TaskStatus::Running;
1356        let mut done = queued.clone();
1357        done.status = TaskStatus::Done;
1358        let mut failed = queued.clone();
1359        failed.status = TaskStatus::Failed;
1360        let mut held = queued.clone();
1361        held.status = TaskStatus::Held;
1362        let mut blocked = queued.clone();
1363        blocked.status = TaskStatus::Blocked;
1364
1365        let counts = TaskCounts::of(&[queued, running, done.clone(), done, failed, held, blocked]);
1366        assert_eq!(
1367            counts,
1368            TaskCounts {
1369                queued: 1,
1370                running: 1,
1371                done: 2,
1372                failed: 1,
1373                held: 1,
1374                blocked: 1,
1375            }
1376        );
1377    }
1378
1379    /// A queue of its own, with no process-global state - which is the point of
1380    /// `Queue::at`, and why these can run in parallel.
1381    fn queue() -> (tempfile::TempDir, Queue) {
1382        let dir = tempfile::tempdir().unwrap();
1383        let q = Queue::at(dir.path().join("queue"));
1384        (dir, q)
1385    }
1386
1387    #[test]
1388    fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
1389        let dir = tempfile::tempdir().unwrap();
1390        let q = Queue::at(dir.path().join("queue"));
1391        let mut t = task("held");
1392        q.put(&mut t).unwrap();
1393        assert_eq!(
1394            crate::notices::Notices::at(dir.path().join("notifications"))
1395                .list()
1396                .len(),
1397            0
1398        );
1399        t.hold_machine(Some("out of attempts".to_owned()));
1400        q.put(&mut t).unwrap();
1401        let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
1402        assert_eq!(listed.len(), 1);
1403        assert!(listed[0].message.contains("out of attempts"));
1404    }
1405
1406    fn task(title: &str) -> Task {
1407        Task::new(
1408            title.to_owned(),
1409            format!("do {title}"),
1410            PathBuf::from("."),
1411            Source::Human,
1412        )
1413    }
1414
1415    #[test]
1416    fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
1417        let (_dir, q) = queue();
1418        let mut t = task("retried");
1419        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
1420        q.put(&mut t).unwrap();
1421
1422        assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
1423        assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
1424        assert_eq!(
1425            q.superseded_by("cccc"),
1426            None,
1427            "the latest attempt replaces nothing"
1428        );
1429        assert_eq!(
1430            q.superseded_by("never-heard-of-it"),
1431            None,
1432            "a run belonging to no task on this queue is not superseded"
1433        );
1434
1435        let mut by = HashMap::new();
1436        by.insert("aaaa".to_owned(), "bbbb".to_owned());
1437        by.insert("bbbb".to_owned(), "cccc".to_owned());
1438        assert_eq!(
1439            q.superseded(),
1440            by,
1441            "the whole-map and single-run forms must agree"
1442        );
1443    }
1444
1445    #[test]
1446    fn superseded_attempts_is_empty_until_the_task_is_done() {
1447        let mut t = task("retried");
1448        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
1449        t.status = TaskStatus::Failed;
1450        assert_eq!(
1451            t.superseded_attempts(true),
1452            &[] as &[String],
1453            "a task still retrying has no attempt yet that a later one made moot"
1454        );
1455
1456        t.status = TaskStatus::Running;
1457        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
1458    }
1459
1460    #[test]
1461    fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
1462        let mut t = task("retried");
1463        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
1464        t.status = TaskStatus::Done;
1465        assert_eq!(
1466            t.superseded_attempts(true),
1467            &["aaaa".to_owned(), "bbbb".to_owned()],
1468            "cccc is the attempt whose success made the task done, and stays out"
1469        );
1470    }
1471
1472    #[test]
1473    fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
1474        let mut t = task("first try landed");
1475        t.runs = vec!["aaaa".to_owned()];
1476        t.status = TaskStatus::Done;
1477        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
1478    }
1479
1480    #[test]
1481    fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
1482        // `succeed` is reachable directly - `magi task done`, its web
1483        // equivalent, and the conductor's `Recovery::Done` - on a task in
1484        // any status, including one whose last recorded attempt is itself
1485        // `Blocked`/`Failed`/anything but `Merged`/`Ready`. `runs.last()`
1486        // alone cannot tell that apart from the loop's own settle path, so
1487        // the caller's own read of that run's status is what decides this.
1488        let mut t = task("closed by hand after a manual merge");
1489        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
1490        t.status = TaskStatus::Done;
1491        assert_eq!(
1492            t.superseded_attempts(false),
1493            &[] as &[String],
1494            "nothing here is provably why the task is done, so nothing is superseded"
1495        );
1496    }
1497
1498    #[test]
1499    fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
1500        let (_dir, q) = queue();
1501        let mut t = task("retried twice");
1502        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
1503        q.put(&mut t).unwrap();
1504
1505        assert_eq!(
1506            q.latest_attempt("aaaa"),
1507            Some("cccc".to_owned()),
1508            "an old attempt points straight at the chain's current head, not the \
1509             next attempt in the middle of it"
1510        );
1511        assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
1512        assert_eq!(
1513            q.latest_attempt("cccc"),
1514            None,
1515            "the latest attempt is not superseded by anything"
1516        );
1517        assert_eq!(
1518            q.latest_attempt("never-heard-of-it"),
1519            None,
1520            "a run belonging to no task on this queue is not superseded"
1521        );
1522    }
1523
1524    #[test]
1525    fn a_markdown_heading_is_the_title_not_decoration() {
1526        // A task file's heading is the summary its author already wrote, so it
1527        // beats the prose underneath. Getting this backwards was visible in the
1528        // first smoke test: a task titled "# Rework the config loader" listed
1529        // as "It re-reads the file on every lookup".
1530        assert_eq!(
1531            title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
1532            "Rework the config loader"
1533        );
1534        assert_eq!(title_from("- fix the thing", 40), "fix the thing");
1535        assert_eq!(title_from("> quoted task", 40), "quoted task");
1536        // Nothing usable at all still has to produce something printable.
1537        assert_eq!(title_from("   \n\n", 40), "(empty task)");
1538        assert_eq!(title_from("###\n", 40), "(empty task)");
1539    }
1540
1541    #[test]
1542    fn a_long_title_is_elided_by_characters_not_bytes() {
1543        // Byte truncation would split a multi-byte character and panic.
1544        let long = "課題".repeat(30);
1545        let title = title_from(&long, 10);
1546        assert_eq!(title.chars().count(), 10);
1547        assert!(title.ends_with('…'));
1548    }
1549
1550    #[test]
1551    fn priority_wins_and_ties_break_oldest_first() {
1552        let (_dir, q) = queue();
1553        let mut a = task("first");
1554        let mut b = task("second");
1555        let mut c = task("urgent");
1556        // Ids carry a timestamp, so force a known order.
1557        a.id = "20260101-000001-aaaa".to_owned();
1558        b.id = "20260101-000002-bbbb".to_owned();
1559        c.id = "20260101-000003-cccc".to_owned();
1560        c.priority = 5;
1561        for t in [&mut a, &mut b, &mut c] {
1562            q.put(t).unwrap();
1563        }
1564
1565        // Priority first...
1566        assert_eq!(q.next_runnable().unwrap().id, c.id);
1567        c.hold_machine(None);
1568        q.put(&mut c).unwrap();
1569        // ...then oldest, so a burst of new work cannot starve older work.
1570        assert_eq!(q.next_runnable().unwrap().id, a.id);
1571        assert_eq!(q.list().len(), 3, "b is still waiting its turn");
1572    }
1573
1574    #[test]
1575    fn a_blocked_task_never_starves_another_runnable_one() {
1576        let (_dir, q) = queue();
1577        let mut blocked = task("blocked");
1578        blocked.block(vec!["something".to_owned()], None);
1579        q.put(&mut blocked).unwrap();
1580
1581        let mut runnable = task("free to go");
1582        q.put(&mut runnable).unwrap();
1583
1584        let next = q.next_runnable().expect("a runnable task is still offered");
1585        assert_eq!(next.id, runnable.id);
1586    }
1587
1588    #[test]
1589    fn a_held_task_is_never_offered_to_the_loop() {
1590        let (_dir, q) = queue();
1591        let mut t = task("held");
1592        q.put(&mut t).unwrap();
1593        assert!(q.next_runnable().is_some());
1594
1595        t.hold_machine(None);
1596        q.put(&mut t).unwrap();
1597        assert!(
1598            q.next_runnable().is_none(),
1599            "a held task must wait for a human"
1600        );
1601
1602        // A failed task, by contrast, is exactly what the loop should retry.
1603        t.status = TaskStatus::Failed;
1604        q.put(&mut t).unwrap();
1605        assert!(q.next_runnable().is_some());
1606    }
1607
1608    #[test]
1609    fn attempts_are_capped_and_then_the_task_is_held() {
1610        let mut t = task("doomed");
1611
1612        t.start("run-1".to_owned());
1613        t.fail("gate red", 2);
1614        assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
1615
1616        t.start("run-2".to_owned());
1617        t.fail("gate red", 2);
1618        assert_eq!(
1619            t.status,
1620            TaskStatus::Held,
1621            "out of attempts: stop spending money on it"
1622        );
1623        assert_eq!(t.runs, ["run-1", "run-2"]);
1624        assert_eq!(t.last_error.as_deref(), Some("gate red"));
1625        assert_eq!(
1626            t.hold_reason.as_deref(),
1627            Some("gate red"),
1628            "the hold must say why, not leave hold_reason null next to a \
1629             populated last_error"
1630        );
1631    }
1632
1633    #[test]
1634    fn handing_off_a_task_records_a_hold_reason_too() {
1635        let mut t = task("left a pull request");
1636        t.start("run-1".to_owned());
1637        t.handed_off("run ended with a pull request open [run run-1]");
1638        assert_eq!(t.status, TaskStatus::Held);
1639        assert_eq!(t.hold_source, Some(HoldSource::Machine));
1640        assert_eq!(
1641            t.hold_reason.as_deref(),
1642            Some("run ended with a pull request open [run run-1]")
1643        );
1644        assert_eq!(t.hold_reason, t.last_error);
1645    }
1646
1647    #[test]
1648    fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
1649        let mut t = task("stalled by quota");
1650
1651        t.start("run-1".to_owned());
1652        assert_eq!(t.attempts, 1);
1653        t.stall("judge-1, judge-2 out of quota");
1654        assert_eq!(
1655            t.attempts, 0,
1656            "a closed quota window must not spend the task's retry budget"
1657        );
1658        assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
1659        assert_eq!(
1660            t.last_error.as_deref(),
1661            Some("judge-1, judge-2 out of quota")
1662        );
1663
1664        // A task can therefore stall all night and still get its real attempts
1665        // once the quota resets - which is the whole point.
1666        for _ in 0..20 {
1667            t.start("run-n".to_owned());
1668            t.stall("still out of quota");
1669        }
1670        t.start("run-real".to_owned());
1671        t.fail("gate red", 2);
1672        assert_eq!(
1673            t.status,
1674            TaskStatus::Failed,
1675            "the first attempt that was really judged is attempt one"
1676        );
1677    }
1678
1679    #[test]
1680    fn releasing_a_held_task_gives_it_a_real_second_chance() {
1681        let mut t = task("retry me");
1682        t.start("run-1".to_owned());
1683        t.fail("gate red", 1);
1684        assert_eq!(t.status, TaskStatus::Held);
1685
1686        t.release();
1687        assert_eq!(t.status, TaskStatus::Queued);
1688        // Without resetting attempts the next failure would re-hold at once,
1689        // and a release would be a no-op the operator cannot see.
1690        assert_eq!(t.attempts, 0);
1691        assert!(t.last_error.is_none());
1692        assert_eq!(
1693            t.runs.len(),
1694            1,
1695            "history is kept: attempts reset, evidence does not"
1696        );
1697    }
1698
1699    #[test]
1700    fn a_hold_reason_survives_and_a_release_clears_it() {
1701        let mut t = task("waiting on something else");
1702        t.hold_manual(Some(
1703            "waiting for 20260101-000000-aaaa to land first".to_owned(),
1704        ));
1705        assert_eq!(t.status, TaskStatus::Held);
1706        assert_eq!(
1707            t.hold_reason.as_deref(),
1708            Some("waiting for 20260101-000000-aaaa to land first")
1709        );
1710
1711        // Holding again with no reason must not erase the one already there.
1712        t.hold_manual(None);
1713        assert_eq!(
1714            t.hold_reason.as_deref(),
1715            Some("waiting for 20260101-000000-aaaa to land first"),
1716            "a bare re-hold keeps whatever a human already wrote down"
1717        );
1718
1719        // A hold with no reason at all is still an ordinary, allowed hold.
1720        let mut plain = task("no reason given");
1721        plain.hold_manual(None);
1722        assert_eq!(plain.status, TaskStatus::Held);
1723        assert!(plain.hold_reason.is_none());
1724
1725        t.release();
1726        assert_eq!(t.status, TaskStatus::Queued);
1727        assert!(
1728            t.hold_reason.is_none(),
1729            "a stale reason must not greet the next person who holds this task"
1730        );
1731    }
1732
1733    #[test]
1734    fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
1735        // `done` can close a held task directly - neither `magi task done`
1736        // nor `POST /api/queue/{id}/done` requires a release first - so a
1737        // task held for "waiting on 3ed9" and then closed without ever being
1738        // released must not still read as waiting on it afterwards.
1739        let mut t = task("landed by hand while held");
1740        t.hold_manual(Some("waiting on 3ed9".to_owned()));
1741        assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
1742
1743        t.succeed();
1744        assert_eq!(t.status, TaskStatus::Done);
1745        assert!(
1746            t.hold_reason.is_none(),
1747            "a done task cannot still be waiting on something"
1748        );
1749    }
1750
1751    #[test]
1752    fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
1753        // The web UI's "Hold" and "Mark done" buttons are both reachable on a
1754        // `blocked` task, not just on `queued`/`held` ones - neither requires
1755        // a release first. A task moved off `Blocked` that way must not still
1756        // carry the dependency it was waiting on: a dependency graph built
1757        // from `blocked_by` would otherwise keep drawing an edge for a task
1758        // that is not blocked on anything any more.
1759        let mut held = task("held straight out of blocked");
1760        held.block(
1761            vec!["20260101-000000-dead".to_owned()],
1762            Some("waiting on the migration script".to_owned()),
1763        );
1764        assert_eq!(held.status, TaskStatus::Blocked);
1765
1766        held.hold_manual(None);
1767        assert_eq!(held.status, TaskStatus::Held);
1768        assert!(
1769            held.blocked_by.is_empty(),
1770            "hold overrides the wait, same as release"
1771        );
1772        assert!(held.block_reason.is_none());
1773
1774        let mut done = task("closed straight out of blocked");
1775        done.block(
1776            vec!["20260101-000000-dead".to_owned()],
1777            Some("waiting on the migration script".to_owned()),
1778        );
1779        done.succeed();
1780        assert_eq!(done.status, TaskStatus::Done);
1781        assert!(
1782            done.blocked_by.is_empty(),
1783            "a done task cannot still be waiting on a dependency"
1784        );
1785        assert!(done.block_reason.is_none());
1786    }
1787
1788    #[test]
1789    fn a_blocked_task_is_never_offered_to_the_loop() {
1790        let mut t = task("blocked");
1791        assert!(t.status.runnable());
1792        t.block(
1793            vec!["dep-id".to_owned()],
1794            Some("waits on dep-id".to_owned()),
1795        );
1796        assert_eq!(t.status, TaskStatus::Blocked);
1797        assert!(!t.status.runnable());
1798        assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
1799    }
1800
1801    #[test]
1802    fn unblocking_the_last_dependency_returns_the_task_to_queued() {
1803        let mut t = task("blocked on two");
1804        t.block(
1805            vec!["a".to_owned(), "b".to_owned()],
1806            Some("waits on a and b".to_owned()),
1807        );
1808
1809        t.unblock("a");
1810        assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
1811        assert_eq!(t.blocked_by, ["b"]);
1812
1813        t.unblock("b");
1814        assert_eq!(t.status, TaskStatus::Queued);
1815        assert!(t.blocked_by.is_empty());
1816        assert!(t.block_reason.is_none());
1817    }
1818
1819    #[test]
1820    fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
1821        let mut t = task("never blocked");
1822        t.unblock("whatever");
1823        assert_eq!(t.status, TaskStatus::Queued);
1824    }
1825
1826    #[test]
1827    fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
1828        // The bug this guards: a task an operator (or `crate::triage`) has
1829        // deliberately held, once `crate::conduct` blocks it on a follow-up
1830        // question, must not silently re-enter the competition queue the
1831        // moment that question is answered - whatever the answer said.
1832        let mut t = task("held, then asked about");
1833        t.hold_machine(Some("out of attempts".to_owned()));
1834        assert_eq!(t.status, TaskStatus::Held);
1835
1836        t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
1837        assert_eq!(t.status, TaskStatus::Blocked);
1838
1839        t.record_answer("what now?".to_owned(), "leave it held".to_owned());
1840        t.unblock("q1");
1841        assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
1842        assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
1843        assert_eq!(t.hold_source, Some(HoldSource::Machine));
1844        assert!(t.blocked_from.is_none(), "consumed once restored");
1845    }
1846
1847    #[test]
1848    fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
1849        let mut t = task("manually held, then asked about");
1850        t.hold_manual(Some("waiting on a dependency".to_owned()));
1851
1852        t.block(vec!["q1".to_owned()], None);
1853        t.unblock("q1");
1854
1855        assert_eq!(t.status, TaskStatus::Held);
1856        assert_eq!(t.hold_source, Some(HoldSource::Manual));
1857    }
1858
1859    #[test]
1860    fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
1861        // A second `Task::block` call - `crate::conduct` adding a question on
1862        // top of an existing block - must not overwrite `blocked_from` with
1863        // `Blocked` itself, or the task would restore into itself.
1864        let mut t = task("held, blocked twice");
1865        t.hold_machine(None);
1866        t.block(vec!["q1".to_owned()], Some("first".to_owned()));
1867        t.block(
1868            vec!["q1".to_owned(), "q2".to_owned()],
1869            Some("second".to_owned()),
1870        );
1871
1872        t.unblock("q1");
1873        assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
1874        t.unblock("q2");
1875        assert_eq!(t.status, TaskStatus::Held);
1876    }
1877
1878    #[test]
1879    fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
1880        // Whatever process was driving the run is gone by the time a
1881        // conductor's question about it gets answered - there is nothing left
1882        // to resume into.
1883        let mut t = task("blocked mid-run");
1884        t.start("run-1".to_owned());
1885        assert_eq!(t.status, TaskStatus::Running);
1886
1887        t.block(vec!["q1".to_owned()], None);
1888        t.unblock("q1");
1889        assert_eq!(t.status, TaskStatus::Queued);
1890    }
1891
1892    #[test]
1893    fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
1894        // `blocked_from` is `None` for a record written before schema 4 (or,
1895        // equivalently, deserialized straight from an on-disk file that never
1896        // had the field). Held evidence surviving on the task - never cleared
1897        // by `block` - is the only way left to tell such a record apart from
1898        // one blocked straight out of `Queued`.
1899        let mut t = task("legacy record, held before it was blocked");
1900        t.hold_source = Some(HoldSource::Machine);
1901        t.hold_reason = Some("legacy hold reason".to_owned());
1902        t.status = TaskStatus::Blocked;
1903        t.blocked_by = vec!["q1".to_owned()];
1904        t.blocked_from = None;
1905
1906        t.unblock("q1");
1907        assert_eq!(t.status, TaskStatus::Held);
1908    }
1909
1910    #[test]
1911    fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
1912        let mut t = task("legacy record, ordinary dependency block");
1913        t.status = TaskStatus::Blocked;
1914        t.blocked_by = vec!["dep".to_owned()];
1915        t.blocked_from = None;
1916
1917        t.unblock("dep");
1918        assert_eq!(t.status, TaskStatus::Queued);
1919    }
1920
1921    #[test]
1922    fn answering_a_question_is_recorded_and_survives_a_release() {
1923        let mut t = task("asked something");
1924        t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
1925        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
1926        t.unblock("q1");
1927        assert_eq!(t.status, TaskStatus::Queued);
1928        assert_eq!(t.answers.len(), 1);
1929        assert_eq!(t.answers[0].answer, "SQLite");
1930
1931        // A release resets attempts, not evidence - the same rule
1932        // `releasing_a_held_task_gives_it_a_real_second_chance` asserts for
1933        // `runs`.
1934        t.release();
1935        assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
1936    }
1937
1938    #[test]
1939    fn requesting_review_requeues_the_task_and_remembers_the_branch() {
1940        let mut t = task("blocked run with a surviving branch");
1941        t.start("run-1".to_owned());
1942        t.fail("blocked with major findings", 5);
1943        assert_eq!(t.status, TaskStatus::Failed);
1944
1945        t.request_review("magi/eba2/A".to_owned());
1946        assert_eq!(t.status, TaskStatus::Queued);
1947        assert_eq!(t.attempts, 0);
1948        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
1949
1950        // An ordinary release (a human overriding the choice) drops it again.
1951        t.release();
1952        assert!(t.review_branch.is_none());
1953    }
1954
1955    #[test]
1956    fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
1957        let mut t = task("retry");
1958        t.start("run-1".to_owned());
1959        t.requeue();
1960        assert!(t.fresh_start);
1961
1962        t.release();
1963        assert!(!t.fresh_start);
1964    }
1965
1966    #[test]
1967    fn priority_can_be_changed_while_queued_but_not_while_running() {
1968        let mut t = task("reprioritise me");
1969        t.set_priority(5).unwrap();
1970        assert_eq!(t.priority, 5);
1971
1972        t.start("run-1".to_owned());
1973        let err = t.set_priority(9).unwrap_err().to_string();
1974        assert!(err.contains("running"), "{err}");
1975        assert_eq!(t.priority, 5, "the rejected write must not partially apply");
1976    }
1977
1978    #[test]
1979    fn interrupt_can_be_marked_while_queued_but_not_while_running() {
1980        let mut t = task("interrupt me");
1981        assert!(!t.interrupt, "off unless asked, same as any other task");
1982
1983        t.set_interrupt(true).unwrap();
1984        assert!(t.interrupt);
1985
1986        t.start("run-1".to_owned());
1987        assert!(
1988            !t.interrupt,
1989            "the mark is one-shot: dispatching the task fulfils it, \
1990             whatever the run that follows ends up doing"
1991        );
1992        let err = t.set_interrupt(true).unwrap_err().to_string();
1993        assert!(err.contains("running"), "{err}");
1994        // Clearing is always allowed, even on a running task - there is
1995        // nothing left for it to interrupt once it has been claimed.
1996        t.set_interrupt(false).unwrap();
1997        assert!(!t.interrupt);
1998    }
1999
2000    /// R2-1-1: a task whose run fails and requeues must not go on
2001    /// re-triggering `crate::daemon`'s interrupt scheduler on every later
2002    /// boundary, attempt after attempt, until it exhausts its budget.
2003    #[test]
2004    fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
2005        let mut t = task("interrupt me");
2006        t.set_interrupt(true).unwrap();
2007        t.start("run-1".to_owned());
2008        t.fail("mock failure", 5);
2009        assert_eq!(t.status, TaskStatus::Failed);
2010        assert!(
2011            !t.interrupt,
2012            "one attempt already spent the mark; a retry is an ordinary \
2013             requeue, not a fresh interrupt request"
2014        );
2015    }
2016
2017    #[test]
2018    fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
2019        let (_dir, q) = queue();
2020        let mut a = task("first filed");
2021        let mut b = task("second filed");
2022        a.id = "20260101-000001-aaaa".to_owned();
2023        b.id = "20260101-000002-bbbb".to_owned();
2024        q.put(&mut a).unwrap();
2025        q.put(&mut b).unwrap();
2026
2027        assert_eq!(
2028            q.next_runnable().unwrap().id,
2029            a.id,
2030            "with equal priority the older task goes first, so a burst of \
2031             new work cannot starve it"
2032        );
2033        assert_eq!(
2034            q.list()[0].id,
2035            b.id,
2036            "but the list an operator reads is newest first, the same as \
2037             before priority existed - a's turn to run does not make it the \
2038             newest task"
2039        );
2040
2041        let mut a = q.get(&a.id).unwrap();
2042        a.set_priority(10).unwrap();
2043        q.put(&mut a).unwrap();
2044
2045        assert_eq!(
2046            q.next_runnable().unwrap().id,
2047            a.id,
2048            "a raised priority must be reflected the moment it is saved"
2049        );
2050        // `magi task list` and `GET /api/queue` both print `Queue::list()`
2051        // directly, so the raised task has to lead there too - not only in
2052        // what the loop would claim next.
2053        assert_eq!(
2054            q.list()[0].id,
2055            a.id,
2056            "the raised task must sort first in the list an operator reads, \
2057             not only in next_runnable's own ordering"
2058        );
2059    }
2060
2061    #[test]
2062    fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
2063        let mut t = Task::new(
2064            "old title".to_owned(),
2065            "old instruction".to_owned(),
2066            PathBuf::from("/repo"),
2067            Source::Agent {
2068                run: "20260101-000000-beef".to_owned(),
2069                node: "implement".to_owned(),
2070            },
2071        );
2072        let id = t.id.clone();
2073        let created_at = t.created_at;
2074        t.runs.push("20260101-000000-beef".to_owned());
2075
2076        t.edit("new title".to_owned(), "new instruction".to_owned())
2077            .unwrap();
2078
2079        assert_eq!(t.title, "new title");
2080        assert_eq!(t.instruction, "new instruction");
2081        assert_eq!(t.id, id, "editing must not mint a new id");
2082        assert_eq!(t.created_at, created_at);
2083        assert_eq!(
2084            t.source,
2085            Source::Agent {
2086                run: "20260101-000000-beef".to_owned(),
2087                node: "implement".to_owned(),
2088            },
2089            "editing must not turn agent attribution into human"
2090        );
2091        assert_eq!(t.runs, ["20260101-000000-beef"]);
2092    }
2093
2094    #[test]
2095    fn editing_is_refused_once_a_task_is_running_or_finished() {
2096        let mut running = task("in flight");
2097        running.start("run-1".to_owned());
2098        let err = running
2099            .edit("x".to_owned(), "y".to_owned())
2100            .unwrap_err()
2101            .to_string();
2102        assert!(err.contains("running"), "{err}");
2103
2104        let mut done = task("finished");
2105        done.succeed();
2106        let err = done
2107            .edit("x".to_owned(), "y".to_owned())
2108            .unwrap_err()
2109            .to_string();
2110        assert!(err.contains("done"), "{err}");
2111
2112        // Both queued and held are the point of the feature and must work.
2113        let mut queued = task("waiting");
2114        queued.edit("x".to_owned(), "y".to_owned()).unwrap();
2115        let mut held = task("parked");
2116        held.hold_machine(None);
2117        held.edit("x".to_owned(), "y".to_owned()).unwrap();
2118    }
2119
2120    #[test]
2121    fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
2122        let (_dir, q) = queue();
2123        let path = q.path_of("20260101-000000-aaaa");
2124        std::fs::create_dir_all(q.root()).unwrap();
2125        std::fs::write(
2126            &path,
2127            serde_json::json!({
2128                "schema": SCHEMA,
2129                "id": "20260101-000000-aaaa",
2130                "title": "from before hold reasons existed",
2131                "instruction": "from before hold reasons existed",
2132                "repo": ".",
2133                "source": { "kind": "human" },
2134                "status": "held",
2135                "created_at": Timestamp::now().to_string(),
2136                "updated_at": Timestamp::now().to_string(),
2137            })
2138            .to_string(),
2139        )
2140        .unwrap();
2141
2142        let task = q.get("20260101-000000-aaaa").expect("must still read");
2143        assert!(task.hold_reason.is_none());
2144        assert!(task.operator_held());
2145    }
2146
2147    #[test]
2148    fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
2149        let (_dir, q) = queue();
2150        let path = q.path_of("20260101-000000-bbbb");
2151        std::fs::create_dir_all(q.root()).unwrap();
2152        std::fs::write(
2153            &path,
2154            serde_json::json!({
2155                "schema": 2,
2156                "id": "20260101-000000-bbbb",
2157                "title": "old manual recovery",
2158                "instruction": "old manual recovery",
2159                "repo": ".",
2160                "source": { "kind": "human" },
2161                "status": "held",
2162                "hold_reason": "active manual recovery run20260912-224242-daf5",
2163                "created_at": Timestamp::now().to_string(),
2164                "updated_at": Timestamp::now().to_string(),
2165            })
2166            .to_string(),
2167        )
2168        .unwrap();
2169
2170        let task = q.get("20260101-000000-bbbb").expect("must still read");
2171        assert_eq!(task.hold_source, None);
2172        assert!(task.operator_held());
2173    }
2174
2175    #[test]
2176    fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
2177        let (_dir, q) = queue();
2178        let path = q.path_of("20260101-000000-aaaa");
2179        std::fs::create_dir_all(q.root()).unwrap();
2180        std::fs::write(
2181            &path,
2182            serde_json::json!({
2183                "schema": SCHEMA,
2184                "id": "20260101-000000-aaaa",
2185                "title": "from before diagnostics existed",
2186                "instruction": "from before diagnostics existed",
2187                "repo": ".",
2188                "source": { "kind": "human" },
2189                "status": "held",
2190                "created_at": Timestamp::now().to_string(),
2191                "updated_at": Timestamp::now().to_string(),
2192            })
2193            .to_string(),
2194        )
2195        .unwrap();
2196
2197        let task = q.get("20260101-000000-aaaa").expect("must still read");
2198        assert!(task.diagnostic.is_none());
2199    }
2200
2201    #[test]
2202    fn a_schema_1_task_with_no_blocking_fields_still_reads() {
2203        // Written by a build that predates `blocked_by`, `block_reason`,
2204        // `answers` and `review_branch` entirely - literal `"schema": 1`,
2205        // not `SCHEMA`, since the whole point is a build older than this one.
2206        let (_dir, q) = queue();
2207        let path = q.path_of("20260101-000000-aaaa");
2208        std::fs::create_dir_all(q.root()).unwrap();
2209        std::fs::write(
2210            &path,
2211            serde_json::json!({
2212                "schema": 1,
2213                "id": "20260101-000000-aaaa",
2214                "title": "from before blocking existed",
2215                "instruction": "from before blocking existed",
2216                "repo": ".",
2217                "source": { "kind": "human" },
2218                "status": "queued",
2219                "created_at": Timestamp::now().to_string(),
2220                "updated_at": Timestamp::now().to_string(),
2221            })
2222            .to_string(),
2223        )
2224        .unwrap();
2225
2226        let task = q.get("20260101-000000-aaaa").expect("must still read");
2227        assert!(task.blocked_by.is_empty());
2228        assert!(task.block_reason.is_none());
2229        assert!(task.answers.is_empty());
2230        assert!(task.review_branch.is_none());
2231    }
2232
2233    #[test]
2234    fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
2235        // A diagnostic belongs to the run that produced it. Left in place
2236        // across a release, an unrelated later failure - a config error, say -
2237        // would go on showing evidence for a problem that is no longer why the
2238        // task is stuck.
2239        let mut held = task("diagnosed");
2240        held.start("run-1".to_owned());
2241        held.fail("gate red", 1);
2242        held.diagnostic = Some("cargo test failed: ...".to_owned());
2243        assert_eq!(held.status, TaskStatus::Held);
2244
2245        held.release();
2246        assert!(held.diagnostic.is_none());
2247
2248        held.diagnostic = Some("cargo test failed: ...".to_owned());
2249        held.succeed();
2250        assert!(held.diagnostic.is_none());
2251    }
2252
2253    #[test]
2254    fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
2255        let mut t = task("retried");
2256        t.start("run-1".to_owned());
2257        t.diagnostic = Some("stale evidence from a previous hold".to_owned());
2258        t.fail("unrelated config error", 5);
2259        assert_eq!(t.status, TaskStatus::Failed);
2260        assert!(
2261            t.diagnostic.is_none(),
2262            "fail() must not let an old diagnostic outlive the run that produced it"
2263        );
2264    }
2265
2266    #[test]
2267    fn a_claim_is_exclusive_and_releases_on_drop() {
2268        let (_dir, q) = queue();
2269        let mut t = task("contended");
2270        q.put(&mut t).unwrap();
2271
2272        let held = q.claim(&t.id).unwrap();
2273        assert!(
2274            q.claim(&t.id).is_err(),
2275            "two daemons must not drive one task into two runs"
2276        );
2277        drop(held);
2278        assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
2279    }
2280
2281    #[test]
2282    fn a_round_trip_survives_disk() {
2283        let (_dir, q) = queue();
2284        let mut t = Task::new(
2285            "titled".to_owned(),
2286            "body".to_owned(),
2287            PathBuf::from("/repo"),
2288            Source::Agent {
2289                run: "20260101-000000-beef".to_owned(),
2290                node: "implement".to_owned(),
2291            },
2292        );
2293        t.priority = 3;
2294        q.put(&mut t).unwrap();
2295
2296        let back = q.get(&t.id).unwrap();
2297        assert_eq!(back.id, t.id);
2298        assert_eq!(back.priority, 3);
2299        assert_eq!(back.source.label(), "implement@beef");
2300        // A prefix is enough, the way run ids work everywhere else.
2301        assert_eq!(q.get(t.short()).unwrap().id, t.id);
2302    }
2303
2304    #[test]
2305    fn an_unreadable_task_does_not_take_the_queue_down() {
2306        let (_dir, q) = queue();
2307        let mut t = task("fine");
2308        q.put(&mut t).unwrap();
2309        std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
2310
2311        let listed = q.list();
2312        assert_eq!(listed.len(), 1, "the readable task still lists");
2313        assert_eq!(listed[0].id, t.id);
2314    }
2315
2316    #[test]
2317    fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
2318        let (_dir, q) = queue();
2319        let path = q.path_of("20260101-000000-aaaa");
2320        std::fs::create_dir_all(q.root()).unwrap();
2321        std::fs::write(
2322            &path,
2323            serde_json::json!({
2324                "schema": SCHEMA,
2325                "id": "20260101-000000-aaaa",
2326                "title": "from before solo existed",
2327                "instruction": "from before solo existed",
2328                "repo": ".",
2329                "source": { "kind": "human" },
2330                "status": "queued",
2331                "created_at": Timestamp::now().to_string(),
2332                "updated_at": Timestamp::now().to_string(),
2333            })
2334            .to_string(),
2335        )
2336        .unwrap();
2337
2338        let task = q.get("20260101-000000-aaaa").expect("must still read");
2339        assert!(!task.solo, "a queue file with no `solo` field means false");
2340    }
2341
2342    #[test]
2343    fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
2344        let (_dir, q) = queue();
2345        let path = q.path_of("20260101-000000-bbbb");
2346        std::fs::create_dir_all(q.root()).unwrap();
2347        std::fs::write(
2348            &path,
2349            serde_json::json!({
2350                "schema": SCHEMA,
2351                "id": "20260101-000000-bbbb",
2352                "title": "from before urgent existed",
2353                "instruction": "from before urgent existed",
2354                "repo": ".",
2355                "source": { "kind": "human" },
2356                "status": "queued",
2357                "created_at": Timestamp::now().to_string(),
2358                "updated_at": Timestamp::now().to_string(),
2359            })
2360            .to_string(),
2361        )
2362        .unwrap();
2363
2364        let task = q.get("20260101-000000-bbbb").expect("must still read");
2365        assert!(
2366            !task.urgent,
2367            "a queue file with no `urgent` field means false, same as `solo`"
2368        );
2369    }
2370
2371    #[test]
2372    fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
2373        let (_dir, q) = queue();
2374        let mut t = task("from the future");
2375        q.put(&mut t).unwrap();
2376        let path = q.path_of(&t.id);
2377        let body = std::fs::read_to_string(&path)
2378            .unwrap()
2379            .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
2380        std::fs::write(&path, body).unwrap();
2381
2382        let err = q.get(&t.id).unwrap_err().to_string();
2383        assert!(err.contains("schema 99"), "{err}");
2384    }
2385
2386    #[test]
2387    fn revision_moves_when_the_queue_changes() {
2388        let (_dir, q) = queue();
2389        assert_eq!(q.revision(), 0, "an empty queue has no revision");
2390        let mut t = task("first");
2391        q.put(&mut t).unwrap();
2392        assert!(q.revision() > 0, "a written task moves the revision");
2393    }
2394
2395    #[test]
2396    fn revision_moves_when_deleting_an_older_task() {
2397        let (dir, q) = queue();
2398        let questions = Questions::at(dir.path().join("questions"));
2399        let mut t1 = task("older");
2400        q.put(&mut t1).unwrap();
2401        // Ensure mtime ticks forward.
2402        std::thread::sleep(std::time::Duration::from_millis(10));
2403        let mut t2 = task("newer");
2404        q.put(&mut t2).unwrap();
2405
2406        let rev_before = q.revision();
2407        q.remove(&t1.id, false, &questions).unwrap();
2408        let rev_after = q.revision();
2409
2410        assert_ne!(
2411            rev_before, rev_after,
2412            "deleting an older task must change the revision so other clients see the deletion"
2413        );
2414    }
2415
2416    #[test]
2417    fn removing_a_task_takes_it_out_of_the_listing() {
2418        let (dir, q) = queue();
2419        let questions = Questions::at(dir.path().join("questions"));
2420        let mut t = task("delete me");
2421        q.put(&mut t).unwrap();
2422        let removed = q.remove(t.short(), false, &questions).unwrap();
2423        assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
2424        assert!(removed.quarantined.is_empty(), "nothing was blocked on it");
2425        assert!(q.list().is_empty());
2426        assert!(
2427            q.remove(&t.id, false, &questions).is_err(),
2428            "removing twice is an error"
2429        );
2430    }
2431
2432    #[test]
2433    fn removing_a_task_takes_its_stale_lock_with_it() {
2434        let (dir, q) = queue();
2435        let questions = Questions::at(dir.path().join("questions"));
2436        let mut t = task("interrupted");
2437        q.put(&mut t).unwrap();
2438
2439        // A daemon killed mid-run leaves this behind. Nothing holds it: the
2440        // process that would have dropped the guard is gone.
2441        let claim = q.claim(&t.id).unwrap();
2442        std::mem::forget(claim);
2443        assert!(
2444            q.claim(&t.id).is_err(),
2445            "the orphaned lock is what makes the task look claimed"
2446        );
2447
2448        // A live daemon on this task is refused, whatever the lock says.
2449        let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
2450        assert!(err.contains("live daemon"), "{err}");
2451        assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
2452
2453        // With no daemon behind it, the lock is stale and goes with the task.
2454        q.remove(&t.id, false, &questions).unwrap();
2455        assert!(q.list().is_empty());
2456        let mut again = task("interrupted");
2457        again.id = t.id.clone();
2458        q.put(&mut again).unwrap();
2459        assert!(
2460            q.claim(&t.id).is_ok(),
2461            "a task that comes back must be claimable, which a left-behind lock would prevent"
2462        );
2463    }
2464
2465    #[test]
2466    fn removing_a_task_quarantines_what_was_blocked_on_it() {
2467        let (dir, q) = queue();
2468        let questions = Questions::at(dir.path().join("questions"));
2469
2470        let mut dep = task("dependency");
2471        q.put(&mut dep).unwrap();
2472
2473        let mut still_valid = task("still valid");
2474        q.put(&mut still_valid).unwrap();
2475
2476        let mut blocked = task("waiting");
2477        blocked.block(
2478            vec![dep.id.clone(), still_valid.id.clone()],
2479            Some("waits on both".to_owned()),
2480        );
2481        q.put(&mut blocked).unwrap();
2482
2483        let removed = q.remove(&dep.id, false, &questions).unwrap();
2484        assert_eq!(removed.quarantined, [blocked.id.clone()]);
2485
2486        let after = q.get(&blocked.id).unwrap();
2487        assert_eq!(after.status, TaskStatus::Held);
2488        assert_eq!(after.hold_source, Some(HoldSource::Machine));
2489        assert!(after.blocked_by.is_empty());
2490        let reason = after.hold_reason.as_deref().unwrap_or_default();
2491        assert!(reason.contains(&dep.id), "{reason}");
2492        assert!(
2493            reason.contains(&still_valid.id),
2494            "the still-valid dependency must survive in the reason text: {reason}"
2495        );
2496    }
2497}