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
33#[cfg(test)]
34thread_local! {
35    pub(crate) static LIST_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
36}
37
38use std::collections::HashMap;
39use std::num::NonZeroUsize;
40use std::path::{Path, PathBuf};
41
42use anyhow::{Context, Result, bail};
43use jiff::Timestamp;
44use serde::{Deserialize, Serialize};
45
46use crate::ask::Questions;
47use crate::config::BuildCache;
48use crate::id_reserve::{IdSource, path_exists};
49
50/// On-disk format for a queued task. Bumped when a field's meaning changes.
51///
52/// 21: task/chat command effect receipts commit atomically with local transitions.
53///
54/// 18: retained review criteria snapshots survive operator edits.
55///
56/// 17: durable explicit operator resumption, independent of run startup.
57///
58/// 7: added [`Task::attachments`], names of files copied under
59/// `<id>.attachments/` beside the task file (a field only; `#[serde(default)]`,
60/// so an older record reads as empty and [`read_path`] still accepts it).
61///
62/// 6: added [`Task::resume_override`] (a field only; `#[serde(default)]`, so
63/// an older record reads as `None` and [`read_path`] still accepts it).
64///
65/// 5: added [`Task::triage_applied`], the ids of triage questions whose
66/// answer has already been applied to this task. A "resume" answer used to
67/// leave no trace ([`Task::release`] clears [`Task::hold_reason`], which was
68/// the only place the applied marker lived), so when the released task failed
69/// its attempts and went back to `held`, the next idle pass found the same
70/// answered question "not applied" and released it again with `attempts` reset
71/// to 0 - the `max_attempts` bound never held. `#[serde(default)]` so an older
72/// record reads as empty. A task already looping when this build arrives has
73/// no record, so it is released once more, recorded, and then stays held.
74///
75/// 8: added [`Task::followup`], the origin of a task `crate::followup` filed
76/// from a merged run's leftover findings. Field-only bump, `#[serde(default)]`.
77///
78/// 4: added [`Task::blocked_from`], the status a task had the moment it
79/// became [`TaskStatus::Blocked`], so [`Task::unblock`] restores it instead
80/// of always landing on [`TaskStatus::Queued`]. Without it, a task a human
81/// or `crate::triage` had deliberately left [`TaskStatus::Held`] — machine
82/// or manual — would lose that the instant `crate::conduct` blocked it on a
83/// follow-up question, and come back `Queued` the moment the question was
84/// answered, regardless of what the answer said: exactly the loop where a
85/// task the operator told to stay held instead re-enters the competition
86/// queue every time someone answers a question about it. `#[serde(default)]`
87/// so an older record reads as `None`; [`Task::unblock`] then falls back to
88/// inferring `Held` from surviving hold evidence ([`Task::hold_reason`] /
89/// [`Task::hold_source`], never cleared by [`Task::block`]) rather than
90/// guessing `Queued` outright — see [`Task::unblock`]'s own doc.
91///
92/// 9: added [`Task::held_at`], the start of the current hold, so a notice can
93/// tell a question filed for this hold from one about an older cause.
94/// Field-only, `#[serde(default)]`.
95///
96/// 10: added [`Task::overrides`] and [`Task::review_of`], so a run started by
97/// hand (`magi run` / `magi review`) is carried by a task without losing its
98/// command-line choices. Field-only.
99///
100/// 11: added [`TaskStatus::Parked`] and [`Task::park_reason`], so a run that
101/// stopped at a node boundary (an upgrade, an operator's park) is no longer
102/// recorded as a failed task. Variant plus `#[serde(default)]` field; an older
103/// build must not half-read the new status.
104///
105/// 12: added [`Task::origin_chat`], the talk a task descends from, so a
106/// follow-up still knows its chat after an ancestor task is deleted.
107/// Field-only, `#[serde(default)]`.
108///
109/// 13: added [`Task::chat_notice`], the record that a chat-filed task's final
110/// state was reported to its conversation. Field-only, `#[serde(default)]`;
111/// a record below this schema is never notified (an upgrade must not replay
112/// the whole history into chats).
113///
114/// 3: added [`HoldSource`] so conductor recovery cannot release a hold an
115/// operator deliberately placed. Old records default to `None` and are
116/// protected as operator-held until an explicit release; the safe direction
117/// when their author was never recorded.
118///
119/// 2: added [`TaskStatus::Blocked`], [`Task::blocked_by`] and
120/// [`Task::block_reason`] (`crate::conduct`'s decisions) and
121/// [`Task::answers`] (operator answers carried forward to the next
122/// conductor prompt and the next run's instruction). All three are
123/// `#[serde(default)]`, so [`read_path`] accepts anything up to and
124/// including this schema rather than only an exact match — a task written
125/// by a build that only knew about schema 1 has nothing to say about
126/// blocking or answers, and defaulting those fields is exactly as good a
127/// reading as a value that build never had a chance to write.
128///
129/// 15: added [`Task::passes`], what each settled pass over a run did to the
130/// attempt budget and why it stopped. Field-only, `#[serde(default)]`; a task
131/// from before this has no entry for its earlier passes, which stay unknown.
132///
133/// 14: record whether a task count edit's overrides inherit daemon options.
134/// Old overrides default to isolated command-line settings, including empty ones.
135///
136/// 16: added [`Task::attempt_limit`], an optional task-specific retry budget.
137/// Field-only, `#[serde(default)]`; old records inherit the daemon limit.
138///
139/// 19: persist settled pass start times for upgrade-resume scheduling.
140/// Old passes default to unknown and use settlement order as an approximation.
141/// 20: persist the task decision chat destination, defaulting to absent.
142/// 21: repository assignment history and execution boundaries, empty on old tasks.
143/// 22: typed disk resource waits and a retained execution pin for automatic recovery.
144/// 23: new tasks inherit `verify.build_cache` unless explicitly overridden.
145/// Older tasks retain shared builds.
146///
147/// 24: bind automatic recovery-budget holds to their stopped execution.
148///
149/// 25: append-only completion/reopen audit and occurrence-bound completion notices.
150///
151/// 26: typed conclusive `head_e2e` machine hold cause.
152/// 27: issue provenance independent of filing attribution.
153/// 28: distinguish a recorded reopen hold from an ambiguous legacy snapshot.
154pub const SCHEMA: u32 = 28;
155
156const RECOVERY_HOLD_SCHEMA: u32 = 24;
157const REOPEN_HOLD_SCHEMA: u32 = 28;
158
159/// Candidate order only: all claims, lanes and eligibility gates still apply.
160/// Upgrade-parked runs retain their pass-start order ahead of ordinary work,
161/// regardless of ordinary priority. Old records without a start time use
162/// settlement time and task id as an approximation. Other parks are ordinary.
163/// Urgent slots and explicit interrupts are handled separately by the daemon.
164pub(crate) fn dispatch_order(a: &Task, b: &Task) -> std::cmp::Ordering {
165    match (a.upgrade_resume_key(), b.upgrade_resume_key()) {
166        (Some(a), Some(b)) => a.cmp(&b),
167        (Some(_), None) => std::cmp::Ordering::Less,
168        (None, Some(_)) => std::cmp::Ordering::Greater,
169        (None, None) => b.priority.cmp(&a.priority).then(a.id.cmp(&b.id)),
170    }
171}
172
173/// Resource waits eligible for automatic admission checks, never owner approval.
174///
175/// Bound to the `hold_reason` it was recorded with: [`Task::has_disk_capacity_cause`]
176/// honours it only while the task still carries that exact reason, so a later
177/// hold that rewrites the reason invalidates it even if a transition forgets to
178/// clear the cause.
179#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
180#[serde(tag = "kind", rename_all = "snake_case")]
181pub enum MachineHoldCause {
182    /// The disk floor or an output reservation prevented execution.
183    DiskCapacity {
184        /// The exact `hold_reason` the hold was placed with.
185        reason: String,
186        /// Admission stopped before a new execution was established.
187        #[serde(default)]
188        before_start: bool,
189    },
190    /// Conclusive current-head `verify.e2e` red on an unchanged candidate/base.
191    HeadE2e {
192        /// Stable stop identity and failure facts.
193        stop: crate::head_e2e_stop::Stop,
194    },
195}
196
197/// Who placed the current hold.
198#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
199#[serde(rename_all = "lowercase")]
200pub enum HoldSource {
201    /// An operator used the CLI or web UI.
202    Manual,
203    /// The daemon or conductor placed the hold as part of its own recovery.
204    Machine,
205}
206
207impl HoldSource {
208    /// Short human-facing label for reports and the CLI.
209    pub fn label(self) -> &'static str {
210        match self {
211            Self::Manual => "manual",
212            Self::Machine => "machine",
213        }
214    }
215}
216
217/// Where a task came from. Recorded because "who asked for this" is the first
218/// question about an autonomous run, and the answer is not recoverable later.
219#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
220#[serde(tag = "kind", rename_all = "lowercase")]
221pub enum Source {
222    /// A person, at a terminal or through the web UI.
223    Human,
224    /// An agent inside a run, via `magi task add`. Both ids are recorded so a
225    /// task can be traced back to the exact seat that asked for it.
226    Agent {
227        /// Run the asking agent belonged to.
228        run: String,
229        /// Node it was working in, e.g. `implement` or `review`.
230        node: String,
231    },
232    /// A GitHub issue, imported by number.
233    Issue {
234        /// Issue number.
235        number: u64,
236        /// `owner/repo`, as `gh` reports it.
237        repo: String,
238    },
239}
240
241/// GitHub issue imported as the task instruction.
242#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
243pub struct IssueRef {
244    /// Issue number in the originating repository.
245    pub number: u64,
246    /// GitHub `owner/repo`.
247    pub repo: String,
248}
249
250/// The `node` a [`Source::Agent`] carries when the asker is a chat
251/// conversation (its `run` is then the conversation's id).
252pub const CHAT_NODE: &str = "chat";
253
254impl Source {
255    /// Short human-facing label, for lists and the web UI.
256    pub fn label(&self) -> String {
257        match self {
258            Self::Human => "human".to_owned(),
259            Self::Agent { run, node } => format!("{node}@{}", short(run)),
260            Self::Issue { number, .. } => format!("issue #{number}"),
261        }
262    }
263}
264
265/// Where a task is in its life.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
267#[serde(rename_all = "lowercase")]
268pub enum TaskStatus {
269    /// Waiting to be claimed.
270    Queued,
271    /// Claimed by a daemon; a run is in flight.
272    Running,
273    /// A run finished and its gate passed.
274    Done,
275    /// A run finished without passing, and attempts remain.
276    Failed,
277    /// Out of attempts, or held by hand. The loop will not pick it up.
278    Held,
279    /// Waiting on another task or an unanswered question. See
280    /// [`Task::blocked_by`]. Set and cleared by `crate::conduct` and
281    /// `crate::daemon`'s deterministic resolver, never by hand.
282    Blocked,
283    /// The run stopped at a node boundary because the process was asked to
284    /// give itself back. Nothing failed: the run's work is intact and the next
285    /// loop resumes it. Runnable like [`TaskStatus::Queued`]; the reason is in
286    /// [`Task::park_reason`], never [`Task::last_error`].
287    Parked,
288}
289
290impl TaskStatus {
291    /// Is this task eligible for a daemon to claim?
292    pub fn runnable(self) -> bool {
293        matches!(self, Self::Queued | Self::Failed | Self::Parked)
294    }
295
296    /// Lowercase name, as it appears on disk and in the API.
297    pub fn as_str(self) -> &'static str {
298        match self {
299            Self::Queued => "queued",
300            Self::Running => "running",
301            Self::Done => "done",
302            Self::Failed => "failed",
303            Self::Held => "held",
304            Self::Blocked => "blocked",
305            Self::Parked => "parked",
306        }
307    }
308}
309
310/// How many tasks sit in each [`TaskStatus`], for a dashboard tile — never a
311/// per-task view, so it carries no ids.
312#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
313pub struct TaskCounts {
314    /// Waiting to be claimed.
315    pub queued: usize,
316    /// Claimed; a run is in flight.
317    pub running: usize,
318    /// A run finished and its gate passed.
319    pub done: usize,
320    /// A run finished without passing, and attempts remain.
321    pub failed: usize,
322    /// Out of attempts, or held by hand.
323    pub held: usize,
324    /// Waiting on another task or an unanswered question.
325    pub blocked: usize,
326    /// Run parked at a node boundary; resumable, not a failure.
327    pub parked: usize,
328}
329
330impl TaskCounts {
331    /// Tally `tasks` by status. A pure function over whatever [`Queue::list`]
332    /// already read, so it needs no root of its own and stays trivially
333    /// testable against a hand-built slice.
334    pub fn of(tasks: &[Task]) -> Self {
335        Self::of_statuses(tasks.iter().map(|task| task.status))
336    }
337
338    /// Count current statuses from a reconciled display projection.
339    pub(crate) fn of_statuses(statuses: impl IntoIterator<Item = TaskStatus>) -> Self {
340        let mut counts = Self::default();
341        for status in statuses {
342            match status {
343                TaskStatus::Queued => counts.queued += 1,
344                TaskStatus::Running => counts.running += 1,
345                TaskStatus::Done => counts.done += 1,
346                TaskStatus::Failed => counts.failed += 1,
347                TaskStatus::Held => counts.held += 1,
348                TaskStatus::Blocked => counts.blocked += 1,
349                TaskStatus::Parked => counts.parked += 1,
350            }
351        }
352        counts
353    }
354}
355
356/// Audit record and execution boundary for a repository reassignment.
357#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
358pub struct Reassignment {
359    /// Original repository.
360    pub from: PathBuf,
361    /// Newly selected repository.
362    pub to: PathBuf,
363    /// Control surface or conversation that requested this change.
364    pub actor: String,
365    /// Time of the operator decision.
366    pub at: Timestamp,
367    /// Runs before this boundary can never execute for this assignment.
368    pub run_boundary: usize,
369}
370
371/// Origin of a completion or reopen decision.
372#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
373#[serde(tag = "kind", content = "talk", rename_all = "snake_case")]
374pub enum CompletionActor {
375    /// Terminal operator.
376    Cli,
377    /// Web operator.
378    Web,
379    /// Decision made in the named conversation.
380    Chat(String),
381    /// Conductor decision.
382    Conductor,
383    /// Automatic run settlement.
384    DaemonSettle,
385}
386
387/// A task lifecycle decision, distinct from a run outcome.
388#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
389#[serde(rename_all = "snake_case")]
390pub enum CompletionAction {
391    /// Task was marked done.
392    Complete,
393    /// Task was reopened into an operator hold.
394    Reopen,
395}
396
397/// The manual hold created by one reopen occurrence.
398#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
399struct ReopenHold {
400    occurrence: String,
401    held_at: Timestamp,
402    decision: Option<Timestamp>,
403    #[serde(default)]
404    legacy: bool,
405}
406
407/// Run and publication evidence observed when a task decision was made.
408#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
409pub struct CompletionRunSnapshot {
410    /// Retained run identifier.
411    pub id: String,
412    /// Unknown when the retained record could not be read.
413    pub status: Option<crate::run::RunStatus>,
414    /// Recorded public pull request.
415    pub pr_url: Option<String>,
416    /// Recorded or freshly observed public lifecycle.
417    pub pr_state: Option<String>,
418    /// Last published or merged public commit.
419    pub pr_head: Option<String>,
420    /// Retained candidate and public branch names; never deleted by a task decision.
421    #[serde(default)]
422    pub branches: Vec<String>,
423    /// Why a run snapshot was unavailable.
424    pub error: Option<String>,
425}
426
427impl CompletionRunSnapshot {
428    fn from_run(state: &crate::run::RunState) -> Self {
429        let mut branches: Vec<String> = state
430            .candidates
431            .iter()
432            .map(|candidate| candidate.branch.clone())
433            .collect();
434        if let Some(branch) = &state.pr_head
435            && !branches.contains(branch)
436        {
437            branches.push(branch.clone());
438        }
439        Self {
440            id: state.id.clone(),
441            status: Some(state.status),
442            pr_url: state.pr.as_ref().map(|pr| pr.url.clone()),
443            pr_state: state.pr.as_ref().map(|pr| pr.state.clone()),
444            pr_head: state
445                .pr_merged_head
446                .clone()
447                .or_else(|| state.pr_pushed_head.clone()),
448            branches,
449            error: None,
450        }
451    }
452}
453
454/// Mandatory evidence supplied by every path that marks a task done.
455#[derive(Debug, Clone)]
456pub struct CompletionContext {
457    /// Surface or process responsible for the decision.
458    pub actor: CompletionActor,
459    /// Operator explanation or settlement rationale.
460    pub reason: Option<String>,
461    /// Explicit permission to abandon an unfinished latest run.
462    pub discard: bool,
463    /// Latest retained execution snapshot, including unreadable-record evidence.
464    pub run: Option<CompletionRunSnapshot>,
465    /// Retained runs whose outcomes could not be read during explicit discard.
466    pub unavailable_runs: Vec<String>,
467}
468
469impl CompletionContext {
470    /// Capture the latest retained execution without inventing missing evidence.
471    pub fn new(actor: CompletionActor, reason: Option<String>, home: &Path, task: &Task) -> Self {
472        let run = task
473            .runs
474            .last()
475            .map(|id| match crate::run::RunState::load_under(id, home) {
476                Ok(state) => CompletionRunSnapshot::from_run(&state),
477                Err(error) => CompletionRunSnapshot {
478                    id: id.clone(),
479                    status: None,
480                    pr_url: None,
481                    pr_state: None,
482                    pr_head: None,
483                    branches: Vec::new(),
484                    error: Some(format!("{error:#}")),
485                },
486            });
487        Self {
488            actor,
489            reason,
490            discard: false,
491            run,
492            unavailable_runs: Vec::new(),
493        }
494    }
495
496    /// Use the exact state already loaded by a run settlement.
497    pub fn from_run(
498        actor: CompletionActor,
499        reason: Option<String>,
500        _task: &Task,
501        state: &crate::run::RunState,
502    ) -> Self {
503        Self {
504            actor,
505            reason,
506            discard: false,
507            run: Some(CompletionRunSnapshot::from_run(state)),
508            unavailable_runs: Vec::new(),
509        }
510    }
511}
512
513/// Immutable, occurrence-addressed task completion/reopen audit.
514#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
515pub struct CompletionEvent {
516    /// Unique decision occurrence, also used to identify its completion notice.
517    pub occurrence: String,
518    /// Kind of transition.
519    pub action: CompletionAction,
520    /// Decision origin.
521    pub actor: CompletionActor,
522    /// Explanation retained verbatim.
523    pub reason: Option<String>,
524    /// Whether unfinished work was explicitly discarded.
525    pub discard: bool,
526    /// Task status before the decision.
527    pub prior_status: TaskStatus,
528    /// Hold explanation before completion cleared active controls.
529    #[serde(default)]
530    pub prior_hold_reason: Option<String>,
531    /// Dependency explanation before completion cleared active controls.
532    #[serde(default)]
533    pub prior_block_reason: Option<String>,
534    /// Last run/task failure evidence before the lifecycle decision.
535    #[serde(default)]
536    pub prior_error: Option<String>,
537    /// Decision time.
538    pub at: Timestamp,
539    /// Run/PR evidence at that time.
540    pub run: Option<CompletionRunSnapshot>,
541    /// Unknown historical outcomes retained when the owner explicitly discarded.
542    #[serde(default, skip_serializing_if = "Vec::is_empty")]
543    pub unavailable_runs: Vec<String>,
544}
545
546/// One unit of work.
547#[derive(Debug, Clone, Serialize, Deserialize)]
548#[serde(deny_unknown_fields)]
549pub struct Task {
550    /// On-disk format version.
551    pub schema: u32,
552    /// Task id, e.g. `20260902-140501-a1b2`.
553    pub id: String,
554    /// One line, for lists and notifications.
555    pub title: String,
556    /// The task itself, handed to the graph verbatim.
557    pub instruction: String,
558    /// Explicit, SHA-pinned implementation imports; separate from instruction text.
559    #[serde(default, skip_serializing_if = "crate::refs::Sources::is_empty")]
560    pub sources: crate::refs::Sources,
561    /// Repository to work in.
562    pub repo: PathBuf,
563    /// Repository assignment boundaries; historical runs remain in `runs`.
564    #[serde(default)]
565    pub reassignments: Vec<Reassignment>,
566    /// Who asked.
567    pub source: Source,
568    /// Issue reference, independent of the filing actor.
569    #[serde(default, skip_serializing_if = "Option::is_none")]
570    pub issue: Option<IssueRef>,
571    /// Durable destination for task decision messages (including tasks filed outside chat).
572    #[serde(default)]
573    pub chat: Option<String>,
574    /// Higher runs first; ties break oldest-first so nothing starves.
575    #[serde(default)]
576    pub priority: i32,
577    /// Run this task alone: one implementer, no panel of judges to convince.
578    ///
579    /// `#[serde(default)]` so a queue file written before this field existed
580    /// still reads, as `false` - the ordinary multi-candidate competition,
581    /// unchanged. A task set to `solo` still runs the whole graph; only the
582    /// candidate count the daemon builds it with changes, and
583    /// [`crate::graph::Runner`] already collapses a single-candidate run to
584    /// implement → review → gate → merge on its own (see
585    /// [`crate::graph::Runner::review`]'s doc), so nothing about judging,
586    /// deliberation or voting had to change to support this.
587    #[serde(default)]
588    pub solo: bool,
589    /// Current state.
590    pub status: TaskStatus,
591    /// Append-only operator and automatic completion/reopen decisions.
592    #[serde(default)]
593    pub completion_history: Vec<CompletionEvent>,
594    /// How many times this task has been claimed.
595    #[serde(default)]
596    pub attempts: usize,
597    /// Total attempt budget; `None` inherits the daemon limit.
598    #[serde(default)]
599    pub attempt_limit: Option<NonZeroUsize>,
600    /// Distinct runs, ordered by their most recent claim. Older records may
601    /// contain repeated ids; execution history lives in the run pass records.
602    #[serde(default)]
603    pub runs: Vec<String>,
604    /// Reserved startups that failed before execution; never a resume source or execution attempt.
605    #[serde(default)]
606    pub startup_failures: Vec<crate::run::StartupFailure>,
607    /// Why the last attempt did not land.
608    #[serde(default)]
609    pub last_error: Option<String>,
610    /// What a human hold is waiting on.
611    ///
612    /// `None` covers both the ordinary cases: a hold the loop makes itself
613    /// (out of attempts, or the disk gate closed) explains itself through
614    /// [`Task::last_error`] instead, and a human hold nobody bothered to
615    /// explain is still a valid hold. The queue has no way to express a
616    /// dependency between two tasks, so on the occasions a hold really is
617    /// "wait for that other task first", this is the only place that reason
618    /// survives - see [`Task::hold_manual`] and [`Task::release`].
619    ///
620    /// `#[serde(default)]` so a queue file written before this field existed
621    /// still reads, with no reason recorded rather than a parse error.
622    #[serde(default)]
623    pub hold_reason: Option<String>,
624    /// Who placed [`Task::hold_reason`].  `None` is a compatible old record;
625    /// see [`Task::operator_held`] for its deliberately conservative meaning.
626    #[serde(default)]
627    pub hold_source: Option<HoldSource>,
628    #[serde(default, skip_serializing_if = "Option::is_none")]
629    recovery_budget_hold: Option<RecoveryBudgetHold>,
630    /// Identity of the manual hold a reopen produced; stale once any later hold or
631    /// owner decision changes `held_at` or `operator_decided_at`.
632    #[serde(default, skip_serializing_if = "Option::is_none")]
633    reopen_hold: Option<ReopenHold>,
634    /// Disk resource wait recorded by the admission gate; never owner consent.
635    #[serde(default)]
636    pub machine_hold_cause: Option<MachineHoldCause>,
637    /// Automatic resource recovery must resume this execution, never compete again.
638    #[serde(default)]
639    pub disk_resume_run: Option<String>,
640    /// Last bounded disk-monitor pass; persisted across scheduler replacement.
641    #[serde(default)]
642    pub disk_checked_at: Option<Timestamp>,
643    /// Diagnostic detail excerpted from the run that led to a hold - what a
644    /// human would have found opening `artifacts/` by hand, not the one-line
645    /// reason in [`Task::last_error`]. Set only when a run's own attempts are
646    /// exhausted and the task becomes [`TaskStatus::Held`]; `daemon` computes
647    /// it from the run's own record, since this module has no notion of a
648    /// run's internals. Bounded in length by the writer - see
649    /// `daemon::diagnostic` - so a verbose run cannot make this file grow
650    /// without limit.
651    ///
652    /// `#[serde(default)]` so a queue file written before this field existed
653    /// still reads, with no diagnostic recorded rather than a parse error.
654    #[serde(default)]
655    pub diagnostic: Option<String>,
656    /// What this task is waiting on: other task ids, unanswered
657    /// `crate::ask::Question` ids, or both. Non-empty exactly when
658    /// [`TaskStatus::Blocked`]; emptying it — see [`Task::unblock`] — is what
659    /// puts the task back at [`TaskStatus::Queued`].
660    ///
661    /// Set by `crate::conduct`'s decisions and cleared deterministically by
662    /// `crate::daemon` as each dependency resolves, never by a person. Never
663    /// `#[serde(default)]` is skipped: a queue file from before this field
664    /// existed has nothing to report here, and an empty list is exactly that.
665    #[serde(default)]
666    pub blocked_by: Vec<String>,
667    /// One line explaining the current [`Task::blocked_by`], written by
668    /// `crate::conduct`. Cleared whenever `blocked_by` empties.
669    #[serde(default)]
670    pub block_reason: Option<String>,
671    /// The status this task had the moment [`Task::block`] most recently
672    /// moved it to [`TaskStatus::Blocked`] — what [`Task::unblock`] restores
673    /// once nothing is left in `blocked_by`, instead of always landing on
674    /// [`TaskStatus::Queued`]. See [`SCHEMA`]'s doc for schema 4 on why this
675    /// exists: an answer to a question `crate::conduct` filed about a
676    /// [`TaskStatus::Held`] task must not itself be what puts the task back
677    /// in the competition queue.
678    ///
679    /// `#[serde(default)]` so a queue file written before this field existed
680    /// reads as `None`; [`Task::unblock`] treats that the same as a task
681    /// blocked straight from `Queued`, unless surviving hold evidence says
682    /// otherwise.
683    #[serde(default)]
684    pub blocked_from: Option<TaskStatus>,
685    /// Last change of blocking targets, independent of explanation or delivery writes.
686    #[serde(default)]
687    pub blocked_at: Option<Timestamp>,
688    /// Questions `crate::conduct` asked about this task that the operator has
689    /// since answered, oldest first — what was asked, and what they said.
690    ///
691    /// A blocking question's id leaves [`Task::blocked_by`] the moment
692    /// [`crate::ask::QuestionStatus::Answered`] is observed, but the id alone
693    /// tells nobody what was decided. This is what carries the answer's
694    /// *content* forward: into the next conductor prompt for this task, and
695    /// into the instruction handed to the next run — see `crate::daemon`'s
696    /// deterministic blocker resolution. Kept for the task's whole life, the
697    /// same as [`Task::runs`]: a release resets attempts, not evidence.
698    #[serde(default)]
699    pub answers: Vec<AnsweredQuestion>,
700    /// Ids of the `crate::triage` questions whose answer has been applied to
701    /// this task. Unlike [`Task::hold_reason`], [`Task::release`] and every
702    /// hold transition leave it alone, so an answer is applied at most once
703    /// however many times the task is held again. See [`SCHEMA`]'s doc for
704    /// schema 5. `#[serde(default)]` so an older record reads as empty.
705    #[serde(default)]
706    pub triage_applied: Vec<String>,
707    /// Ids of the `magi ask` questions whose [`crate::ask::ChoiceAction`] has
708    /// been applied to this task. Separate from [`Task::triage_applied`]
709    /// (a different producer) and, like it, untouched by [`Task::release`],
710    /// so one answer acts at most once however often the task is held again.
711    /// `#[serde(default)]` so an older record reads as empty.
712    #[serde(default)]
713    pub actions_applied: Vec<String>,
714    /// Exact task/chat commands committed in the same write as their effects.
715    /// These receipts survive subsequent transitions and execution starts.
716    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
717    pub decision_effects: std::collections::BTreeMap<String, String>,
718    /// Exact resume pins explicitly replaced or removed before dispatch.
719    /// Retained independently of later task transitions and stale writers.
720    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
721    pub superseded_resumes: std::collections::BTreeMap<String, String>,
722    /// Resume inquiry ownership committed atomically with task dispatch.
723    /// This is not effect evidence: only the run's committed pass proves execution.
724    /// Retained across recovery and stale writers until that pass can consume it.
725    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
726    pub dispatched_resumes: std::collections::BTreeMap<String, String>,
727    /// Durable base-recovery request keys saved atomically with the exact-run pin.
728    #[serde(default)]
729    pub base_recovery_requests: Vec<String>,
730    /// Durable land-sync-recovery request keys saved atomically with the exact-run pin.
731    #[serde(default)]
732    pub land_sync_recovery_requests: Vec<String>,
733    /// The operator's "resume" answer to a triage question, kept until the
734    /// task actually runs (or is done) so `crate::conduct` cannot silently
735    /// undo it and `crate::triage` can tell that a hold it sees now came
736    /// *after* the answer. See [`OperatorResume`]. `#[serde(default)]`.
737    #[serde(default)]
738    pub resume_override: Option<OperatorResume>,
739    /// The sync-only fence survives consumption of the ordinary dispatch pin.
740    #[serde(default, skip_serializing_if = "Option::is_none")]
741    pub sync_only: Option<crate::base_sync_only::Request>,
742    /// Immutable repair receipts, saved atomically with the exact-run queue pin.
743    #[serde(default)]
744    pub repair_grants: Vec<crate::repair_budget::Receipt>,
745    /// Append-only owner-authorized reconciliation of an unspent receipt.
746    #[serde(default)]
747    pub repair_reconciliations: Vec<crate::repair_budget::reconcile::Receipt>,
748    /// Latest explicit operator release. Historical answers remain audit evidence;
749    /// this approval takes precedence over their earlier waiting premises.
750    #[serde(default)]
751    pub resumption: Option<Resumption>,
752    /// Earlier explicit approvals retained for audit and instruction suffix matching.
753    #[serde(default)]
754    pub resumption_history: Vec<Resumption>,
755    /// Latest explicit release or manual hold, used to reject delayed answers.
756    #[serde(default)]
757    pub operator_decided_at: Option<Timestamp>,
758    /// Set by `crate::conduct` when it chooses `Review` recovery for a task
759    /// whose branch survived a blocked run: the branch to reopen with
760    /// `crate::graph::Runner::review` instead of competing from scratch.
761    ///
762    /// Requeues the task the same way [`Task::release`] does, so it is
763    /// picked up by the ordinary loop; `crate::daemon` reads this field once,
764    /// when it actually starts the run, and clears it either way — consumed
765    /// on success, dropped if the branch no longer exists by then. Never set
766    /// from the conductor's own words: `crate::daemon` derives the branch
767    /// name itself from the task's last run, so a hallucinated branch can
768    /// never reach here.
769    #[serde(default)]
770    pub review_branch: Option<String>,
771    /// Authored criteria when the retained recovery review was selected.
772    #[serde(default)]
773    pub review_instruction: Option<String>,
774    /// Explicit public implementation selected by the operator; never inferred from prose.
775    #[serde(default)]
776    pub pr_recovery: Option<crate::pr_recovery::Selection>,
777    /// A release deliberately starts a new competition instead of resuming
778    /// the prior run. History remains as evidence in `runs`.
779    #[serde(default)]
780    pub fresh_start: bool,
781    /// Explicit replacement selection; persists through dispatch and resume.
782    #[serde(default)]
783    pub replacement: Option<crate::merge_decision::Replacement>,
784    /// Marked by an operator (`magi task interrupt`) to ask `magi serve` to
785    /// run this one ahead of whatever it already has in flight, once
786    /// `[daemon] pause_for_interrupts` is on - see
787    /// `crate::daemon::advance_interrupt`. Never set by the loop itself, and
788    /// deliberately a different operation from [`Task::set_priority`]: a
789    /// priority only reorders the queue a claim has not reached yet, while
790    /// this asks a run already in flight to park at its next safe boundary
791    /// and step aside. `#[serde(default)]` so a queue file written before
792    /// this field existed still reads, as `false` - no task interrupts
793    /// anything unless asked to, exactly as before.
794    #[serde(default)]
795    pub interrupt: bool,
796    /// Marked by `magi task add --urgent` or `magi task urgent`.
797    /// `crate::daemon::poll` dispatches this task through its own one-slot `urgent_sem` the moment it is
798    /// runnable, in addition to whatever is already running under the
799    /// ordinary `[daemon] max_concurrent_runs` pool - never instead of it,
800    /// and never by pausing or otherwise touching that run. This is the
801    /// opposite direction from [`Task::interrupt`]: that one asks a run
802    /// already in flight to step aside; this one never asks anything to
803    /// step aside, it only spends one additional, temporary concurrency
804    /// slot. The two are independent and may both be set on the same task,
805    /// but this exemption stops at `[daemon] pause_for_interrupts`'s own
806    /// park/resume handoff (75dd): while an interrupt sequence is actively
807    /// parking, running, or resuming - its own, or an unrelated task's -
808    /// `crate::daemon::interrupt_gate` withholds an urgent candidate exactly
809    /// like an ordinary one, never exempted. 75dd's "at most one run, ever,
810    /// at once" guarantee takes precedence, because the alternative is a run
811    /// still genuinely in flight (only *asked* to park, not yet gone) ending
812    /// up alongside a second one this feature let through - the very thing
813    /// that guarantee exists to rule out.
814    ///
815    /// `#[serde(default)]` so a queue file written before this field existed
816    /// still reads, as `false` - no task claims the urgent slot unless asked
817    /// to, exactly as before.
818    #[serde(default)]
819    pub urgent: bool,
820    /// Marked by the owner (`magi task add --immediate`, `magi task immediate`,
821    /// or the Web UI toggle). Stronger than [`Task::urgent`]:
822    /// `crate::daemon::poll` dispatches every runnable immediate task on the
823    /// next scan even when both ordinary and urgent lanes are full, without
824    /// consuming ordinary or urgent permits and without parking or cancelling
825    /// existing workers. Independent of [`Task::urgent`] so clearing immediate
826    /// preserves any saved urgent setting. Non-concurrency gates (dependencies,
827    /// holds, interrupt gate, quota cooldown, disk admission, repository
828    /// coordination, resource waits, merge approvals, and claim exclusivity)
829    /// still apply.
830    ///
831    /// `#[serde(default)]` so a queue file written before this field existed
832    /// still reads as `false`.
833    #[serde(default)]
834    pub immediate: bool,
835    /// Set by [`Task::new`], cleared once a queue has stored the task. Never
836    /// persisted: a task read from disk is always an existing one. While set,
837    /// [`Queue::put`] reserves the id (see [`Queue::file_with`]) instead of
838    /// merging into whatever record already carries it.
839    #[serde(skip)]
840    pub(crate) unfiled: bool,
841    /// Files (typically screenshots) copied into `<id>.attachments/` beside
842    /// this task's file by [`Queue::attach`], as bare validated names. The
843    /// copy is what makes them reach the implementer: the original may be
844    /// cleaned up long before the task runs. Untouched by [`Task::edit`].
845    /// `#[serde(default)]` so an older record reads as empty.
846    #[serde(default)]
847    pub attachments: Vec<String>,
848    /// Set on a task `crate::followup` filed from the findings a merged run
849    /// left open: which run and findings it carries, and how many follow-ups
850    /// deep it is. `None` for every ordinary task. `#[serde(default)]`.
851    #[serde(default)]
852    pub followup: Option<FollowUp>,
853    /// Id of the chat this task descends from: set by [`Task::new`] when a
854    /// chat files it, inherited by the follow-ups `crate::followup` files, so
855    /// the provenance survives deleting an ancestor. `None` for a task written
856    /// before the field existed (`crate::consult` then walks the ancestry).
857    /// `#[serde(default)]`.
858    #[serde(default)]
859    pub origin_chat: Option<String>,
860    /// The command-line choices (`--merge`, `-c`, `--seed`, ...) of the
861    /// `magi run` / `magi review` that filed this task, applied on top of the
862    /// repository's config by whoever executes it - a daemon included - so
863    /// handing the task over does not change what it does. A count edit on an
864    /// ordinary queue task explicitly inherits daemon options instead.
865    /// `#[serde(default)]`.
866    #[serde(default)]
867    pub overrides: Option<RunOverrides>,
868    /// The branch an explicit `magi review <branch>` asked to review. Unlike
869    /// [`Task::review_branch`] (a recovery choice the daemon consumes and
870    /// drops back to a competition when the branch is gone), this is the whole
871    /// request: it is never consumed, and a missing branch fails the attempt
872    /// rather than paying for an implementation nobody asked for.
873    /// `#[serde(default)]`.
874    #[serde(default)]
875    pub review_of: Option<String>,
876    /// When the current hold began. Set by the transitions into
877    /// [`TaskStatus::Held`] (a re-hold keeps it), cleared by
878    /// [`Task::release`]. `crate::notices` uses it as the identity of the
879    /// cause: a question filed before it is about something older.
880    #[serde(default)]
881    pub held_at: Option<Timestamp>,
882    /// Why the run parked, while the task is [`TaskStatus::Parked`]. Kept apart
883    /// from [`Task::last_error`] because nothing failed. Cleared by every
884    /// transition out of the parked state. `#[serde(default)]`.
885    #[serde(default)]
886    pub park_reason: Option<String>,
887    /// The last final state reported to the originating chat. See
888    /// [`Task::chat_notice_due`]. Never cleared by a release or requeue.
889    #[serde(default)]
890    pub chat_notice: Option<ChatNotice>,
891    /// Delivery ledger, unioned under the task lock even on stale writes.
892    #[serde(default)]
893    pub chat_notices: Vec<String>,
894    /// Structured producer identity of the unresolved hold. Requeues and prose
895    /// updates retain it; a settled run or a distinct startup stage replaces it.
896    #[serde(default)]
897    pub hold_notice_cause: Option<NoticeCause>,
898    /// Append-only: one entry per pass over a run that the loop settled. A
899    /// resumed run is one run with several passes, and `attempts` counts
900    /// claims net of refunds, so the two are not the same number; this says
901    /// which pass cost what. Kept across a release.
902    #[serde(default)]
903    pub passes: Vec<TaskPass>,
904    /// When the loop claimed this task for its latest dispatch. Stamped under
905    /// the claim, before any slow start-up work, so it is the real dispatch
906    /// order; `record_pass_at` prefers it over the graph's own pass start.
907    #[serde(default)]
908    pub dispatched_at: Option<Timestamp>,
909    /// Durable failed-input budget, unaffected by automatic release/requeue.
910    #[serde(default)]
911    pub recovery_budget: Option<RecoveryBudget>,
912    /// Inputs resolved before starting the current automatic attempt. The
913    /// settlement uses this same identity even for review-only runs.
914    #[serde(default)]
915    pub recovery_admission: Option<RecoveryAdmission>,
916    /// Previously seen input generations. Switching inputs away and back does
917    /// not refund an exhausted generation without explicit operator authority.
918    #[serde(default)]
919    pub recovery_generations: Vec<RecoveryBudget>,
920    /// When the task was filed.
921    pub created_at: Timestamp,
922    /// Last change to this file.
923    pub updated_at: Timestamp,
924}
925
926/// Admission identity shared by start and settlement.
927#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
928pub struct RecoveryAdmission {
929    /// Fetched upstream commit before any run-local rebase.
930    pub base: String,
931    /// Resolved instruction references and explicit review source.
932    pub inputs: String,
933}
934
935#[derive(Debug, Clone, Serialize, Deserialize)]
936struct RecoveryBudgetHold {
937    admission: RecoveryAdmission,
938    run: String,
939    pass: usize,
940    held_at: Timestamp,
941    decision: Option<Timestamp>,
942    #[serde(default)]
943    legacy: bool,
944}
945
946/// Failures against one recovery input generation. An owner release explicitly
947/// starts a new generation; a machine requeue never replenishes it.
948#[derive(Debug, Clone, Serialize, Deserialize)]
949pub struct RecoveryBudget {
950    /// Authored instructions, not generated review scaffolding.
951    pub instruction: String,
952    /// Upstream commit used to prepare this generation.
953    pub base: String,
954    /// Referenced input commits, including their resolved identities.
955    pub inputs: String,
956    /// Stable processing stage of the last failure.
957    pub stage: String,
958    /// Failed passes, independent of the resettable claim counter.
959    pub failures: usize,
960    /// Fingerprint of actual candidate patches; equivalent rebased commits do
961    /// not count as progress. Unknown inputs never replenish the budget.
962    #[serde(default)]
963    pub progress: Option<String>,
964}
965
966impl RecoveryBudget {
967    fn budget_reason(&self) -> String {
968        format!(
969            "[recovery-budget] {} failed passes against unchanged inputs ({}). Inspect the retained recovery sources and correct the cause, change the inputs, or explicitly release the task to approve another generation. Automatic requeue does not reset this budget.",
970            self.failures, self.stage
971        )
972    }
973}
974
975fn recovery_progress(state: &crate::run::RunState) -> Option<String> {
976    use crate::proc::Quiet as _;
977    use std::hash::{Hash, Hasher};
978    let mut patches = Vec::new();
979    for candidate in state.candidates.iter().filter(|c| c.commits > 0) {
980        let output = std::process::Command::new("git")
981            .current_dir(&state.repo)
982            .args(["diff", "--binary", &state.base_commit, &candidate.branch])
983            .quiet()
984            .output()
985            .ok()?;
986        if !output.status.success() {
987            return None;
988        }
989        patches.push(output.stdout);
990    }
991    patches.sort();
992    patches.dedup();
993    let mut hash = std::collections::hash_map::DefaultHasher::new();
994    patches.hash(&mut hash);
995    Some(format!("{:x}", hash.finish()))
996}
997
998/// The implementation inputs a recovery budget is keyed on: the explicit,
999/// SHA-pinned sources only, never references parsed from instruction prose.
1000/// No sources is `[]`, the key an input-free task always had.
1001pub(crate) fn recovery_inputs(sources: &crate::refs::Sources) -> String {
1002    serde_json::to_string(
1003        &sources
1004            .start_from
1005            .iter()
1006            .map(|i| ("start", &i.token, &i.sha))
1007            .chain(
1008                sources
1009                    .pick_commits
1010                    .iter()
1011                    .map(|i| ("pick", &i.token, &i.sha)),
1012            )
1013            .collect::<Vec<_>>(),
1014    )
1015    .unwrap_or_default()
1016}
1017
1018/// Facts a producer can independently attest about a held outcome.
1019#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1020pub struct NoticeCause {
1021    /// Processing stage or verified external evidence.
1022    pub stage: String,
1023    /// Producer-verified blocker object, independent of the displayed error.
1024    /// Omitted when absent to preserve existing persisted notice keys.
1025    #[serde(default, skip_serializing_if = "Option::is_none")]
1026    pub target: Option<String>,
1027    /// An actual run that reached settlement; absent for preflight failures.
1028    pub run: Option<String>,
1029    /// The settled pass, so a resumed run can report a new failure.
1030    pub pass: Option<usize>,
1031}
1032
1033/// Current and legacy completion keys; legacy run counts contain only digits.
1034pub(crate) fn is_done_notice_key(key: &str) -> bool {
1035    key == "done"
1036        || key
1037            .strip_prefix("done#")
1038            .is_some_and(|count| !count.is_empty() && count.bytes().all(|b| b.is_ascii_digit()))
1039}
1040
1041/// What a settled pass did to the attempt budget.
1042#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1043#[serde(rename_all = "snake_case")]
1044pub enum PassCost {
1045    /// The attempt stays counted.
1046    Spent,
1047    /// The attempt was handed back.
1048    Refunded,
1049}
1050
1051/// One settled pass over a run. See [`Task::passes`].
1052#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1053pub struct TaskPass {
1054    /// The run the pass belongs to.
1055    pub run: String,
1056    /// [`crate::run::RunPass::index`] in that run.
1057    pub pass_index: usize,
1058    /// What it did to the budget.
1059    pub cost: PassCost,
1060    /// `attempts` once this pass was settled.
1061    pub attempts_after: usize,
1062    /// When this pass began, retained across daemon upgrades.
1063    #[serde(default)]
1064    pub started_at: Option<Timestamp>,
1065    /// When the loop settled it.
1066    pub settled_at: Timestamp,
1067    /// Why the pass parked, when it did.
1068    #[serde(default)]
1069    pub parked: Option<crate::run::ParkCause>,
1070}
1071
1072/// What became of a completion notice. See [`Task::chat_notice`].
1073#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
1074#[serde(rename_all = "lowercase")]
1075pub enum ChatNoticeOutcome {
1076    /// Queued as a draft of the originating talk.
1077    Posted,
1078    /// The talk is gone or closed; nothing was queued, and nothing will be.
1079    Skipped,
1080}
1081
1082/// The final state of a chat-filed task that was already reported (or skipped).
1083#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1084pub struct ChatNotice {
1085    /// Identity of the cause, see [`Task::chat_notice_key`].
1086    pub key: String,
1087    /// When it was recorded.
1088    pub at: Timestamp,
1089    /// Posted or skipped.
1090    pub outcome: ChatNoticeOutcome,
1091}
1092
1093/// Command-line choices carried by a task. See [`Task::overrides`].
1094#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
1095pub struct RunOverrides {
1096    /// Count edits on ordinary queued tasks inherit the loop's config and merge.
1097    /// False for direct-run overrides and old records, even when otherwise empty.
1098    #[serde(default)]
1099    pub inherit_daemon_options: bool,
1100    /// `--merge`: `none`, `local` or `pr`.
1101    #[serde(default)]
1102    pub merge: Option<String>,
1103    /// `-c` / `--implementers`: parallel implementations (persisted as `candidates`).
1104    #[serde(default)]
1105    pub candidates: Option<usize>,
1106    /// `-j`: independent judges.
1107    #[serde(default)]
1108    pub judges: Option<usize>,
1109    /// `--reviewers`: reviewers per round.
1110    #[serde(default)]
1111    pub reviewers: Option<usize>,
1112    /// `--review-rounds`.
1113    #[serde(default)]
1114    pub review_rounds: Option<usize>,
1115    /// `--seed`.
1116    #[serde(default)]
1117    pub seed: Option<u64>,
1118    /// `--config`, absolute: the daemon's own working directory differs.
1119    #[serde(default)]
1120    pub config: Option<PathBuf>,
1121    /// `--build-cache`; unset inherits the repository's policy on new tasks.
1122    #[serde(default, skip_serializing_if = "Option::is_none")]
1123    pub build_cache: Option<BuildCache>,
1124}
1125
1126impl RunOverrides {
1127    /// Lay `other` over these: every choice `other` made wins, the rest stay.
1128    pub fn merge_over(&mut self, other: &RunOverrides) {
1129        macro_rules! take {
1130            ($($f:ident),*) => {$(
1131                if other.$f.is_some() {
1132                    self.$f.clone_from(&other.$f);
1133                }
1134            )*};
1135        }
1136        take!(
1137            merge,
1138            candidates,
1139            judges,
1140            reviewers,
1141            review_rounds,
1142            seed,
1143            config,
1144            build_cache
1145        );
1146    }
1147
1148    /// Apply these on top of `config`.
1149    pub fn apply(&self, config: &mut crate::config::Config) {
1150        if let Some(n) = self.candidates {
1151            config.graph.implementers = n;
1152        }
1153        if let Some(n) = self.judges {
1154            config.graph.judges = n;
1155        }
1156        if let Some(n) = self.reviewers {
1157            config.graph.reviewers = n;
1158        }
1159        if let Some(n) = self.review_rounds {
1160            config.graph.review_rounds = n;
1161        }
1162        if let Some(m) = &self.merge
1163            && let Ok(mode) = crate::daemon::merge_mode(m)
1164        {
1165            config.merge.mode = mode;
1166        }
1167        if let Some(s) = self.seed {
1168            config.blind.seed = Some(s);
1169        }
1170        if let Some(mode) = self.build_cache {
1171            config.verify.build_cache = mode;
1172        }
1173    }
1174}
1175
1176/// What a follow-up task came from. See [`Task::followup`].
1177#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1178pub struct FollowUp {
1179    /// The merged run whose open findings this task carries.
1180    pub run: String,
1181    /// The queue task that run served, when it had one.
1182    #[serde(default)]
1183    pub origin_task: Option<String>,
1184    /// The merged pull request.
1185    pub pr: String,
1186    /// Ids of the findings (e.g. `R3-1-1`) this task covers.
1187    pub findings: Vec<String>,
1188    /// Follow-up depth: 1 for a follow-up of an ordinary task's run, 2 for a
1189    /// follow-up of that, and so on. An ordinary task is generation 0.
1190    pub generation: u32,
1191}
1192
1193/// Durable scope of an explicit operator resumption, surviving run startup.
1194#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1195pub struct Resumption {
1196    /// Monotonic count of explicit resumptions.
1197    pub generation: u64,
1198    /// Mutation path that applied the approval.
1199    pub source: String,
1200    /// Answered question, if the approval came from one.
1201    pub question_id: Option<String>,
1202    /// When this approval was applied.
1203    pub at: Timestamp,
1204    /// Authored instruction approved at release.
1205    pub instruction: String,
1206    /// Number of historical answers superseded as waiting premises.
1207    pub answers_through: usize,
1208    /// Legacy run-list boundary retained for record compatibility. Evidence
1209    /// uses approval time and run passes because resumes retain the same id.
1210    pub runs_through: usize,
1211    /// Previous hold or dependency reason cleared by this release.
1212    pub cleared_reason: Option<String>,
1213    /// Verified evidence versions already used to block after this approval.
1214    #[serde(default)]
1215    pub blocking_evidence: Vec<String>,
1216}
1217
1218/// A triage "resume" answer and what became of it. See
1219/// [`Task::resume_override`].
1220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1221pub struct OperatorResume {
1222    /// 回答された Question の ID。Question を伴わない再開では空文字列。
1223    pub question_id: String,
1224    /// When the answer was applied.
1225    pub at: Timestamp,
1226    /// The reason `crate::conduct` gave for holding the task again after the
1227    /// answer, if it did. The conductor may do this once.
1228    #[serde(default)]
1229    pub conductor_rehold: Option<String>,
1230    /// The operator answered "resume" a second time, to the question about
1231    /// that contradiction: the conductor may no longer hold this task.
1232    #[serde(default)]
1233    pub forced: bool,
1234    /// Set when the answer was a structured `resume` action on a `magi ask`
1235    /// choice ([`crate::ask::ChoiceAction::Resume`]): the run the operator
1236    /// chose to continue. Its presence also stops `crate::conduct` from
1237    /// requeuing the task into a fresh competition, which would discard
1238    /// exactly the run that was named. Cleared with the rest of the record
1239    /// once the task runs. `#[serde(default)]` so older records read as `None`.
1240    #[serde(default)]
1241    pub pinned_run: Option<String>,
1242}
1243
1244/// One question `crate::conduct` asked about a task, and what the operator
1245/// said back. See [`Task::answers`].
1246#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1247pub struct AnsweredQuestion {
1248    /// The question as asked, e.g. [`crate::ask::Question::summary`].
1249    pub question: String,
1250    /// What the operator answered.
1251    pub answer: String,
1252}
1253
1254fn append_missing<T: PartialEq>(ledger: &mut Vec<T>, entries: Vec<T>) {
1255    for entry in entries {
1256        if !ledger.contains(&entry) {
1257            ledger.push(entry);
1258        }
1259    }
1260}
1261
1262fn prepend_missing_by<T>(ledger: &mut Vec<T>, mut older: Vec<T>, same: impl Fn(&T, &T) -> bool) {
1263    older.retain(|old| !ledger.iter().any(|entry| same(entry, old)));
1264    if !older.is_empty() {
1265        older.append(ledger);
1266        *ledger = older;
1267    }
1268}
1269
1270impl Task {
1271    /// File a new task. Persist it with [`Queue::put`].
1272    pub fn new(title: String, instruction: String, repo: PathBuf, source: Source) -> Self {
1273        let now = Timestamp::now();
1274        let origin_chat = match &source {
1275            Source::Agent { run, node } if node == CHAT_NODE => Some(run.clone()),
1276            _ => None,
1277        };
1278        Self {
1279            schema: SCHEMA,
1280            id: new_id(),
1281            title,
1282            instruction,
1283            sources: crate::refs::Sources::default(),
1284            repo,
1285            reassignments: Vec::new(),
1286            source,
1287            issue: None,
1288            chat: None,
1289            priority: 0,
1290            solo: false,
1291            status: TaskStatus::Queued,
1292            completion_history: Vec::new(),
1293            attempts: 0,
1294            attempt_limit: None,
1295            runs: Vec::new(),
1296            startup_failures: Vec::new(),
1297            last_error: None,
1298            hold_reason: None,
1299            hold_source: None,
1300            recovery_budget_hold: None,
1301            reopen_hold: None,
1302            machine_hold_cause: None,
1303            disk_resume_run: None,
1304            disk_checked_at: None,
1305            diagnostic: None,
1306            blocked_by: Vec::new(),
1307            block_reason: None,
1308            blocked_from: None,
1309            blocked_at: None,
1310            answers: Vec::new(),
1311            triage_applied: Vec::new(),
1312            actions_applied: Vec::new(),
1313            decision_effects: Default::default(),
1314            superseded_resumes: Default::default(),
1315            dispatched_resumes: Default::default(),
1316            base_recovery_requests: Vec::new(),
1317            land_sync_recovery_requests: Vec::new(),
1318            resume_override: None,
1319            sync_only: None,
1320            repair_grants: Vec::new(),
1321            repair_reconciliations: Vec::new(),
1322            resumption: None,
1323            resumption_history: Vec::new(),
1324            operator_decided_at: None,
1325            review_branch: None,
1326            review_instruction: None,
1327            pr_recovery: None,
1328            fresh_start: false,
1329            replacement: None,
1330            interrupt: false,
1331            urgent: false,
1332            immediate: false,
1333            unfiled: true,
1334            attachments: Vec::new(),
1335            followup: None,
1336            origin_chat,
1337            overrides: None,
1338            review_of: None,
1339            held_at: None,
1340            park_reason: None,
1341            chat_notice: None,
1342            chat_notices: Vec::new(),
1343            hold_notice_cause: None,
1344            passes: Vec::new(),
1345            dispatched_at: None,
1346            recovery_budget: None,
1347            recovery_admission: None,
1348            recovery_generations: Vec::new(),
1349            created_at: now,
1350            updated_at: now,
1351        }
1352    }
1353
1354    /// Apply a validated idle-task assignment, preserving evidence and history.
1355    pub(crate) fn reassign_repository(&mut self, repo: PathBuf, actor: &str) {
1356        self.stamp_schema();
1357        if matches!(self.status, TaskStatus::Failed | TaskStatus::Parked) {
1358            self.hold_manual(Some(
1359                "Repository reassigned; inspect history and release to start fresh.".into(),
1360            ));
1361        }
1362        let at = Timestamp::now();
1363        self.reassignments.push(Reassignment {
1364            from: self.repo.clone(),
1365            to: repo.clone(),
1366            actor: actor.to_owned(),
1367            at,
1368            run_boundary: self.runs.len(),
1369        });
1370        self.repo = repo;
1371        self.review_branch = None;
1372        self.review_instruction = None;
1373        self.pr_recovery = None;
1374        self.replacement = None;
1375        self.interrupt = false;
1376        self.resume_override = None;
1377        self.fresh_start = true;
1378        self.operator_decided_at = Some(at);
1379    }
1380
1381    /// Public branch for the task's current repository assignment.
1382    pub fn publication_branch(&self) -> String {
1383        crate::run::task_pr_branch_name(&self.id, self.reassignments.len())
1384    }
1385
1386    /// Runs eligible for execution in the current assignment only.
1387    pub fn execution_runs(&self) -> &[String] {
1388        let boundary = self.reassignments.last().map_or(0, |r| r.run_boundary);
1389        self.runs.get(boundary..).unwrap_or_default()
1390    }
1391
1392    /// Attention for a completed task whose current Ready run owns a stale open PR.
1393    pub fn stale_pr_attention(&self, home: &Path) -> Option<String> {
1394        if self.status != TaskStatus::Done {
1395            return None;
1396        }
1397        let run = crate::run::RunState::load_under(self.execution_runs().last()?, home).ok()?;
1398        self.assignment_accepts(&run)
1399            .then(|| run.stale_pr_cause())
1400            .flatten()
1401    }
1402
1403    /// Whether a historical run still belongs to this execution assignment.
1404    pub fn execution_run(&self, run: &str) -> bool {
1405        self.execution_runs().iter().any(|id| id == run)
1406    }
1407
1408    /// Check both the assignment boundary and the saved repository before execution.
1409    pub(crate) fn assignment_accepts(&self, run: &crate::run::RunState) -> bool {
1410        self.reassignments.last().is_none_or(|boundary| {
1411            self.execution_run(&run.id)
1412                && run.task_assignment == self.reassignments.len()
1413                && run.created_at > boundary.at
1414                && run
1415                    .repo
1416                    .canonicalize()
1417                    .ok()
1418                    .zip(self.repo.canonicalize().ok())
1419                    .is_some_and(|(run_repo, task_repo)| run_repo == task_repo)
1420        })
1421    }
1422
1423    /// Questions issued before reassignment cannot control the new assignment.
1424    pub(crate) fn stale_question(&self, q: &crate::ask::Question) -> bool {
1425        self.reassignments
1426            .last()
1427            .is_some_and(|r| q.asked_at <= r.at)
1428            || (self.runs.contains(&q.run) && !self.execution_run(&q.run))
1429    }
1430
1431    /// The chat this task itself says it came from, including its original source.
1432    pub fn chat_talk(&self) -> Option<&str> {
1433        if let Some(id) = &self.origin_chat {
1434            return Some(id);
1435        }
1436        match &self.source {
1437            Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1438            _ => None,
1439        }
1440    }
1441
1442    /// The talk that filed this task *itself* (`Source::Agent` with
1443    /// [`CHAT_NODE`]); unlike [`Task::chat_talk`] a follow-up's inherited
1444    /// `origin_chat` does not count.
1445    pub fn filed_by_chat(&self) -> Option<&str> {
1446        match &self.source {
1447            Source::Agent { run, node } if node == CHAT_NODE => Some(run),
1448            _ => None,
1449        }
1450    }
1451
1452    /// Issue provenance, including legacy records that stored it as the actor.
1453    pub fn issue_ref(&self) -> Option<IssueRef> {
1454        self.issue.clone().or_else(|| match &self.source {
1455            Source::Issue { number, repo } => Some(IssueRef {
1456                number: *number,
1457                repo: repo.clone(),
1458            }),
1459            _ => None,
1460        })
1461    }
1462
1463    /// Filing actor and imported issue, when both are known.
1464    pub fn source_label(&self) -> String {
1465        let actor = self.source.label();
1466        match &self.issue {
1467            Some(issue) if self.source == Source::Human => format!("issue #{}", issue.number),
1468            Some(issue) => format!("{actor} · issue #{}", issue.number),
1469            None => actor,
1470        }
1471    }
1472
1473    /// Identity of a material outcome. Prose and wall-clock times are never
1474    /// evidence. Dependencies are a set; held causes survive intermediate states.
1475    pub fn chat_notice_key(&self) -> Option<String> {
1476        match self.status {
1477            TaskStatus::Done => Some(
1478                self.completion_history
1479                    .iter()
1480                    .rev()
1481                    .find(|event| event.action == CompletionAction::Complete)
1482                    .map_or_else(
1483                        || "done".to_owned(),
1484                        |event| format!("done:{}", event.occurrence),
1485                    ),
1486            ),
1487            TaskStatus::Held => {
1488                let cause = self
1489                    .hold_notice_cause
1490                    .clone()
1491                    .unwrap_or_else(|| self.unresolved_hold_cause());
1492                Some(format!(
1493                    "cause:{}",
1494                    serde_json::to_string(&cause).expect("cause")
1495                ))
1496            }
1497            TaskStatus::Blocked => {
1498                let ids: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
1499                // Only new verified blocking evidence versions the dependency
1500                // set. Freezing an unrelated hold on release must not do so.
1501                let evidence = self
1502                    .hold_notice_cause
1503                    .as_ref()
1504                    .filter(|c| c.stage.starts_with("conductor-evidence:"));
1505                Some(format!(
1506                    "dependencies:{}",
1507                    serde_json::to_string(&(ids, evidence)).expect("ids")
1508                ))
1509            }
1510            _ => None,
1511        }
1512    }
1513
1514    fn unresolved_hold_cause(&self) -> NoticeCause {
1515        NoticeCause {
1516            stage: "hold".into(),
1517            target: None,
1518            run: self.runs.last().cloned(),
1519            pass: None,
1520        }
1521    }
1522
1523    /// Exact old delivery identity, only for reconciling an existing record.
1524    pub(crate) fn legacy_chat_notice_key(&self) -> Option<String> {
1525        let key = match self.status {
1526            TaskStatus::Held if self.hold_notice_cause.is_none() => Some(format!(
1527                "held#{}",
1528                self.held_at.map(|t| t.to_string()).unwrap_or_default()
1529            )),
1530            TaskStatus::Blocked => Some(format!(
1531                "blocked#{}#{}",
1532                self.blocked_by.join(","),
1533                self.block_reason.as_deref().unwrap_or_default()
1534            )),
1535            _ => None,
1536        };
1537        key.filter(|key| self.legacy_notice_matches(key))
1538    }
1539
1540    pub(crate) fn legacy_notice_matches(&self, key: &str) -> bool {
1541        match self.status {
1542            TaskStatus::Held if self.hold_notice_cause.is_none() => key
1543                .strip_prefix("held#")
1544                .is_some_and(|time| time.is_empty() || time.parse::<Timestamp>().is_ok()),
1545            TaskStatus::Blocked
1546                if self
1547                    .hold_notice_cause
1548                    .as_ref()
1549                    .is_none_or(|c| !c.stage.starts_with("conductor-evidence:")) =>
1550            {
1551                key.strip_prefix("blocked#").is_some_and(|tail| {
1552                    let Some((ids, _)) = tail.split_once('#') else {
1553                        return false;
1554                    };
1555                    let old: std::collections::BTreeSet<_> =
1556                        ids.split(',').filter(|id| !id.is_empty()).collect();
1557                    let current: std::collections::BTreeSet<_> =
1558                        self.blocked_by.iter().map(String::as_str).collect();
1559                    old == current
1560                })
1561            }
1562            _ => false,
1563        }
1564    }
1565
1566    fn import_chat_notice(&mut self) {
1567        if let Some(n) = &self.chat_notice {
1568            let key = if is_done_notice_key(&n.key) {
1569                "done".to_owned()
1570            } else if self.legacy_notice_matches(&n.key) {
1571                self.chat_notice_key().unwrap_or_else(|| n.key.clone())
1572            } else {
1573                n.key.clone()
1574            };
1575            if !self.chat_notices.contains(&key) {
1576                self.chat_notices.push(key);
1577            }
1578        }
1579    }
1580
1581    /// A producer records the processing stage and actual run/pass, never the
1582    /// error's rendered prose. No run means startup made no implementation progress.
1583    pub(crate) fn notice_cause(&mut self, stage: &str, run: Option<&str>, pass: Option<usize>) {
1584        self.import_chat_notice();
1585        self.hold_notice_cause = Some(NoticeCause {
1586            stage: stage.to_owned(),
1587            target: None,
1588            run: run.map(str::to_owned),
1589            pass,
1590        });
1591    }
1592
1593    /// Startup retries cannot replace an unresolved run outcome without doing
1594    /// work. Distinct startup stages can still explain a newly encountered blocker.
1595    pub(crate) fn startup_notice_cause(&mut self, stage: &str) {
1596        let recovery_only = matches!(
1597            stage,
1598            "startup-source" | "startup-candidates" | "startup-public-head"
1599        );
1600        match self.hold_notice_cause.as_ref() {
1601            Some(cause) if recovery_only && !cause.stage.starts_with("startup-") => return,
1602            None if recovery_only
1603                && self
1604                    .chat_notice
1605                    .as_ref()
1606                    .is_some_and(|n| !is_done_notice_key(&n.key)) =>
1607            {
1608                return;
1609            }
1610            _ => {}
1611        }
1612        self.notice_cause(stage, None, None);
1613    }
1614
1615    /// Apply a preflight failure without allowing Running's generic failure
1616    /// identity to overwrite the producer's stage or its unresolved recovery anchor.
1617    pub(crate) fn fail_startup(
1618        &mut self,
1619        stage: &str,
1620        why: impl Into<String>,
1621        max_attempts: usize,
1622    ) {
1623        let unresolved = self.hold_notice_cause.clone();
1624        self.fail(why, max_attempts);
1625        self.hold_notice_cause = unresolved;
1626        self.startup_notice_cause(stage);
1627    }
1628
1629    /// A startup failure tied to a concrete object, such as a missing attachment.
1630    pub(crate) fn fail_startup_target(
1631        &mut self,
1632        stage: &str,
1633        target: String,
1634        why: impl Into<String>,
1635        max_attempts: usize,
1636    ) {
1637        self.fail_startup(stage, why, max_attempts);
1638        if let Some(cause) = self.hold_notice_cause.as_mut() {
1639            cause.target = Some(target);
1640        }
1641    }
1642
1643    /// A chat-filed task owes each material final outcome at most one notice.
1644    pub fn chat_notice_due(&self) -> Option<String> {
1645        self.filed_by_chat()?;
1646        if self.schema < 13 {
1647            return None;
1648        }
1649        let key = self.chat_notice_key()?;
1650        if self.chat_notices.contains(&key) {
1651            return None;
1652        }
1653        match &self.chat_notice {
1654            Some(n)
1655                if n.key == key
1656                    || (key == "done" && is_done_notice_key(&n.key))
1657                    || self.legacy_notice_matches(&n.key) =>
1658            {
1659                None
1660            }
1661            _ => Some(key),
1662        }
1663    }
1664
1665    /// Short form used in reports, matching a run's short id.
1666    pub fn short(&self) -> &str {
1667        short(&self.id)
1668    }
1669
1670    /// Record that triage question `question_id`'s answer has been applied.
1671    pub fn mark_triage_applied(&mut self, question_id: &str) {
1672        if !self.triage_applied(question_id) {
1673            self.triage_applied.push(question_id.to_owned());
1674        }
1675    }
1676
1677    /// Has the action of `magi ask` question `question_id` already been
1678    /// applied, or is it being applied now? See [`Task::actions_applied`].
1679    pub fn action_applied(&self, question_id: &str) -> bool {
1680        self.actions_applied.iter().any(|id| id == question_id)
1681    }
1682
1683    /// Record that `magi ask` question `question_id`'s action was applied.
1684    pub fn mark_action_applied(&mut self, question_id: &str) {
1685        if !self.action_applied(question_id) {
1686            self.actions_applied.push(question_id.to_owned());
1687        }
1688    }
1689
1690    /// Has triage question `question_id`'s answer already been applied?
1691    pub fn triage_applied(&self, question_id: &str) -> bool {
1692        self.triage_applied.iter().any(|id| id == question_id)
1693    }
1694
1695    /// Record that a run has started for this task.
1696    /// Move an already linked run to the end so it remains the current attempt,
1697    /// with one history entry per run and separate pass records for each resume.
1698    ///
1699    /// Clears [`Task::interrupt`]: a mark to run ahead of whatever else is
1700    /// in flight is fulfilled the moment this task actually gets its turn,
1701    /// dispatched same as any other. Without this, a task whose run fails
1702    /// and requeues - still `runnable`, still carrying the mark from its
1703    /// first attempt - would keep re-triggering `crate::daemon`'s interrupt
1704    /// scheduler and re-parking whatever it interrupted on every later
1705    /// boundary, for as long as its attempts hold out, instead of the
1706    /// one-shot "let this go next" the mark is meant to be.
1707    pub fn start(&mut self, run: String) {
1708        self.stamp_schema();
1709        self.status = TaskStatus::Running;
1710        self.attempts += 1;
1711        self.runs.retain(|id| id != &run);
1712        if let Some(pin) = &self.resume_override
1713            && pin.pinned_run.as_ref() == Some(&run)
1714            && !pin.question_id.is_empty()
1715        {
1716            self.dispatched_resumes
1717                .insert(pin.question_id.clone(), run.clone());
1718        }
1719        self.runs.push(run);
1720        self.last_error = None;
1721        self.park_reason = None;
1722        self.fresh_start = false;
1723        self.interrupt = false;
1724        // The answer has been honoured: the task got its turn.
1725        self.resume_override = None;
1726        // The automatic disk recovery pin is consumed by this start; a later
1727        // failure and requeue must retry normally.
1728        self.disk_resume_run = None;
1729    }
1730
1731    /// Attribute a failed reservation once without spending an execution attempt.
1732    pub fn record_startup_failure(&mut self, failure: crate::run::StartupFailure) {
1733        if !self.startup_failures.iter().any(|f| f.run == failure.run) {
1734            self.startup_failures.push(failure);
1735        }
1736    }
1737
1738    /// Note that `run` serves this task without otherwise changing its life:
1739    /// no status, attempt or interrupt change, unlike [`Task::start`]. For a
1740    /// run somebody else started on the task's behalf (`magi run --task`);
1741    /// idempotent. Returns whether anything was added.
1742    pub fn link_run(&mut self, run: &str) -> bool {
1743        if self.runs.iter().any(|r| r == run) {
1744            return false;
1745        }
1746        self.runs.push(run.to_owned());
1747        true
1748    }
1749
1750    /// Record a successful run.
1751    ///
1752    /// Both `magi task done` and `POST /api/queue/{id}/done` can close a held
1753    /// *or blocked* task directly, with no release in between, so this clears
1754    /// `hold_reason` and `blocked_by`/`block_reason` the same way
1755    /// [`Task::release`] does. Otherwise a task held for "waiting on 3ed9", or
1756    /// blocked on a dependency that never actually finished, and then closed
1757    /// as done without ever being released would still read as waiting on
1758    /// something in `magi task show` and on its card, after it no longer is.
1759    pub fn succeed(&mut self, context: CompletionContext) {
1760        if self.status == TaskStatus::Done {
1761            return;
1762        }
1763        self.record_completion(CompletionAction::Complete, context);
1764        self.stamp_schema();
1765        self.status = TaskStatus::Done;
1766        if let Some(pin) = self.resume_override.take()
1767            && !pin.question_id.is_empty()
1768            && let Some(run) = pin.pinned_run
1769        {
1770            // Completion cancels a queued request; normal dispatch records its
1771            // start separately and must not be mistaken for supersession.
1772            self.superseded_resumes.insert(pin.question_id, run);
1773        }
1774        self.sync_only = None;
1775        self.last_error = None;
1776        self.park_reason = None;
1777        self.hold_reason = None;
1778        self.hold_source = None;
1779        self.machine_hold_cause = None;
1780        self.disk_resume_run = None;
1781        self.disk_checked_at = None;
1782        self.diagnostic = None;
1783        self.blocked_by.clear();
1784        self.block_reason = None;
1785        self.blocked_from = None;
1786    }
1787
1788    /// Finish the task because the run's whole change turned out to be on the
1789    /// base already ([`crate::run::RunStatus::AlreadyInBase`]): `Done`, with
1790    /// `note` kept in [`Task::last_error`] so `magi task show` says why, and
1791    /// the attempt refunded. Nothing went wrong and nothing was spent
1792    /// misbehaving, so this is neither [`Task::fail`] nor
1793    /// [`Task::handed_off`]; and unlike [`Task::succeed`] it does not pretend
1794    /// the run landed anything.
1795    pub fn already_landed(&mut self, note: impl Into<String>, mut context: CompletionContext) {
1796        let note = note.into();
1797        if context.reason.is_none() {
1798            context.reason = Some(note.clone());
1799        }
1800        self.succeed(context);
1801        self.attempts = self.attempts.saturating_sub(1);
1802        self.last_error = Some(note);
1803    }
1804
1805    fn record_completion(&mut self, action: CompletionAction, context: CompletionContext) {
1806        self.completion_history.push(CompletionEvent {
1807            occurrence: format!(
1808                "{}-{:016x}{:016x}",
1809                Timestamp::now(),
1810                crate::rng::entropy(),
1811                crate::rng::entropy()
1812            ),
1813            action,
1814            actor: context.actor,
1815            reason: context.reason,
1816            discard: context.discard,
1817            prior_status: self.status,
1818            at: Timestamp::now(),
1819            prior_hold_reason: self.hold_reason.clone(),
1820            prior_block_reason: self.block_reason.clone(),
1821            prior_error: self.last_error.clone(),
1822            run: context.run,
1823            unavailable_runs: context.unavailable_runs,
1824        });
1825        self.stamp_schema();
1826    }
1827
1828    /// Reopen a completed task into a hold after transactional admission.
1829    /// Release remains a separate operator decision.
1830    pub fn reopen(&mut self, context: CompletionContext) -> Result<()> {
1831        anyhow::ensure!(
1832            self.status == TaskStatus::Done,
1833            "only a done task can be reopened"
1834        );
1835        anyhow::ensure!(
1836            context
1837                .reason
1838                .as_deref()
1839                .is_some_and(|reason| !reason.trim().is_empty()),
1840            "reopen requires a non-empty reason"
1841        );
1842        let reason = context.reason.clone();
1843        self.record_completion(CompletionAction::Reopen, context);
1844        self.hold_manual(reason);
1845        self.resume_override = None;
1846        self.reopen_hold =
1847            self.held_at
1848                .zip(self.completion_history.last())
1849                .map(|(held_at, event)| ReopenHold {
1850                    occurrence: event.occurrence.clone(),
1851                    held_at,
1852                    decision: self.operator_decided_at,
1853                    legacy: false,
1854                });
1855        self.fresh_start = false;
1856        self.last_error = None;
1857        self.diagnostic = None;
1858        Ok(())
1859    }
1860
1861    /// Earlier attempts at this task that a later one has since made moot —
1862    /// empty unless the task is [`TaskStatus::Done`] *and* `last_run_succeeded`
1863    /// says `runs.last()` is actually why.
1864    ///
1865    /// `runs` is oldest first, and [`Task::start`] is the only thing that
1866    /// pushes to it, always right before the attempt it names either succeeds
1867    /// or fails; `succeed` itself never touches `runs`. So whenever `status`
1868    /// is `Done` *because* the loop itself saw that last attempt land
1869    /// (`Merged`/`Ready`), everything before it in the same list is a retry
1870    /// this task no longer needs. But `succeed` is also reachable directly —
1871    /// `magi task done`, the web UI's equivalent, and the conductor's
1872    /// `Recovery::Done` all call it on a task in *any* status, including one
1873    /// whose last recorded attempt never landed at all (closed by hand after
1874    /// a merge magi's own loop never saw). `runs.last()` alone cannot tell
1875    /// those two cases apart — that requires the caller to have actually
1876    /// looked at that run's own `status`, which this module has no way to
1877    /// do — so `last_run_succeeded` is the caller's answer to exactly that
1878    /// question, not something this function can derive from `Task` alone.
1879    ///
1880    /// Deliberately narrower than [`Queue::superseded`]'s "every earlier
1881    /// attempt has a later one" walk, which fires the moment a retry starts
1882    /// even though the retry itself might still fail: that reading is right
1883    /// for the web UI's "a newer attempt exists, go look at that one
1884    /// instead" note, but wrong for deciding a run no longer needs a human's
1885    /// attention, which is only true once the task's story has actually
1886    /// ended well. Two Blocked runs sitting side by side while a third
1887    /// attempt is still in flight must not be touched by this — see
1888    /// `daemon::supersede_prior_runs`, the caller that turns this list into
1889    /// rewritten `run.json` files.
1890    pub fn superseded_attempts(&self, last_run_succeeded: bool) -> &[String] {
1891        if self.status != TaskStatus::Done || !last_run_succeeded || self.execution_runs().len() < 2
1892        {
1893            return &[];
1894        }
1895        &self.execution_runs()[..self.execution_runs().len() - 1]
1896    }
1897
1898    /// The attempt right after the last occurrence of `run`, if there is one.
1899    /// Resuming records the same run again; it cannot supersede itself.
1900    ///
1901    /// The one place "a later attempt replaced this run" is decided:
1902    /// [`Queue::superseded`] and [`Queue::superseded_by`] (the web UI's
1903    /// note) read it, and so does [`Task::earlier_attempts`], so what is shown
1904    /// and what `crate::handover` acts on cannot disagree.
1905    pub fn successor_of(&self, run: &str) -> Option<&String> {
1906        let runs = self.execution_runs();
1907        let pos = runs.iter().rposition(|r| r == run)?;
1908        runs.get(pos + 1)
1909    }
1910
1911    /// Every run in this assignment, i.e. every run that an
1912    /// attempt being minted *right now* supersedes.
1913    ///
1914    /// The new run is not in [`Task::runs`] yet when it decides what to take
1915    /// over (`Task::start` pushes it afterwards), so "has a later attempt" is
1916    /// true of everything listed here by the time the new run exists.
1917    pub fn earlier_attempts(&self) -> &[String] {
1918        self.execution_runs()
1919    }
1920
1921    fn preserve_legacy_build_cache(&mut self) {
1922        if self.schema < 23 {
1923            let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
1924                inherit_daemon_options: true,
1925                ..RunOverrides::default()
1926            });
1927            overrides.build_cache.get_or_insert(BuildCache::Shared);
1928        }
1929    }
1930
1931    /// A transition this build makes (start, hold, block, done) makes the task
1932    /// eligible for a chat notice even when it was filed under an older
1933    /// schema; only records no build has touched since stay silent
1934    /// ([`Task::chat_notice_due`]).
1935    fn stamp_schema(&mut self) {
1936        self.preserve_legacy_build_cache();
1937        if self.schema < RECOVERY_HOLD_SCHEMA && self.recovery_budget_hold.is_none() {
1938            self.recovery_budget_hold = self.legacy_recovery_budget_hold();
1939        }
1940        self.snapshot_legacy_reopen_hold();
1941        self.schema = self.schema.max(SCHEMA);
1942    }
1943
1944    /// Stamp [`Task::held_at`] on the way into [`TaskStatus::Held`]; a task
1945    /// that is already held keeps the time its hold began.
1946    fn note_held(&mut self) {
1947        self.stamp_schema();
1948        self.recovery_budget_hold = None;
1949        self.reopen_hold = None;
1950        let continuing = self.status == TaskStatus::Held
1951            || (self.status == TaskStatus::Blocked
1952                && (self.blocked_from == Some(TaskStatus::Held)
1953                    || (self.blocked_from.is_none()
1954                        && (self.hold_reason.is_some() || self.hold_source.is_some()))));
1955        if !continuing || self.held_at.is_none() {
1956            self.held_at = Some(Timestamp::now());
1957        }
1958    }
1959
1960    /// Record a failed attempt. Out of attempts means held for a human, rather
1961    /// than retried until the money runs out.
1962    ///
1963    /// Clears [`Task::diagnostic`] unconditionally: it belongs to whatever run
1964    /// produced it, and a caller that has one for *this* attempt sets it
1965    /// itself right after calling this, once it knows the task actually ended
1966    /// up [`TaskStatus::Held`] - see `daemon::diagnostic`. Without the clear, a
1967    /// task released after a diagnosed hold and then failed again for an
1968    /// unrelated, undiagnosed reason (a config error, say) would go on
1969    /// showing the previous run's diagnostic as if it explained the new one.
1970    ///
1971    /// Also records `why` into [`Task::hold_reason`] when this ends up
1972    /// [`TaskStatus::Held`], so the notification and `magi task show` say the
1973    /// same thing as [`Task::last_error`] instead of leaving the hold's own
1974    /// reason blank.
1975    pub fn fail(&mut self, why: impl Into<String>, max_attempts: usize) {
1976        let why = why.into();
1977        if self.status == TaskStatus::Running {
1978            let run = self.runs.last().cloned();
1979            self.notice_cause("run-failed", run.as_deref(), Some(self.attempts));
1980        }
1981        self.diagnostic = None;
1982        self.park_reason = None;
1983        self.status = if self.attempts >= self.effective_attempt_limit(max_attempts) {
1984            self.note_held();
1985            self.hold_source = Some(HoldSource::Machine);
1986            self.machine_hold_cause = None;
1987            self.disk_resume_run = None;
1988            self.disk_checked_at = None;
1989            self.hold_reason = Some(why.clone());
1990            TaskStatus::Held
1991        } else {
1992            TaskStatus::Failed
1993        };
1994        self.last_error = Some(why);
1995    }
1996
1997    /// Record an attempt that failed for a reason the task is not responsible
1998    /// for - the agent CLIs ran out of quota and the judging panel collapsed.
1999    ///
2000    /// This refunds the attempt on purpose. A quota window closing at 4am must
2001    /// not spend the backlog's retry budget: the operator would come back to a
2002    /// queue of held tasks that were never actually judged, and would have to
2003    /// release every one by hand to find out which had a real problem. The task
2004    /// goes back to `Failed`, which the loop retries, so a reset quota picks the
2005    /// work up where it stopped.
2006    pub fn stall(&mut self, why: impl Into<String>) {
2007        self.last_error = Some(why.into());
2008        self.diagnostic = None;
2009        self.attempts = self.attempts.saturating_sub(1);
2010        self.status = TaskStatus::Failed;
2011    }
2012
2013    /// Record a run that parked at a node boundary. Nothing failed: the attempt
2014    /// is refunded, [`Task::last_error`] is left as it was, the run history and
2015    /// `fresh_start` are kept so the next loop resumes the same run, and the
2016    /// reason goes to [`Task::park_reason`]. Runnable like a requeued task and
2017    /// never counted against `max_attempts`.
2018    pub fn park(&mut self, why: impl Into<String>) {
2019        self.diagnostic = None;
2020        self.attempts = self.attempts.saturating_sub(1);
2021        self.status = TaskStatus::Parked;
2022        self.park_reason = Some(why.into());
2023        // The variant and field are schema 11; stamp it so an older build
2024        // refuses the record instead of half-reading it.
2025        self.stamp_schema();
2026    }
2027
2028    /// Record a settled pass whose start time is unknown (see [`Self::record_pass_at`]).
2029    pub fn record_pass(
2030        &mut self,
2031        run: &str,
2032        pass_index: usize,
2033        attempts_before: usize,
2034        parked: Option<crate::run::ParkCause>,
2035    ) {
2036        self.record_pass_at(run, pass_index, None, attempts_before, parked);
2037    }
2038
2039    /// Record a settled pass. `attempts_before` is the count just before the
2040    /// settle, so a refund is read off what actually changed, not inferred.
2041    pub fn record_pass_at(
2042        &mut self,
2043        run: &str,
2044        pass_index: usize,
2045        started_at: Option<Timestamp>,
2046        attempts_before: usize,
2047        parked: Option<crate::run::ParkCause>,
2048    ) {
2049        if self
2050            .passes
2051            .iter()
2052            .any(|p| p.run == run && p.pass_index == pass_index)
2053        {
2054            return;
2055        }
2056        let cost = if self.attempts < attempts_before {
2057            PassCost::Refunded
2058        } else {
2059            PassCost::Spent
2060        };
2061        self.passes.push(TaskPass {
2062            run: run.to_owned(),
2063            pass_index,
2064            started_at: self.dispatched_at.or(started_at),
2065            cost,
2066            attempts_after: self.attempts,
2067            settled_at: Timestamp::now(),
2068            parked,
2069        });
2070        self.stamp_schema();
2071    }
2072
2073    /// Only the latest pass of the current, resumable upgrade-parked run
2074    /// retains its place. Explicit fresh starts and other park causes do not.
2075    pub(crate) fn upgrade_resume_key(&self) -> Option<(Timestamp, &str)> {
2076        if self.status != TaskStatus::Parked || self.fresh_start {
2077            return None;
2078        }
2079        let pass = self.passes.last()?;
2080        if self.execution_runs().last() != Some(&pass.run)
2081            || !matches!(pass.parked, Some(crate::run::ParkCause::Upgrade { .. }))
2082        {
2083            return None;
2084        }
2085        // Before schema 19 the dispatch start was not copied to the task.
2086        // Settlement time is only an approximation for those old records.
2087        Some((pass.started_at.unwrap_or(pass.settled_at), &self.id))
2088    }
2089
2090    /// Whether this held task may only be released by an operator.
2091    ///
2092    /// Old files did not record a source. Preserve every such hold rather
2093    /// than guessing that it was automatic and risking duplicate work. New
2094    /// automatic holds record [`HoldSource::Machine`] and remain recoverable.
2095    pub fn operator_held(&self) -> bool {
2096        self.status == TaskStatus::Held && !matches!(self.hold_source, Some(HoldSource::Machine))
2097    }
2098
2099    /// Take this task out of the loop's reach by an operator action.
2100    ///
2101    /// Clears `blocked_by`/`block_reason` unconditionally, the same as
2102    /// [`Task::release`] and for the same reason its own comment already
2103    /// gives: a human choosing to hold a *blocked* task overrides its wait
2104    /// outright, the same as it overrides an ordinary hold. Without this, a
2105    /// task held straight out of [`TaskStatus::Blocked`] - the web UI's "Hold"
2106    /// button is reachable on a blocked task, same as "Mark done" - kept
2107    /// reading as still waiting on a dependency it no longer had any claim on.
2108    pub fn hold_manual(&mut self, reason: Option<String>) {
2109        // A later explicit hold supersedes outstanding triage answers.
2110        self.operator_decided_at = Some(Timestamp::now());
2111        if self.status != TaskStatus::Running && self.sync_only.take().is_some() {
2112            self.resume_override = None;
2113        }
2114        self.hold_unrequested_retry(reason);
2115    }
2116
2117    /// Keep a hand-started run from retrying automatically, without recording
2118    /// an operator decision that could invalidate its outstanding questions.
2119    pub(crate) fn hold_unrequested_retry(&mut self, reason: Option<String>) {
2120        self.park_reason = None;
2121        self.note_held();
2122        self.status = TaskStatus::Held;
2123        if reason.is_some() {
2124            self.hold_reason = reason;
2125        }
2126        self.hold_source = Some(HoldSource::Manual);
2127        self.machine_hold_cause = None;
2128        self.disk_resume_run = None;
2129        self.disk_checked_at = None;
2130        self.blocked_by.clear();
2131        self.block_reason = None;
2132        self.blocked_from = None;
2133    }
2134
2135    pub(crate) fn hold_after_sync_only(&mut self, reason: String) {
2136        let recovery_hold = self.recovery_budget_hold.take();
2137        self.hold_unrequested_retry(Some(reason));
2138        self.recovery_budget_hold = recovery_hold;
2139    }
2140
2141    /// Take this task out of the loop's reach during automatic recovery.
2142    ///
2143    /// Clears `blocked_by`/`block_reason` for the same reason
2144    /// [`Task::hold_manual`] does.
2145    pub fn hold_machine(&mut self, reason: Option<String>) {
2146        self.park_reason = None;
2147        self.note_held();
2148        self.status = TaskStatus::Held;
2149        if reason.is_some() {
2150            self.hold_reason = reason;
2151        }
2152        self.hold_source = Some(HoldSource::Machine);
2153        self.machine_hold_cause = None;
2154        self.disk_resume_run = None;
2155        self.disk_checked_at = None;
2156        self.blocked_by.clear();
2157        self.block_reason = None;
2158        self.blocked_from = None;
2159    }
2160
2161    /// Record the disk-capacity cause bound to the current `hold_reason`.
2162    pub(crate) fn mark_disk_capacity(&mut self) {
2163        self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2164            reason: self.hold_reason.clone().unwrap_or_default(),
2165            before_start: false,
2166        });
2167    }
2168
2169    pub(crate) fn mark_startup_disk_capacity(&mut self) {
2170        self.machine_hold_cause = Some(MachineHoldCause::DiskCapacity {
2171            reason: self.hold_reason.clone().unwrap_or_default(),
2172            before_start: true,
2173        });
2174    }
2175
2176    pub(crate) fn disk_wait_run(&self) -> Option<&String> {
2177        if self.has_disk_capacity_cause()
2178            && matches!(
2179                self.machine_hold_cause,
2180                Some(MachineHoldCause::DiskCapacity {
2181                    before_start: true,
2182                    ..
2183                })
2184            )
2185        {
2186            None
2187        } else {
2188            self.execution_runs().last()
2189        }
2190    }
2191
2192    /// Does the structured disk-capacity cause still match the current hold?
2193    pub fn has_disk_capacity_cause(&self) -> bool {
2194        matches!(
2195            (&self.machine_hold_cause, self.hold_reason.as_deref()),
2196            (Some(MachineHoldCause::DiskCapacity { reason, .. }), Some(now)) if reason == now
2197        )
2198    }
2199
2200    /// Admission waits preserve all execution and approval evidence on recovery.
2201    pub(crate) fn resume_disk_wait(&mut self) {
2202        let retained = self.disk_wait_run().cloned();
2203        self.status = TaskStatus::Queued;
2204        self.held_at = None;
2205        self.hold_source = None;
2206        self.hold_reason = None;
2207        self.machine_hold_cause = None;
2208        self.last_error = None;
2209        self.disk_resume_run = retained;
2210    }
2211
2212    /// Hold this task at one actionable machine hold for a conclusive `head_e2e` failure.
2213    pub(crate) fn hold_head_e2e(
2214        &mut self,
2215        stop: crate::head_e2e_stop::Stop,
2216        reason: String,
2217        last_error: String,
2218    ) {
2219        self.hold_machine(Some(reason));
2220        self.last_error = Some(last_error);
2221        self.machine_hold_cause = Some(MachineHoldCause::HeadE2e { stop });
2222    }
2223
2224    /// Keep a conclusive `head_e2e` stop identity stable across passes and re-holds.
2225    pub(crate) fn head_e2e_notice(&mut self, stop: &crate::head_e2e_stop::Stop) {
2226        if let Some(at) = stop.recorded_at {
2227            self.held_at = Some(at);
2228        }
2229        self.notice_cause(crate::head_e2e_stop::NOTICE_STAGE, Some(&stop.run), None);
2230        if let Some(cause) = &mut self.hold_notice_cause {
2231            cause.target = Some(stop.id.clone());
2232        }
2233    }
2234
2235    /// Whether this task currently carries a typed conclusive `head_e2e` hold cause.
2236    pub fn has_head_e2e_cause(&self) -> bool {
2237        matches!(
2238            self.machine_hold_cause,
2239            Some(MachineHoldCause::HeadE2e { .. })
2240        )
2241    }
2242
2243    /// Stable stop identifier when this task is held on a conclusive `head_e2e` failure.
2244    pub fn head_e2e_stop_id(&self) -> Option<&str> {
2245        if let Some(MachineHoldCause::HeadE2e { stop }) = &self.machine_hold_cause {
2246            return Some(stop.id.as_str());
2247        }
2248        self.hold_notice_cause
2249            .as_ref()
2250            .filter(|c| c.stage == crate::head_e2e_stop::NOTICE_STAGE)
2251            .and_then(|c| c.target.as_deref())
2252    }
2253
2254    /// Requeue a `head_e2e` hold after candidate/base/repair facts changed,
2255    /// preserving spent attempts and run/pass history.
2256    pub(crate) fn resume_head_e2e_wait(&mut self) {
2257        self.status = TaskStatus::Queued;
2258        self.held_at = None;
2259        self.hold_source = None;
2260        self.hold_reason = None;
2261        self.machine_hold_cause = None;
2262        self.last_error = None;
2263        self.diagnostic = None;
2264        self.blocked_by.clear();
2265        self.block_reason = None;
2266        self.blocked_from = None;
2267    }
2268
2269    /// Block this task on other task ids and/or open question ids, chosen by
2270    /// `crate::conduct`. Pure: the caller still owns writing it back with
2271    /// [`Queue::put`].
2272    ///
2273    /// Records [`Task::blocked_from`] the first time this moves the task into
2274    /// [`TaskStatus::Blocked`], and leaves it alone on a later call that adds
2275    /// or replaces `blocked_by` while the task is already `Blocked` - a
2276    /// second question about an already-blocked task must not overwrite the
2277    /// status it should eventually return to with `Blocked` itself.
2278    pub fn block(&mut self, blocked_by: Vec<String>, reason: Option<String>) {
2279        self.stamp_schema();
2280        let before: std::collections::BTreeSet<_> = self.blocked_by.iter().collect();
2281        let after: std::collections::BTreeSet<_> = blocked_by.iter().collect();
2282        if self.status != TaskStatus::Blocked || before != after {
2283            self.blocked_at = Some(Timestamp::now());
2284        }
2285        if self.status != TaskStatus::Blocked {
2286            self.blocked_from = Some(self.status);
2287        }
2288        self.status = TaskStatus::Blocked;
2289        self.blocked_by = blocked_by;
2290        self.block_reason = reason;
2291    }
2292
2293    /// Remove one resolved dependency (a task id that became [`TaskStatus::Done`],
2294    /// or a question id that became [`crate::ask::QuestionStatus::Answered`]).
2295    /// Once nothing is left in [`Task::blocked_by`], the task returns to
2296    /// whatever [`Task::blocked_from`] recorded - deciding *why* a task was
2297    /// blocked was `crate::conduct`'s job, but noticing a dependency resolved
2298    /// needs no model at all, and restoring the status it interrupted needs
2299    /// nothing more than what `block` already wrote down.
2300    ///
2301    /// A task blocked while `Running` restores to [`TaskStatus::Queued`]
2302    /// instead: whatever process was running it is gone by the time this
2303    /// runs, so there is nothing left to resume. A task with no recorded
2304    /// `blocked_from` - a pre-schema-4 record, or one blocked before this
2305    /// field existed - falls back to [`TaskStatus::Held`] when it still
2306    /// carries hold evidence ([`Task::hold_reason`] or [`Task::hold_source`],
2307    /// neither ever cleared by `block`), and to `Queued` otherwise: the same
2308    /// choice `block` itself would have recorded, reconstructed from what
2309    /// survived.
2310    ///
2311    /// A no-op, on purpose, for a task that is not [`TaskStatus::Blocked`]:
2312    /// `crate::daemon`'s deterministic resolver runs over every task on every
2313    /// poll, and a task that moved on for some other reason must not be
2314    /// dragged back by a stale id it still happens to carry.
2315    pub fn unblock(&mut self, resolved_id: &str) {
2316        if self.status != TaskStatus::Blocked {
2317            return;
2318        }
2319        self.blocked_by.retain(|id| id != resolved_id);
2320        self.restore_if_unblocked();
2321    }
2322
2323    /// A dependency this task waited on was deleted on purpose
2324    /// ([`Queue::remove`]): drop just that id from [`Task::blocked_by`] and,
2325    /// once nothing is left, return to the status the block interrupted, the
2326    /// same way [`Task::unblock`] does. Returns whether anything changed.
2327    ///
2328    /// Never a hold: the operator chose the deletion, so the dependent is not
2329    /// in trouble. Touches nothing but a `Blocked` task that actually names
2330    /// `deleted_id`, so a `Held` task (or a manual hold) is left exactly as it
2331    /// was. A dependency that vanished *without* going through a deletion is
2332    /// not this method's case - that stays a machine hold.
2333    pub fn dependency_deleted(&mut self, deleted_id: &str) -> bool {
2334        if self.status != TaskStatus::Blocked || !self.blocked_by.iter().any(|b| b == deleted_id) {
2335            return false;
2336        }
2337        self.blocked_by.retain(|id| id != deleted_id);
2338        self.restore_if_unblocked();
2339        true
2340    }
2341
2342    /// The shared tail of [`Task::unblock`] and [`Task::dependency_deleted`]:
2343    /// with nothing left in `blocked_by`, restore the interrupted status and
2344    /// clear the now-stale block bookkeeping.
2345    fn restore_if_unblocked(&mut self) {
2346        if self.blocked_by.is_empty() {
2347            self.status = match self.blocked_from {
2348                Some(TaskStatus::Running) => TaskStatus::Queued,
2349                Some(other) => other,
2350                None if self.hold_reason.is_some() || self.hold_source.is_some() => {
2351                    TaskStatus::Held
2352                }
2353                None => TaskStatus::Queued,
2354            };
2355            self.block_reason = None;
2356            self.blocked_from = None;
2357        }
2358    }
2359
2360    /// Record that a question `crate::conduct` asked about this task has been
2361    /// answered, so the answer's content — not just the fact that the
2362    /// question is gone — reaches the next conductor prompt and the next
2363    /// run's instruction. See [`Task::answers`].
2364    pub fn record_answer(&mut self, question: String, answer: String) {
2365        self.answers.push(AnsweredQuestion { question, answer });
2366    }
2367
2368    /// Requeue this task to reopen its last run as a review-only pass against
2369    /// `branch` (`crate::graph::Runner::review`) rather than competing from
2370    /// scratch. See [`Task::review_branch`].
2371    pub fn request_review(&mut self, branch: String) {
2372        self.release();
2373        self.review_branch = Some(branch);
2374        self.review_instruction = Some(self.instruction.clone());
2375    }
2376
2377    /// Requeue after a conductor chose a new competition. Unlike an ordinary
2378    /// operator release, this deliberately does not resume the old run.
2379    pub fn requeue(&mut self) {
2380        self.release();
2381        // A fresh competition is the opposite of a review of the old branch.
2382        self.review_branch = None;
2383        self.review_instruction = None;
2384        self.fresh_start = true;
2385    }
2386
2387    /// Hold this task because a takeover of `branch` was refused, keeping
2388    /// [`Task::review_branch`] so that once the operator has cleaned up and
2389    /// released it, the retry is a review of the same branch rather than a
2390    /// resume or a fresh competition. Spends no attempt.
2391    ///
2392    /// This is the only way a machine hold keeps a `review_branch`: the
2393    /// daemon takes it at the start of every attempt, so [`Task::release`]
2394    /// relies on that to tell this hold from every other.
2395    pub fn hold_for_handover(&mut self, branch: Option<String>, reason: String) {
2396        if branch.is_some() {
2397            self.review_branch = branch;
2398            self.review_instruction = Some(self.instruction.clone());
2399        }
2400        self.hold_machine(Some(reason));
2401    }
2402
2403    /// Change the urgent lane setting without releasing a held task.
2404    pub fn set_urgent(&mut self, urgent: bool) -> Result<()> {
2405        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2406            bail!(
2407                "task {} is {}; urgent can only change while queued or held; \
2408                 wait for the active attempt to finish and requeue or hold the task first",
2409                self.short(),
2410                self.status.as_str()
2411            );
2412        }
2413        self.urgent = urgent;
2414        Ok(())
2415    }
2416
2417    /// Change the owner-selected immediate execution setting without releasing
2418    /// a held task or altering `urgent`, priority, interrupt, attempts, or
2419    /// resume state.
2420    pub fn set_immediate(&mut self, immediate: bool) -> Result<()> {
2421        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2422            bail!(
2423                "task {} is {}; immediate can only change while queued or held; \
2424                 wait for the active attempt to finish and requeue or hold the task first",
2425                self.short(),
2426                self.status.as_str()
2427            );
2428        }
2429        self.immediate = immediate;
2430        Ok(())
2431    }
2432
2433    /// Change how urgently this task should run next.
2434    ///
2435    /// Refused once the task is `running`: priority only feeds the sort
2436    /// [`Queue::next_runnable`] does over tasks waiting to be claimed, and a
2437    /// running task has already left that pool. Accepting the write anyway
2438    /// would look like it worked while changing nothing until - and unless -
2439    /// this attempt fails and the task becomes runnable again, which is a
2440    /// surprise the phone should not hand back as a success.
2441    pub fn set_priority(&mut self, priority: i32) -> Result<()> {
2442        if self.status == TaskStatus::Running {
2443            bail!(
2444                "task {} is running; its priority cannot be changed until \
2445                 this attempt finishes",
2446                self.short()
2447            );
2448        }
2449        self.priority = priority;
2450        Ok(())
2451    }
2452
2453    /// Mark (or unmark) this task to interrupt whatever `magi serve` already
2454    /// has in flight, once `[daemon] pause_for_interrupts` is on. See
2455    /// [`Task::interrupt`].
2456    ///
2457    /// Setting it is restricted to a task the loop could pick up on its own
2458    /// right now - [`TaskStatus::runnable`] - for the same reason as
2459    /// [`Task::set_priority`]: a task already `running` has been claimed, and
2460    /// a task that is `done`, `held`, or `blocked` is not going to compete
2461    /// for the daemon's attention regardless of this flag. Unlike priority,
2462    /// this is never silently inert while `running` - it is refused outright,
2463    /// because the entire feature this flag drives (`crate::daemon`'s
2464    /// interrupt scheduler) is scoped to tasks still waiting to be claimed.
2465    /// Clearing it back to `false` carries no such risk and is always
2466    /// allowed, including on a task that moved on since it was set.
2467    pub fn set_interrupt(&mut self, interrupt: bool) -> Result<()> {
2468        if interrupt && !self.status.runnable() {
2469            bail!(
2470                "task {} is {}; only a queued or failed task can be marked \
2471                 to interrupt",
2472                self.short(),
2473                self.status.as_str()
2474            );
2475        }
2476        self.interrupt = interrupt;
2477        Ok(())
2478    }
2479
2480    /// Resolve the task override against the running daemon's limit.
2481    pub fn effective_attempt_limit(&self, daemon_limit: usize) -> usize {
2482        self.attempt_limit.map_or(daemon_limit, NonZeroUsize::get)
2483    }
2484
2485    /// Change the budget without resetting attempts or releasing a hold.
2486    /// Callers must hold the queue claim and reload the task before calling.
2487    pub fn change_attempt_limit(&mut self, limit: Option<NonZeroUsize>) -> Result<()> {
2488        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2489            bail!("only queued or held tasks can change the attempt limit");
2490        }
2491        self.stamp_schema();
2492        self.attempt_limit = limit;
2493        Ok(())
2494    }
2495
2496    /// Explicit implementer choice, with Solo taking precedence for old records.
2497    pub fn implementers(&self) -> Option<usize> {
2498        if self.solo {
2499            Some(1)
2500        } else {
2501            self.overrides.as_ref().and_then(|o| o.candidates)
2502        }
2503    }
2504
2505    /// Task-level policy for a new run in `config`, before falling back to its
2506    /// layered value: the explicit per-task choice, else isolated for an
2507    /// immediate or urgent task where that helps and works
2508    /// (`build_target::urgent_isolation`).
2509    pub fn build_cache_override(
2510        &self,
2511        config: &crate::config::Config,
2512    ) -> Option<(BuildCache, &'static str)> {
2513        self.overrides
2514            .as_ref()
2515            .and_then(|o| o.build_cache)
2516            .map(|mode| (mode, "task-override"))
2517            .or_else(|| {
2518                ((self.immediate || self.urgent) && crate::build_target::urgent_isolation(config))
2519                    .then_some((
2520                        BuildCache::Isolated,
2521                        if self.immediate {
2522                            "immediate"
2523                        } else {
2524                            "urgent"
2525                        },
2526                    ))
2527            })
2528    }
2529
2530    /// Set or clear the policy for new runs without changing any saved run.
2531    /// Callers must hold the queue claim and reload the task before calling.
2532    pub fn change_build_cache(&mut self, mode: Option<BuildCache>) -> Result<()> {
2533        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2534            bail!(
2535                "task {} is {}; only queued or held tasks can change build cache",
2536                self.short(),
2537                self.status.as_str()
2538            );
2539        }
2540        self.stamp_schema();
2541        if self.overrides.is_some() || mode.is_some() {
2542            let overrides = self.overrides.get_or_insert_with(|| RunOverrides {
2543                inherit_daemon_options: true,
2544                ..RunOverrides::default()
2545            });
2546            overrides.build_cache = mode;
2547        }
2548        Ok(())
2549    }
2550
2551    /// Validate against this task's configuration and change only its seat count.
2552    /// Callers must hold the queue claim and reload the task before calling.
2553    pub fn change_implementers(&mut self, count: u8) -> Result<()> {
2554        self.check_implementers_editable()?;
2555        let explicit = self.overrides.as_ref().and_then(|o| o.config.as_deref());
2556        let (mut config, _) = crate::config::Config::discover(&self.repo, explicit)?;
2557        if let Some(o) = &self.overrides {
2558            o.apply(&mut config);
2559        }
2560        self.set_implementers(count, &config)
2561    }
2562
2563    fn check_implementers_editable(&self) -> Result<()> {
2564        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2565            bail!(
2566                "task {} is {}; only queued or held tasks can change implementers",
2567                self.short(),
2568                self.status.as_str()
2569            );
2570        }
2571        Ok(())
2572    }
2573
2574    /// Normalize Solo and candidate overrides without altering task history.
2575    pub fn set_implementers(&mut self, count: u8, config: &crate::config::Config) -> Result<()> {
2576        self.check_implementers_editable()?;
2577        crate::talk::check_implementers(count, config).map_err(anyhow::Error::msg)?;
2578        self.stamp_schema();
2579        self.solo = count == 1;
2580        let mut overrides = self.overrides.clone().unwrap_or_else(|| RunOverrides {
2581            inherit_daemon_options: true,
2582            ..Default::default()
2583        });
2584        overrides.candidates = (count > 1).then_some(usize::from(count));
2585        let mut settings = overrides.clone();
2586        settings.inherit_daemon_options = false;
2587        // Some(empty) is a direct-run setting too: retain its isolation on Solo.
2588        self.overrides = if overrides.inherit_daemon_options && settings == RunOverrides::default()
2589        {
2590            None
2591        } else {
2592            Some(overrides)
2593        };
2594        Ok(())
2595    }
2596
2597    /// Replace this task's title and instruction wholesale.
2598    ///
2599    /// Restricted to `queued` and `held`. A `running` task's instruction has
2600    /// already been handed to the graph, so a run in flight and the file on
2601    /// disk must not be allowed to disagree about what was asked; a `done` or
2602    /// `failed` task is a record of what actually happened and editing it
2603    /// after the fact would falsify that record. `id`, `created_at`,
2604    /// `source`, and `runs` are left untouched on purpose - an edit stands in
2605    /// for "delete and refile", and keeping the id, the timestamp, the
2606    /// attribution, and the run history is the entire reason it exists
2607    /// instead.
2608    pub fn edit(&mut self, title: String, instruction: String) -> Result<()> {
2609        if !matches!(self.status, TaskStatus::Queued | TaskStatus::Held) {
2610            bail!(
2611                "task {} is {}; only a queued or held task's instruction can \
2612                 be edited",
2613                self.short(),
2614                self.status.as_str()
2615            );
2616        }
2617        // Older retained reviews have no criteria snapshot yet. Capture the
2618        // old instruction before this supported edit can change the target.
2619        if self.review_branch.is_some() && self.review_instruction.is_none() {
2620            self.review_instruction = Some(self.instruction.clone());
2621        }
2622        if self.instruction != instruction {
2623            // A run selected for earlier criteria is no longer authorized by
2624            // this revised instruction. Title-only edits preserve the pin.
2625            self.resume_override = None;
2626        }
2627        if self.status == TaskStatus::Held && self.machine_hold_cause.is_some() {
2628            self.hold_manual(self.hold_reason.clone());
2629        }
2630        self.machine_hold_cause = None;
2631        self.disk_resume_run = None;
2632        self.disk_checked_at = None;
2633        self.title = title;
2634        self.instruction = instruction;
2635        Ok(())
2636    }
2637
2638    /// Record a run that produced a pull request without merging it.
2639    ///
2640    /// The task is held rather than retried, and it costs no further attempt
2641    /// either way. The work the task asked for exists: it is sitting on a
2642    /// branch, in a pull request, waiting for CI or for a person. Retrying
2643    /// would spend the whole competition budget a second time and then race a
2644    /// second branch against the pull request the first one opened - which is
2645    /// exactly what happened to run 01c2, whose finished and green pull request
2646    /// was re-competed from scratch four seconds after it opened.
2647    ///
2648    /// A pull request nobody merged is a request for a person, not a failure.
2649    ///
2650    /// Records `why` into [`Task::hold_reason`] as well as
2651    /// [`Task::last_error`], so the notification centre and `magi task show`
2652    /// say why the task is held rather than "no reason recorded". This is
2653    /// also the path a verified no-op with an outstanding `magi ask` question
2654    /// settles through - see `daemon::settle` and `daemon::settle_and_diagnose`,
2655    /// which append the question id to `hold_reason` when one is still open
2656    /// for the run.
2657    pub fn handed_off(&mut self, why: impl Into<String>) {
2658        let why = why.into();
2659        self.diagnostic = None;
2660        self.note_held();
2661        self.status = TaskStatus::Held;
2662        self.hold_source = Some(HoldSource::Machine);
2663        self.machine_hold_cause = None;
2664        self.disk_resume_run = None;
2665        self.disk_checked_at = None;
2666        self.hold_reason = Some(why.clone());
2667        self.last_error = Some(why);
2668    }
2669
2670    /// Release on explicit operator authority, rather than automatic recovery.
2671    pub fn release_operator(&mut self, source: &str, question_id: Option<&str>) {
2672        self.recovery_budget = None;
2673        self.recovery_generations.clear();
2674        self.recovery_admission = None;
2675        if self
2676            .resumption
2677            .as_ref()
2678            .is_some_and(|r| r.instruction != self.instruction)
2679        {
2680            // Also cover persisted revisions whose earlier approval still
2681            // carries a transient pin when this release is applied.
2682            self.resume_override = None;
2683        }
2684        let approval = Resumption {
2685            generation: self.resumption.as_ref().map_or(1, |r| r.generation + 1),
2686            source: source.to_owned(),
2687            question_id: question_id.map(str::to_owned),
2688            at: Timestamp::now(),
2689            instruction: self.instruction.clone(),
2690            answers_through: self.answers.len(),
2691            runs_through: self.runs.len(),
2692            blocking_evidence: Vec::new(),
2693            cleared_reason: self
2694                .hold_reason
2695                .clone()
2696                .or_else(|| self.block_reason.clone()),
2697        };
2698        self.release();
2699        self.operator_decided_at = Some(approval.at);
2700        if let Some(previous) = self.resumption.replace(approval) {
2701            self.resumption_history.push(previous);
2702        }
2703    }
2704
2705    /// Record a failed graph pass without allowing automatic requeues to refund it.
2706    pub(crate) fn recovery_failed(&mut self, state: &crate::run::RunState) {
2707        let (base, inputs) = self.recovery_admission.as_ref().map_or_else(
2708            || (state.base_commit.clone(), recovery_inputs(&state.sources)),
2709            |a| (a.base.clone(), a.inputs.clone()),
2710        );
2711        let progress = recovery_progress(state);
2712        let stage = if state.prep_failure.is_some() {
2713            "preparation"
2714        } else {
2715            "execution"
2716        };
2717        let matches = |b: &RecoveryBudget| {
2718            b.instruction == self.instruction
2719                && b.base == base
2720                && b.inputs == inputs
2721                && (progress.is_none() || b.progress == progress)
2722        };
2723        if !self.recovery_budget.as_ref().is_some_and(matches) {
2724            let previous = self
2725                .recovery_generations
2726                .iter()
2727                .position(matches)
2728                .map(|index| self.recovery_generations.remove(index));
2729            if let Some(old) = self.recovery_budget.take() {
2730                self.recovery_generations.push(old);
2731            }
2732            self.recovery_budget = previous;
2733        }
2734        if let Some(budget) = &mut self.recovery_budget {
2735            budget.failures = budget.failures.saturating_add(1);
2736            budget.stage = stage.to_owned();
2737        } else {
2738            self.recovery_budget = Some(RecoveryBudget {
2739                instruction: self.instruction.clone(),
2740                base,
2741                inputs,
2742                stage: stage.to_owned(),
2743                failures: 1,
2744                progress,
2745            });
2746        }
2747    }
2748
2749    pub(crate) fn recovery_exhausted(
2750        &self,
2751        base: &str,
2752        inputs: &str,
2753        limit: usize,
2754    ) -> Option<String> {
2755        let same_input = |b: &&RecoveryBudget| {
2756            b.instruction == self.instruction && b.base == base && b.inputs == inputs
2757        };
2758        let budget = self
2759            .recovery_budget
2760            .as_ref()
2761            .filter(same_input)
2762            .or_else(|| self.recovery_generations.iter().rev().find(same_input))?;
2763        (budget.failures >= limit.max(1)).then(|| budget.budget_reason())
2764    }
2765
2766    pub(crate) fn hold_recovery_budget(&mut self, reason: String, admission: RecoveryAdmission) {
2767        self.hold_unrequested_retry(Some(reason));
2768        if let Some(pass) = self.passes.last()
2769            && self.execution_runs().last() == Some(&pass.run)
2770        {
2771            self.recovery_budget_hold = Some(RecoveryBudgetHold {
2772                admission,
2773                run: pass.run.clone(),
2774                pass: pass.pass_index,
2775                held_at: self.held_at.expect("hold timestamp just recorded"),
2776                decision: self.operator_decided_at,
2777                legacy: false,
2778            });
2779        }
2780    }
2781
2782    fn matches_budget_hold(&self, admission: &RecoveryAdmission) -> bool {
2783        self.status == TaskStatus::Held
2784            && self.hold_source == Some(HoldSource::Manual)
2785            && self.machine_hold_cause.is_none()
2786            && self.recovery_budget.as_ref().is_some_and(|budget| {
2787                budget.instruction == self.instruction
2788                    && budget.base == admission.base
2789                    && budget.inputs == admission.inputs
2790                    && budget.stage == "execution"
2791                    && budget.failures > 0
2792                    && self
2793                        .hold_reason
2794                        .as_ref()
2795                        .is_some_and(|reason| *reason == budget.budget_reason())
2796            })
2797    }
2798
2799    fn legacy_recovery_budget_hold(&self) -> Option<RecoveryBudgetHold> {
2800        let held_at = self.held_at?;
2801        let settled = self.passes.last()?;
2802        let admission = self.recovery_admission.as_ref()?;
2803        if !self.matches_budget_hold(admission)
2804            || self.execution_runs().last() != Some(&settled.run)
2805            || settled.cost != PassCost::Spent
2806            || settled.parked.is_some()
2807            || settled.settled_at > held_at
2808            || self.operator_decided_at.is_some_and(|at| at >= held_at)
2809        {
2810            return None;
2811        }
2812        Some(RecoveryBudgetHold {
2813            admission: admission.clone(),
2814            run: settled.run.clone(),
2815            pass: settled.pass_index,
2816            held_at,
2817            decision: self.operator_decided_at,
2818            legacy: true,
2819        })
2820    }
2821
2822    pub(crate) fn held_for_recovery_budget(&self, run: &crate::run::RunState) -> bool {
2823        let (Some(held_at), Some(settled), Some(pass), Some(admission)) = (
2824            self.held_at,
2825            self.passes.last(),
2826            run.passes.last(),
2827            self.recovery_admission.as_ref(),
2828        ) else {
2829            return false;
2830        };
2831        if !self.matches_budget_hold(admission)
2832            || self.execution_runs().last() != Some(&run.id)
2833            || settled.run != run.id
2834            || settled.pass_index != pass.index
2835            || settled.cost != PassCost::Spent
2836            || settled.parked.is_some()
2837            || settled.settled_at < pass.started_at
2838            || settled.settled_at > held_at
2839            || self.operator_decided_at.is_some_and(|at| at >= held_at)
2840            || !crate::daemon::compatible_run_instruction(run, self)
2841        {
2842            return false;
2843        }
2844        match &self.recovery_budget_hold {
2845            Some(hold) => {
2846                hold.run == run.id
2847                    && hold.pass == pass.index
2848                    && hold.held_at == held_at
2849                    && hold.decision == self.operator_decided_at
2850                    && &hold.admission == admission
2851                    && (!hold.legacy
2852                        || self
2853                            .operator_decided_at
2854                            .is_none_or(|at| at < pass.started_at))
2855            }
2856            None => {
2857                self.schema < RECOVERY_HOLD_SCHEMA
2858                    && self
2859                        .operator_decided_at
2860                        .is_none_or(|at| at < pass.started_at)
2861            }
2862        }
2863    }
2864
2865    pub(crate) fn queue_repair(&mut self, receipt: &crate::repair_budget::Receipt) {
2866        self.stamp_schema();
2867        self.repair_grants.push(receipt.clone());
2868        self.status = TaskStatus::Queued;
2869        self.hold_source = None;
2870        self.hold_reason = None;
2871        self.held_at = None;
2872        self.recovery_budget_hold = None;
2873        self.reopen_hold = None;
2874        self.resume_override = Some(OperatorResume {
2875            question_id: String::new(),
2876            at: receipt.at,
2877            conductor_rehold: None,
2878            forced: true,
2879            pinned_run: Some(receipt.request.run.clone()),
2880        });
2881    }
2882
2883    /// A legacy record can identify the current hold, but cannot prove that
2884    /// it was never replaced. Preserve that distinction across schema upgrades.
2885    fn snapshot_legacy_reopen_hold(&mut self) {
2886        if self.schema >= REOPEN_HOLD_SCHEMA || self.reopen_hold.is_some() {
2887            return;
2888        }
2889        let Some(event) = self.completion_history.last() else {
2890            return;
2891        };
2892        if event.action == CompletionAction::Reopen
2893            && self.status == TaskStatus::Held
2894            && self.hold_source == Some(HoldSource::Manual)
2895            && event.reason.is_some()
2896            && self.hold_reason == event.reason
2897            && let (Some(held_at), Some(decision)) = (self.held_at, self.operator_decided_at)
2898            && held_at >= event.at
2899            && decision >= event.at
2900        {
2901            self.reopen_hold = Some(ReopenHold {
2902                occurrence: event.occurrence.clone(),
2903                held_at,
2904                decision: Some(decision),
2905                legacy: true,
2906            });
2907        }
2908    }
2909
2910    /// A legacy snapshot additionally requires explicit approval of the
2911    /// current hold timestamps, not an inference from temporal proximity.
2912    pub(crate) fn held_by_reopen(
2913        &self,
2914        occurrence: &str,
2915        run: &str,
2916        legacy_confirmation: Option<&str>,
2917    ) -> bool {
2918        let Some(event) = self.completion_history.last() else {
2919            return false;
2920        };
2921        if self.status != TaskStatus::Held
2922            || self.hold_source != Some(HoldSource::Manual)
2923            || !self.blocked_by.is_empty()
2924            || self.resume_override.is_some()
2925            || self.fresh_start
2926            || event.action != CompletionAction::Reopen
2927            || event.occurrence != occurrence
2928            || event.run.as_ref().map(|r| r.id.as_str()) != Some(run)
2929            || event.reason.is_none()
2930            || self.hold_reason != event.reason
2931        {
2932            return false;
2933        }
2934        let (Some(held_at), Some(decided), Some(hold)) =
2935            (self.held_at, self.operator_decided_at, &self.reopen_hold)
2936        else {
2937            return false;
2938        };
2939        hold.occurrence == occurrence
2940            && hold.held_at == held_at
2941            && hold.decision == Some(decided)
2942            && if hold.legacy {
2943                legacy_confirmation == Some(format!("{held_at}/{decided}").as_str())
2944            } else {
2945                legacy_confirmation.is_none()
2946            }
2947    }
2948
2949    /// Put a held or finished task back in line, with its attempt count reset
2950    /// so a release is a real second chance rather than an instant re-hold.
2951    /// The run history is kept: attempts reset, evidence does not.
2952    pub fn release(&mut self) {
2953        // Freeze the unresolved cause before a recovery can mint a run without
2954        // doing work. Approval and timestamps alone are not new outcomes.
2955        self.import_chat_notice();
2956        if self.hold_notice_cause.is_none()
2957            && matches!(self.status, TaskStatus::Held | TaskStatus::Blocked)
2958        {
2959            self.hold_notice_cause = Some(self.unresolved_hold_cause());
2960        }
2961        let refused_handover = self.status == TaskStatus::Held
2962            && self.hold_source == Some(HoldSource::Machine)
2963            && self.review_branch.is_some()
2964            && self
2965                .review_instruction
2966                .as_ref()
2967                .is_none_or(|i| *i == self.instruction);
2968        self.status = TaskStatus::Queued;
2969        self.held_at = None;
2970        self.attempts = 0;
2971        self.last_error = None;
2972        self.park_reason = None;
2973        // Otherwise the next person who holds this task reads a reason that
2974        // belonged to whatever it was waiting on last time.
2975        self.hold_reason = None;
2976        self.hold_source = None;
2977        self.machine_hold_cause = None;
2978        self.disk_resume_run = None;
2979        self.disk_checked_at = None;
2980        self.diagnostic = None;
2981        // A release also un-blocks: the dependency or question `blocked_by`
2982        // named may still be unresolved, but a human (or `crate::conduct`)
2983        // choosing to release the task overrides that wait outright, the same
2984        // as it overrides an ordinary hold.
2985        self.blocked_by.clear();
2986        self.block_reason = None;
2987        self.blocked_from = None;
2988        // A machine hold that still names a review branch is a refused
2989        // handover (see [`Task::hold_for_handover`]): the retry must review
2990        // that same branch. Any other release drops it.
2991        if !refused_handover {
2992            self.review_branch = None;
2993            self.review_instruction = None;
2994        }
2995        self.fresh_start = false;
2996    }
2997}
2998
2999/// Copy `src` into `dir` as `name`, or `stem-2.ext`, `stem-3.ext`, ... when
3000/// that is taken. `create_new` makes the collision check atomic and also
3001/// catches a case-insensitive filesystem. Returns the stored name and path.
3002fn copy_new(dir: &Path, src: &Path, name: &str) -> Result<(String, PathBuf)> {
3003    use std::io::ErrorKind;
3004    let (stem, ext) = match name.rfind('.') {
3005        Some(i) if i > 0 => (&name[..i], &name[i..]),
3006        _ => (name, ""),
3007    };
3008    for n in 1u32.. {
3009        let candidate = if n == 1 {
3010            name.to_owned()
3011        } else {
3012            let suffix = format!("-{n}");
3013            let room = 64usize.saturating_sub(suffix.len() + ext.len());
3014            let stem: String = stem.chars().take(room).collect();
3015            format!("{stem}{suffix}{ext}")
3016        };
3017        if !crate::ask::valid_asset_name(&candidate) {
3018            bail!("no valid attachment name is left for `{name}`");
3019        }
3020        let path = dir.join(&candidate);
3021        match std::fs::OpenOptions::new()
3022            .write(true)
3023            .create_new(true)
3024            .open(&path)
3025        {
3026            Ok(mut out) => {
3027                let copied = std::fs::File::open(src)
3028                    .and_then(|mut input| std::io::copy(&mut input, &mut out));
3029                if let Err(e) = copied {
3030                    drop(out);
3031                    let _ = std::fs::remove_file(&path);
3032                    return Err(e).with_context(|| format!("copy {}", src.display()));
3033                }
3034                return Ok((candidate, path));
3035            }
3036            Err(e) if e.kind() == ErrorKind::AlreadyExists => continue,
3037            Err(e) => return Err(e).with_context(|| format!("create {}", path.display())),
3038        }
3039    }
3040    unreachable!("the counter never runs out")
3041}
3042
3043/// Minimum age before a dead writer's lock may be recovered, and maximum wait
3044/// for a contending writer. Age alone never revokes a live writer's ownership.
3045const TASK_LOCK_STALE: std::time::Duration = std::time::Duration::from_secs(10);
3046
3047/// Guard for [`Queue::lock_task`]; removes the lock file on drop, but only
3048/// while the file still carries this guard's owner token.
3049pub(crate) struct TaskLock {
3050    path: PathBuf,
3051    token: String,
3052}
3053
3054/// A token no other holder shares: pid, then a mix of entropy and a process
3055/// counter so threads born in the same nanosecond still differ.
3056fn owner_token() -> String {
3057    static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
3058    let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
3059    let mut r = crate::rng::SplitMix64::new(crate::rng::entropy() ^ n.rotate_left(32));
3060    format!("{}-{:016x}", std::process::id(), r.next_u64())
3061}
3062
3063/// The marker that serializes everyone removing the lock that carries `token`.
3064/// Hashed (FNV-1a) so an empty or foreign token is still a valid file name.
3065fn break_marker(path: &Path, token: &str) -> PathBuf {
3066    let mut h: u64 = 0xcbf29ce484222325;
3067    for b in token.bytes() {
3068        h ^= u64::from(b);
3069        h = h.wrapping_mul(0x100000001b3);
3070    }
3071    let mut name = path.as_os_str().to_owned();
3072    name.push(format!(".break-{h:016x}"));
3073    PathBuf::from(name)
3074}
3075
3076fn older_than_stale(path: &Path) -> bool {
3077    std::fs::metadata(path)
3078        .and_then(|m| m.modified())
3079        .ok()
3080        .and_then(|t| t.elapsed().ok())
3081        .is_some_and(|age| age > TASK_LOCK_STALE)
3082}
3083
3084fn writer_may_be_gone(token: &str) -> bool {
3085    let Some(pid) = token
3086        .split_once('-')
3087        .and_then(|(pid, _)| pid.parse::<u32>().ok())
3088    else {
3089        // Legacy/incomplete tokens have no valid writer identity. They remain
3090        // subject to the age and compare/remove checks.
3091        return true;
3092    };
3093    if pid == std::process::id() {
3094        return false;
3095    }
3096    // Unknown process-table access must not steal a long-running retirement.
3097    crate::proc::pid_status(pid) == Some(false)
3098}
3099
3100/// How many levels of "a stale marker guarding a stale marker" are recovered
3101/// before giving up. Each level needs its own crashed remover, so the cap is
3102/// never reached without several independent crashes.
3103const MAX_MARKER_DEPTH: u8 = 3;
3104
3105/// Take the break marker for `token`, or `None` if another remover holds it.
3106/// The marker carries its own owner token. One older than [`TASK_LOCK_STALE`]
3107/// was left by a remover that died; it is cleared by the same compare-and-
3108/// remove discipline as a lock, guarded by a marker of its own, so a recoverer
3109/// that judged it stale cannot delete a fresh marker that replaced it.
3110fn take_marker(
3111    path: &Path,
3112    token: &str,
3113    depth: u8,
3114    retry: crate::lock_file::Retry,
3115) -> Option<(PathBuf, String)> {
3116    use std::io::Write;
3117    let marker = break_marker(path, token);
3118    for _ in 0..2 {
3119        match retry.create(&marker) {
3120            Ok(mut f) => {
3121                let mine = owner_token();
3122                if f.write_all(mine.as_bytes()).is_err() {
3123                    drop(f);
3124                    let _ = std::fs::remove_file(&marker);
3125                    return None;
3126                }
3127                return Some((marker, mine));
3128            }
3129            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
3130                let judged = std::fs::read_to_string(&marker).ok();
3131                match judged.filter(|_| older_than_stale(&marker)) {
3132                    Some(judged) if depth < MAX_MARKER_DEPTH => {
3133                        remove_lock_if(&marker, &judged, true, depth + 1, retry)?;
3134                    }
3135                    _ => return None,
3136                }
3137            }
3138            Err(_) => return None,
3139        }
3140    }
3141    None
3142}
3143
3144/// Remove the lock at `path` if it still carries `token` (and, when
3145/// `require_stale`, is still stale). Removal is serialized per token by the
3146/// break marker, so a remover that judged an old lock cannot delete the fresh
3147/// one that replaced it. `None` means the marker was busy: try again.
3148fn remove_lock_if(
3149    path: &Path,
3150    token: &str,
3151    require_stale: bool,
3152    depth: u8,
3153    retry: crate::lock_file::Retry,
3154) -> Option<bool> {
3155    let (marker, mine) = take_marker(path, token, depth, retry)?;
3156    let still = std::fs::read_to_string(path).is_ok_and(|c| c == token)
3157        && (!require_stale || older_than_stale(path) && writer_may_be_gone(token));
3158    if still {
3159        let _ = std::fs::remove_file(path);
3160    }
3161    // Release the marker only if it is still ours.
3162    if depth >= MAX_MARKER_DEPTH {
3163        if std::fs::read_to_string(&marker).is_ok_and(|c| c == mine) {
3164            let _ = std::fs::remove_file(&marker);
3165        }
3166    } else {
3167        let _ = remove_lock_if(&marker, &mine, false, depth + 1, retry);
3168    }
3169    Some(still)
3170}
3171
3172/// Break the lock judged stale while it held `judged`. Returns whether it was
3173/// removed; a lock that has since been replaced is left alone.
3174#[cfg(test)]
3175fn break_stale(path: &Path, judged: &str) -> bool {
3176    break_stale_with(path, judged, crate::lock_file::Retry::new(None))
3177}
3178
3179fn break_stale_with(path: &Path, judged: &str, retry: crate::lock_file::Retry) -> bool {
3180    remove_lock_if(path, judged, true, 0, retry).unwrap_or(false)
3181}
3182
3183impl Drop for TaskLock {
3184    fn drop(&mut self) {
3185        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2);
3186        let retry = crate::lock_file::Retry::new(Some(deadline));
3187        loop {
3188            match remove_lock_if(&self.path, &self.token, false, 0, retry) {
3189                Some(_) => return,
3190                None if std::time::Instant::now() > deadline => return,
3191                None => std::thread::sleep(std::time::Duration::from_millis(5)),
3192            }
3193        }
3194    }
3195}
3196
3197#[derive(Debug, thiserror::Error)]
3198#[error("task changed during completion decision; reload and inspect it")]
3199pub(crate) struct CompletionSnapshotChanged;
3200
3201/// A queue on disk.
3202#[derive(Debug, Clone)]
3203pub struct Queue {
3204    root: PathBuf,
3205    ids: IdSource,
3206}
3207
3208fn validate_attachments(sources: &[PathBuf]) -> Result<Vec<(&PathBuf, &str)>> {
3209    let mut wanted = Vec::new();
3210    for src in sources {
3211        let name = src
3212            .file_name()
3213            .and_then(|n| n.to_str())
3214            .with_context(|| format!("`{}` has no usable file name", src.display()))?;
3215        if !crate::ask::valid_asset_name(name) {
3216            bail!(
3217                "attachment name `{name}` must match ^[A-Za-z0-9][A-Za-z0-9._-]{{0,63}}$ \
3218                 with no `..`; rename the file and try again"
3219            );
3220        }
3221        if !src.is_file() {
3222            bail!("attachment `{}` is not a file", src.display());
3223        }
3224        wanted.push((src, name));
3225    }
3226    Ok(wanted)
3227}
3228
3229impl Queue {
3230    /// The operator's queue, `<home>/queue`.
3231    pub fn open() -> Self {
3232        Self::at(crate::run::home().join("queue"))
3233    }
3234
3235    /// A queue at an explicit root. Tests use this; so could an operator who
3236    /// wants a queue per project.
3237    pub fn at(root: PathBuf) -> Self {
3238        Self {
3239            root,
3240            ids: IdSource::new(new_id),
3241        }
3242    }
3243
3244    /// Replace the source of candidate ids for new tasks. For tests that need
3245    /// a deterministic collision.
3246    #[doc(hidden)]
3247    pub fn with_id_source(mut self, f: impl Fn() -> String + Send + Sync + 'static) -> Self {
3248        self.ids = IdSource::custom(f);
3249        self
3250    }
3251
3252    /// File a new task: reserve its id atomically and write it without ever
3253    /// reading, merging into or replacing an existing record.
3254    ///
3255    /// The candidate is `task.id`. Under that id's write lock, a record that
3256    /// already exists makes the candidate taken and another id is minted; a
3257    /// failure to find out is an error, never "free". `hook` runs under the
3258    /// lock once the id looks free and may veto it with `Ok(false)` (an
3259    /// orphaned claim or attachment directory also marks an id as used). The
3260    /// first `Err` ends the attempt. `undo` runs if the record then fails to
3261    /// write. `task.id` is the reserved id on success.
3262    fn file_with(
3263        &self,
3264        task: &mut Task,
3265        hook: impl FnMut(&mut Task) -> Result<bool>,
3266        undo: impl FnMut(&mut Task),
3267    ) -> Result<()> {
3268        self.reserve_id(task, hook, undo, true)
3269    }
3270
3271    /// The reservation loop behind [`Queue::file_with`]. With `store` false
3272    /// the id is only reserved through whatever `hook` leaves on disk (an
3273    /// attachment directory) and no record is written; the task stays unfiled.
3274    ///
3275    /// An injected id source supplies the first candidate too, unless the
3276    /// task already holds an id through an earlier reservation (attachments);
3277    /// production keeps the id [`Task::new`] minted.
3278    fn reserve_id(
3279        &self,
3280        task: &mut Task,
3281        mut hook: impl FnMut(&mut Task) -> Result<bool>,
3282        mut undo: impl FnMut(&mut Task),
3283        store: bool,
3284    ) -> Result<()> {
3285        let redraw_first = self.ids.is_custom() && task.attachments.is_empty();
3286        let initial = task.id.clone();
3287        self.ids
3288            .reserve((!redraw_first).then_some(initial.as_str()), "task", |id| {
3289                task.id = id.to_owned();
3290                let _lock = self.lock_task(&task.id)?;
3291                if path_exists(&self.path_of(&task.id))? || !hook(task)? {
3292                    return Ok(false);
3293                }
3294                if store {
3295                    if let Err(e) = self.write_record(task) {
3296                        undo(task);
3297                        return Err(e);
3298                    }
3299                    task.unfiled = false;
3300                }
3301                Ok(true)
3302            })?;
3303        Ok(())
3304    }
3305
3306    /// Is `id` used by anything but a stored record: a claim file, or an
3307    /// attachment directory (`check_attachments`) left by an earlier
3308    /// reservation or an interrupted filing? Only a definite "not found" is
3309    /// free; any other answer is an error, never "free".
3310    fn id_in_use(&self, id: &str, check_attachments: bool) -> Result<bool> {
3311        if path_exists(&self.lock_path(id))? || path_exists(&self.filing_reservation_path(id))? {
3312            return Ok(true);
3313        }
3314        Ok(check_attachments && path_exists(&self.attachments_dir(id))?)
3315    }
3316
3317    /// The `hook` of a plain [`Queue::put`] of a new task. Attachments
3318    /// already copied by [`Queue::attach`] sit in this id's own directory,
3319    /// which is then not a sign of someone else's use.
3320    fn plain_filing_hook(&self, task: &Task) -> Result<bool> {
3321        Ok(!self.id_in_use(&task.id, task.attachments.is_empty())?)
3322    }
3323
3324    /// File a new task and take its claim in one step, on the id that ends up
3325    /// reserved. An id whose claim file already exists is taken.
3326    pub fn file_claimed(&self, task: &mut Task) -> Result<Claim> {
3327        let mut claim = None;
3328        self.file_with(
3329            task,
3330            |t| {
3331                if self.id_in_use(&t.id, true)? {
3332                    return Ok(false);
3333                }
3334                claim = Some(self.claim(&t.id)?);
3335                Ok(true)
3336            },
3337            |_| {},
3338        )?;
3339        claim.context("claim missing after filing")
3340    }
3341
3342    /// Directory holding the task files.
3343    pub fn root(&self) -> &Path {
3344        &self.root
3345    }
3346
3347    /// Path for one task id.
3348    pub fn path_of(&self, id: &str) -> PathBuf {
3349        self.root.join(format!("{id}.json"))
3350    }
3351
3352    /// Directory holding a task's attachments. A sibling of the task file,
3353    /// not a `*.json`, so [`Queue::list`] and [`Queue::revision`] never see it.
3354    pub fn attachments_dir(&self, id: &str) -> PathBuf {
3355        self.root.join(format!("{id}.attachments"))
3356    }
3357
3358    /// Copy each of `sources` into `task`'s attachment directory and record
3359    /// the stored names on `task` (persist with [`Queue::put`]). Returns the
3360    /// names, in order.
3361    ///
3362    /// Every source is checked (a readable file, a name passing
3363    /// [`crate::ask::valid_asset_name`]) before anything is copied, and a
3364    /// copy that fails part-way removes only what this call created. A name
3365    /// already taken is never overwritten: it becomes `stem-2.ext`,
3366    /// `stem-3.ext`, ... A name that does not validate is refused rather than
3367    /// sanitised - the operator renames the file.
3368    pub fn attach(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3369        let wanted = validate_attachments(sources)?;
3370        if task.unfiled && task.attachments.is_empty() {
3371            // Not stored yet: the directory is created under the id's
3372            // reservation and keeps the id taken until the record lands.
3373            let names = std::cell::RefCell::new(Vec::new());
3374            self.reserve_id(
3375                task,
3376                |t| {
3377                    if self.id_in_use(&t.id, true)? {
3378                        return Ok(false);
3379                    }
3380                    *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3381                    Ok(true)
3382                },
3383                |_| {},
3384                false,
3385            )?;
3386            return Ok(names.into_inner());
3387        }
3388        self.copy_attachments(task, &wanted)
3389    }
3390
3391    /// Copy `wanted` into `task`'s attachment directory (see [`Queue::attach`]).
3392    fn copy_attachments(
3393        &self,
3394        task: &mut Task,
3395        wanted: &[(&PathBuf, &str)],
3396    ) -> Result<Vec<String>> {
3397        let dir = self.attachments_dir(&task.id);
3398        let existed = dir.is_dir();
3399        std::fs::create_dir_all(&dir).with_context(|| format!("create {}", dir.display()))?;
3400        let mut created: Vec<PathBuf> = Vec::new();
3401        let mut names = Vec::new();
3402        let mut copy_all = || -> Result<()> {
3403            for (src, name) in wanted {
3404                let (stored, path) = copy_new(&dir, src, name)?;
3405                created.push(path);
3406                names.push(stored);
3407            }
3408            Ok(())
3409        };
3410        if let Err(e) = copy_all() {
3411            for path in &created {
3412                let _ = std::fs::remove_file(path);
3413            }
3414            if !existed {
3415                let _ = std::fs::remove_dir(&dir);
3416            }
3417            return Err(e);
3418        }
3419        task.attachments.extend(names.iter().cloned());
3420        Ok(names)
3421    }
3422
3423    /// [`Queue::attach`] then [`Queue::put`], undoing the copies when the
3424    /// record cannot be written. Without the undo the files sit in
3425    /// `<id>.attachments/` with no task pointing at them.
3426    ///
3427    /// Only what this call copied is removed (the names `attach` returned,
3428    /// and the directory itself only when it did not exist before and is
3429    /// empty), never an attachment an earlier save recorded. `task` is rolled
3430    /// back too, and the error the caller sees is `put`'s own. This relies on
3431    /// a failed `put` leaving the stored record untouched, which its
3432    /// write-then-rename guarantees.
3433    pub fn attach_and_put(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3434        if task.unfiled && task.attachments.is_empty() {
3435            return self.attach_and_file(task, sources);
3436        }
3437        let dir = self.attachments_dir(&task.id);
3438        let existed = dir.is_dir();
3439        let before = task.attachments.len();
3440        let names = self.attach(task, sources)?;
3441        if let Err(e) = self.put(task) {
3442            for name in &names {
3443                let _ = std::fs::remove_file(dir.join(name));
3444            }
3445            if !existed {
3446                let _ = std::fs::remove_dir(&dir);
3447            }
3448            task.attachments.truncate(before);
3449            return Err(e);
3450        }
3451        Ok(names)
3452    }
3453
3454    /// [`Queue::attach_and_put`] for a task not yet stored: the attachment
3455    /// directory is created under the id's reservation, and a candidate whose
3456    /// directory already exists is taken.
3457    fn attach_and_file(&self, task: &mut Task, sources: &[PathBuf]) -> Result<Vec<String>> {
3458        let wanted = validate_attachments(sources)?;
3459        let before = task.attachments.len();
3460        let names = std::cell::RefCell::new(Vec::new());
3461        let result = self.file_with(
3462            task,
3463            |t| {
3464                if self.id_in_use(&t.id, true)? {
3465                    return Ok(false);
3466                }
3467                *names.borrow_mut() = self.copy_attachments(t, &wanted)?;
3468                Ok(true)
3469            },
3470            |t| {
3471                let dir = self.attachments_dir(&t.id);
3472                for name in names.borrow().iter() {
3473                    let _ = std::fs::remove_file(dir.join(name));
3474                }
3475                // The directory did not exist when the id was reserved.
3476                let _ = std::fs::remove_dir(&dir);
3477                t.attachments.truncate(before);
3478            },
3479        );
3480        result.map(|()| names.into_inner())
3481    }
3482
3483    /// Absolute paths of `task`'s attachments, whatever shape this queue's
3484    /// root has. Absolute because the prompt hands them to an agent whose
3485    /// working directory is somewhere else entirely.
3486    pub fn attachment_paths(&self, task: &Task) -> Vec<PathBuf> {
3487        let dir = self.attachments_dir(&task.id);
3488        task.attachments
3489            .iter()
3490            .map(|n| {
3491                let p = dir.join(n);
3492                std::path::absolute(&p).unwrap_or(p)
3493            })
3494            .collect()
3495    }
3496
3497    /// Write a task, atomically, so a daemon killed mid-write leaves the
3498    /// previous state readable rather than a truncated file.
3499    ///
3500    /// Runs already recorded on disk that `task` does not carry are kept, not
3501    /// dropped: `magi run --task` links a run into a task from another
3502    /// process ([`Queue::link_run`]) while a daemon may hold a snapshot taken
3503    /// before it, and writing that snapshot back whole would erase the link.
3504    /// Nothing ever removes a run from a task, so the union loses nothing.
3505    pub fn put(&self, task: &mut Task) -> Result<()> {
3506        if task.unfiled {
3507            // A new task never merges into a record that has its id.
3508            return self.file_with(task, |t| self.plain_filing_hook(t), |_| {});
3509        }
3510        let _lock = self.lock_task(&task.id)?;
3511        self.put_unlocked(task)
3512    }
3513
3514    /// Write `task` only if no task with its id exists yet; `Ok(false)` when
3515    /// one does. Unlike [`Queue::put`] it never replaces a record, so a
3516    /// producer with a deterministic id cannot rewind a task that has since
3517    /// started running or finished.
3518    pub fn create_new(&self, task: &mut Task) -> Result<bool> {
3519        let _lock = self.lock_task(&task.id)?;
3520        if path_exists(&self.path_of(&task.id))?
3521            || path_exists(&self.filing_reservation_path(&task.id))?
3522        {
3523            return Ok(false);
3524        }
3525        self.write_record(task)?;
3526        task.unfiled = false;
3527        Ok(true)
3528    }
3529
3530    fn filing_reservation_path(&self, id: &str) -> PathBuf {
3531        self.root.join(format!("{id}.filing-reservation"))
3532    }
3533
3534    /// Durably reserve a fresh id before a two-phase receipt is saved. The
3535    /// marker survives crashes and task deletion, so neither a prepared nor
3536    /// an applied receipt can ever refer to an unrelated later filing.
3537    /// A crash before receipt publication may leave an unused reserved id.
3538    pub(crate) fn reserve_unused_id(&self) -> Result<String> {
3539        let mut chosen = String::new();
3540        self.ids.reserve(None, "task", |id| {
3541            let _lock = self.lock_task(id)?;
3542            if path_exists(&self.path_of(id))?
3543                || path_exists(&self.tombstone_path(id))?
3544                || self.id_in_use(id, true)?
3545            {
3546                return Ok(false);
3547            }
3548            std::fs::File::create_new(self.filing_reservation_path(id))?.sync_all()?;
3549            chosen = id.to_owned();
3550            Ok(true)
3551        })?;
3552        Ok(chosen)
3553    }
3554
3555    /// File `task` under its exact pre-allocated `task.id` (with optional
3556    /// attachments) without redrawing an id or replacing an existing record.
3557    ///
3558    /// Returns `Ok(false)` when a record for `task.id` already exists on disk.
3559    /// When `allow_clean_unfiled_attachments` is true (Phase 1 receipt recovery
3560    /// with no `<id>.json` yet), an incomplete `<id>.attachments/` directory
3561    /// from an interrupted copy is removed before re-copying validated sources.
3562    /// `verify_attachments` checks the copied files under the reservation
3563    /// before publishing the task record; failure rolls back the copies.
3564    pub(crate) fn file_with_exact_id(
3565        &self,
3566        task: &mut Task,
3567        sources: &[PathBuf],
3568        allow_clean_unfiled_attachments: bool,
3569        verify_attachments: impl FnOnce(&Task) -> Result<()>,
3570    ) -> Result<bool> {
3571        let wanted = validate_attachments(sources)?;
3572        let _lock = self.lock_task(&task.id)?;
3573        anyhow::ensure!(
3574            path_exists(&self.filing_reservation_path(&task.id))?,
3575            "task id {} has no durable filing reservation",
3576            task.id
3577        );
3578        if path_exists(&self.path_of(&task.id))? {
3579            return Ok(false);
3580        }
3581        // Removal publishes its tombstone before deleting the record.
3582        anyhow::ensure!(
3583            !path_exists(&self.tombstone_path(&task.id))?,
3584            "reserved task {} was deleted; refusing to file it again",
3585            task.id
3586        );
3587        if path_exists(&self.lock_path(&task.id))? {
3588            bail!(
3589                "reserved task id {} is claimed; cannot finish filing",
3590                task.id
3591            );
3592        }
3593        let dir = self.attachments_dir(&task.id);
3594        if path_exists(&dir)? {
3595            if allow_clean_unfiled_attachments {
3596                std::fs::remove_dir_all(&dir)
3597                    .with_context(|| format!("clean partial attachments {}", dir.display()))?;
3598            } else {
3599                bail!(
3600                    "reserved task id {} already has an attachment directory",
3601                    task.id
3602                );
3603            }
3604        }
3605        if !wanted.is_empty() {
3606            let before = task.attachments.len();
3607            let names = self.copy_attachments(task, &wanted)?;
3608            if let Err(e) = verify_attachments(task).and_then(|()| self.write_record(task)) {
3609                for name in &names {
3610                    let _ = std::fs::remove_file(dir.join(name));
3611                }
3612                let _ = std::fs::remove_dir(&dir);
3613                task.attachments.truncate(before);
3614                return Err(e);
3615            }
3616        } else {
3617            verify_attachments(task)?;
3618            self.write_record(task)?;
3619        }
3620        task.unfiled = false;
3621        Ok(true)
3622    }
3623
3624    /// [`Queue::put`] for a caller already holding [`Queue::lock_task`].
3625    fn put_unlocked(&self, task: &mut Task) -> Result<()> {
3626        self.merge_stored(task);
3627        if let Some(boundary) = task.reassignments.last() {
3628            let stored = self.get(&task.id)?;
3629            anyhow::ensure!(
3630                task.reassignments == stored.reassignments
3631                    && task.repo == stored.repo
3632                    && task.runs.get(..boundary.run_boundary)
3633                        == stored.runs.get(..boundary.run_boundary),
3634                "historical repository execution cannot be restarted; reload the task"
3635            );
3636        }
3637        self.write_record(task)
3638    }
3639
3640    /// Save an exact-run recovery pin only if its admitted owner snapshot is current.
3641    pub(crate) fn commit_base_recovery(
3642        &self,
3643        task: &mut Task,
3644        expected: &serde_json::Value,
3645    ) -> Result<()> {
3646        let _lock = self.lock_task(&task.id)?;
3647        anyhow::ensure!(
3648            serde_json::to_value(self.get(&task.id)?)? == *expected,
3649            "task changed during base recovery; inspect the pending authorization"
3650        );
3651        // Retain the ordinary merge evidence when replacing an earlier decision pin.
3652        self.put_unlocked(task)
3653    }
3654
3655    /// Save an exact-run landing base-sync recovery pin only if its admitted owner snapshot is current.
3656    pub(crate) fn commit_land_sync_recovery(
3657        &self,
3658        task: &mut Task,
3659        expected: &serde_json::Value,
3660    ) -> Result<()> {
3661        let _lock = self.lock_task(&task.id)?;
3662        anyhow::ensure!(
3663            serde_json::to_value(self.get(&task.id)?)? == *expected,
3664            "task changed during landing base-sync recovery; inspect the pending authorization"
3665        );
3666        self.put_unlocked(task)
3667    }
3668
3669    pub(crate) fn commit_repair_grant(
3670        &self,
3671        task: &mut Task,
3672        expected: &serde_json::Value,
3673    ) -> Result<()> {
3674        let _lock = self.lock_task(&task.id)?;
3675        anyhow::ensure!(
3676            serde_json::to_value(self.get(&task.id)?)? == *expected,
3677            "repair grant refused: task changed during admission"
3678        );
3679        self.write_record(task)
3680            .context(crate::repair_budget::PublicationUnknown)
3681    }
3682
3683    /// Save a disk monitor transition only while its complete task snapshot matches.
3684    pub(crate) fn commit_disk_wait(&self, task: &mut Task, expected: &Task) -> Result<()> {
3685        let _lock = self.lock_task(&task.id)?;
3686        anyhow::ensure!(
3687            serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3688            "task changed during disk monitoring"
3689        );
3690        task.stamp_schema();
3691        self.write_record_inner(task, false)
3692    }
3693
3694    /// Commit one validated reassignment under the task write lock.
3695    pub(crate) fn commit_reassignment(&self, task: &mut Task, expected: &Task) -> Result<()> {
3696        let _lock = self.lock_task(&task.id)?;
3697        let stored = self.get(&task.id)?;
3698        anyhow::ensure!(
3699            serde_json::to_value(&stored)? == serde_json::to_value(expected)?
3700                && stored.reassignments.len() + 1 == task.reassignments.len()
3701                && stored.repo == task.reassignments.last().expect("new boundary").from
3702                && stored.runs == task.runs,
3703            "task changed during reassignment; retry after inspecting it"
3704        );
3705        self.write_record(task)
3706    }
3707
3708    /// Commit a validated lifecycle transition only against its admitted snapshot.
3709    pub(crate) fn commit_completion(&self, task: &mut Task, expected: &Task) -> Result<()> {
3710        let _lock = self.lock_task(&task.id)?;
3711        anyhow::ensure!(
3712            serde_json::to_value(self.get(&task.id)?)? == serde_json::to_value(expected)?,
3713            CompletionSnapshotChanged
3714        );
3715        self.write_record(task)
3716    }
3717
3718    /// Fold the stored record of `task`'s id into `task` (updates only).
3719    fn merge_stored(&self, task: &mut Task) {
3720        if let Ok(mut stored) = read_path(&self.path_of(&task.id)) {
3721            stored.import_chat_notice();
3722            // A stale writer may add evidence, but never erase/rewrite an
3723            // immutable event or undo the lifecycle decision it did not see.
3724            let local_decision = task.completion_history.iter().any(|event| {
3725                !stored
3726                    .completion_history
3727                    .iter()
3728                    .any(|saved| saved.occurrence == event.occurrence)
3729                    && event.at > stored.updated_at
3730            });
3731            let unseen_decision = stored.completion_history.iter().any(|event| {
3732                !task
3733                    .completion_history
3734                    .iter()
3735                    .any(|mine| mine.occurrence == event.occurrence)
3736            });
3737            let mut history = std::mem::take(&mut stored.completion_history);
3738            for event in std::mem::take(&mut task.completion_history) {
3739                if !history
3740                    .iter()
3741                    .any(|stored| stored.occurrence == event.occurrence)
3742                {
3743                    history.push(event);
3744                }
3745            }
3746            if unseen_decision {
3747                // Keep the persisted decision and every live control that followed
3748                // it. Only import evidence from the writer that missed it.
3749                task.import_chat_notice();
3750                let mut stale = std::mem::replace(task, stored);
3751                append_missing(&mut task.answers, stale.answers);
3752                if task.reassignments == stale.reassignments {
3753                    append_missing(&mut task.runs, stale.runs);
3754                }
3755                for (ledger, entries) in [
3756                    (&mut task.decision_effects, stale.decision_effects),
3757                    (&mut task.superseded_resumes, stale.superseded_resumes),
3758                    (&mut task.dispatched_resumes, stale.dispatched_resumes),
3759                ] {
3760                    for (key, value) in entries {
3761                        ledger.entry(key).or_insert(value);
3762                    }
3763                }
3764                append_missing(&mut task.actions_applied, stale.actions_applied);
3765                append_missing(&mut task.triage_applied, stale.triage_applied);
3766                append_missing(&mut task.chat_notices, stale.chat_notices);
3767                append_missing(
3768                    &mut task.base_recovery_requests,
3769                    stale.base_recovery_requests,
3770                );
3771                append_missing(
3772                    &mut task.land_sync_recovery_requests,
3773                    stale.land_sync_recovery_requests,
3774                );
3775                // The tail is the current grant. Older receipts must not replace
3776                // it or bring back their queued status or exact-run pins.
3777                prepend_missing_by(&mut task.repair_grants, stale.repair_grants, |a, b| {
3778                    a.request.request == b.request.request
3779                });
3780                prepend_missing_by(
3781                    &mut task.repair_reconciliations,
3782                    stale.repair_reconciliations,
3783                    |a, b| a.request.request == b.request.request,
3784                );
3785                // A triage effect can refer to an approval from the stale writer.
3786                // Retain it for proof, never as the active release.
3787                stale.resumption_history.extend(stale.resumption);
3788                stale.resumption_history.retain(|approval| {
3789                    task.resumption
3790                        .as_ref()
3791                        .is_none_or(|r| r.at != approval.at || r.generation != approval.generation)
3792                });
3793                prepend_missing_by(
3794                    &mut task.resumption_history,
3795                    stale.resumption_history,
3796                    |a, b| a.at == b.at && a.generation == b.generation,
3797                );
3798                for failure in stale.startup_failures {
3799                    task.record_startup_failure(failure);
3800                }
3801                for pass in stale.passes {
3802                    if !task.passes.iter().any(|stored| {
3803                        stored.run == pass.run && stored.pass_index == pass.pass_index
3804                    }) {
3805                        task.passes.push(pass);
3806                    }
3807                }
3808                task.completion_history = history;
3809                if !task.decision_effects.is_empty() {
3810                    task.stamp_schema();
3811                }
3812                return;
3813            }
3814            if stored.reassignments.len() > task.reassignments.len() {
3815                // An older writer may contribute evidence, but cannot restore
3816                // old execution selections, status, or runs across the boundary.
3817                let stale = std::mem::replace(task, stored.clone());
3818                for answer in stale.answers {
3819                    if !task.answers.contains(&answer) {
3820                        task.answers.push(answer);
3821                    }
3822                }
3823            }
3824            // Receipt history is append-only; control state comes from the
3825            // newer snapshot, not from whichever writer happens to keep a receipt.
3826            if task.updated_at < stored.updated_at
3827                && (task.sync_only != stored.sync_only
3828                    || stored.sync_only.is_some()
3829                    || (task.reopen_hold.is_some() && task.reopen_hold != stored.reopen_hold)
3830                    || stored
3831                        .recovery_budget_hold
3832                        .as_ref()
3833                        .is_some_and(|hold| hold.held_at > task.updated_at)
3834                    || stored.repair_grants.last().is_some_and(|grant| {
3835                        task.repair_grants.last() != Some(grant)
3836                            || stored.operator_decided_at > task.operator_decided_at
3837                            || stored
3838                                .resume_override
3839                                .as_ref()
3840                                .is_some_and(|pin| pin.at > task.updated_at)
3841                            || (task.resume_override != stored.resume_override
3842                                && task
3843                                    .resume_override
3844                                    .as_ref()
3845                                    .is_some_and(|pin| pin.at == grant.at))
3846                    }))
3847                && task
3848                    .operator_decided_at
3849                    .is_none_or(|at| at <= stored.updated_at)
3850                && task
3851                    .resume_override
3852                    .as_ref()
3853                    .is_none_or(|pin| pin.at <= stored.updated_at)
3854                && !local_decision
3855            {
3856                *task = stored.clone();
3857            }
3858            task.completion_history = history;
3859            append_missing(
3860                &mut task.base_recovery_requests,
3861                stored.base_recovery_requests,
3862            );
3863            append_missing(
3864                &mut task.land_sync_recovery_requests,
3865                stored.land_sync_recovery_requests,
3866            );
3867            append_missing(&mut task.actions_applied, stored.actions_applied);
3868            append_missing(&mut task.triage_applied, stored.triage_applied);
3869            for receipt in &stored.repair_grants {
3870                if !task
3871                    .repair_grants
3872                    .iter()
3873                    .any(|r| r.request.request == receipt.request.request)
3874                {
3875                    // History can be recovered independently of the live pin.
3876                    task.repair_grants.push(receipt.clone());
3877                }
3878            }
3879            for receipt in &stored.repair_reconciliations {
3880                if !task.repair_reconciliations.contains(receipt) {
3881                    // A pre-reconciliation snapshot must preserve the recovery's
3882                    // exact-run queue pin and release state with its receipt.
3883                    task.repair_reconciliations.push(receipt.clone());
3884                    task.resume_override = stored.resume_override.clone();
3885                    task.status = stored.status;
3886                    task.hold_source = stored.hold_source;
3887                    task.machine_hold_cause = stored.machine_hold_cause.clone();
3888                    task.disk_resume_run = stored.disk_resume_run.clone();
3889                    task.disk_checked_at = stored.disk_checked_at;
3890                    task.hold_reason = stored.hold_reason.clone();
3891                    task.held_at = stored.held_at;
3892                }
3893            }
3894            task.superseded_resumes.extend(stored.superseded_resumes);
3895            task.dispatched_resumes.extend(stored.dispatched_resumes);
3896            if task.status != TaskStatus::Running
3897                && let Some(pin) = &stored.resume_override
3898                && !pin.question_id.is_empty()
3899                && let Some(run) = &pin.pinned_run
3900                && task.resume_override.as_ref().is_none_or(|next| {
3901                    next.question_id != pin.question_id || next.pinned_run != pin.pinned_run
3902                })
3903            {
3904                task.superseded_resumes
3905                    .insert(pin.question_id.clone(), run.clone());
3906            }
3907            // A writer holding an older task snapshot must never erase or
3908            // rewrite proof that a chat command already committed its effect.
3909            for (id, receipt) in stored.decision_effects {
3910                task.decision_effects.insert(id, receipt);
3911            }
3912            if !task.decision_effects.is_empty() {
3913                task.stamp_schema();
3914            }
3915            // The task's message chat is recorded once and never rewound or
3916            // dropped by a writer holding an older snapshot.
3917            if task.chat.is_none() {
3918                task.chat = stored.chat.clone();
3919            }
3920            if task.issue.is_none() {
3921                task.issue = stored.issue.clone();
3922            }
3923            append_missing(&mut task.chat_notices, stored.chat_notices);
3924            for failure in stored.startup_failures {
3925                task.record_startup_failure(failure);
3926            }
3927            append_missing(&mut task.runs, stored.runs);
3928            for p in stored.passes {
3929                if !task
3930                    .passes
3931                    .iter()
3932                    .any(|q| q.run == p.run && q.pass_index == p.pass_index)
3933                {
3934                    task.passes.push(p);
3935                }
3936            }
3937            // A completion notice already recorded is never rewound by an
3938            // older snapshot: that would report the same state twice.
3939            if let Some(n) = stored.chat_notice
3940                && task.chat_notice.as_ref().is_none_or(|mine| mine.at < n.at)
3941            {
3942                task.chat_notice = Some(n);
3943            }
3944        }
3945    }
3946
3947    /// Audit-only update; caller holds the task write lock and claim. Preserve
3948    /// timestamps, controls and notification state while appending startup evidence.
3949    pub(crate) fn write_startup_history(&self, task: &Task) -> Result<()> {
3950        let path = self.path_of(&task.id);
3951        let tmp = path.with_extension("json.tmp");
3952        std::fs::write(&tmp, serde_json::to_vec_pretty(task)?)?;
3953        std::fs::rename(tmp, path)?;
3954        Ok(())
3955    }
3956
3957    /// Stamp and write `task` atomically; the caller holds the id's lock.
3958    fn write_record(&self, task: &mut Task) -> Result<()> {
3959        self.write_record_inner(task, true)
3960    }
3961
3962    fn write_record_inner(&self, task: &mut Task, notify: bool) -> Result<()> {
3963        task.import_chat_notice();
3964        if task.status != TaskStatus::Held && task.sync_only.is_none() {
3965            task.recovery_budget_hold = None;
3966        }
3967        task.updated_at = Timestamp::now();
3968        std::fs::create_dir_all(&self.root)
3969            .with_context(|| format!("create {}", self.root.display()))?;
3970        let body = serde_json::to_string_pretty(task).context("serialize task")?;
3971        let path = self.path_of(&task.id);
3972        let tmp = path.with_extension("json.tmp");
3973        std::fs::write(&tmp, &body).with_context(|| format!("write {}", tmp.display()))?;
3974        std::fs::rename(&tmp, &path).with_context(|| format!("replace {}", path.display()))?;
3975        // A machine hold is news for the notification centre, filed beside
3976        // this queue (`<home>/queue` -> `<home>/notifications`) rather than
3977        // through a process-global, so a queue in a temp directory notifies
3978        // into that directory.
3979        if let (Some(notice), Some(home)) = (
3980            notify.then(|| crate::notices::task_held(task)).flatten(),
3981            self.root.parent().filter(|p| !p.as_os_str().is_empty()),
3982        ) {
3983            crate::notices::raise_in(home, notice);
3984        }
3985        Ok(())
3986    }
3987
3988    /// Change the task `id` in place: read it inside its write lock, let `f`
3989    /// edit it, and write it back only when `f` returns `true`. The check a
3990    /// caller makes in `f` therefore sees the record as stored now, not a
3991    /// snapshot taken before another writer got in. Returns whether it wrote.
3992    pub fn modify(&self, id: &str, f: impl FnOnce(&mut Task) -> bool) -> Result<bool> {
3993        let id = self.resolve_id(id)?;
3994        let _lock = self.lock_task(&id)?;
3995        let mut task = self.get(&id)?;
3996        if !f(&mut task) {
3997            return Ok(false);
3998        }
3999        self.put_unlocked(&mut task)?;
4000        Ok(true)
4001    }
4002
4003    /// Append `run` to the runs of the task `id` (or an unambiguous prefix),
4004    /// leaving everything else about it alone — see [`Task::link_run`]. Read
4005    /// and written back in one breath, because [`Queue::put`] replaces the
4006    /// whole record. Returns the task as stored.
4007    pub fn link_run(&self, id: &str, run: &str) -> Result<Task> {
4008        let id = self.resolve_id(id)?;
4009        // Read inside the lock, so the record written back is the current one
4010        // and a daemon's write cannot slip between the read and the write.
4011        let _lock = self.lock_task(&id)?;
4012        let mut task = self.get(&id)?;
4013        if task.link_run(run) {
4014            self.put_unlocked(&mut task)?;
4015        }
4016        Ok(task)
4017    }
4018
4019    /// Exclusive right to rewrite task `id`'s record, held until the guard
4020    /// drops. Every writer ([`Queue::put`], [`Queue::link_run`]) takes it, so
4021    /// a process linking a run and the daemon saving a transition are
4022    /// serialized instead of last-writer-wins. An old lock may be broken only
4023    /// after its writer is confirmed dead (legacy tokens without a PID retain
4024    /// age-based recovery). Not the claim lock (`<id>.lock`), held for a
4025    /// whole run.
4026    pub(crate) fn lock_task(&self, id: &str) -> Result<TaskLock> {
4027        std::fs::create_dir_all(&self.root)
4028            .with_context(|| format!("create {}", self.root.display()))?;
4029        let path = self.root.join(format!("{id}.write-lock"));
4030        let started = std::time::Instant::now();
4031        let retry = crate::lock_file::Retry::task_write(started + TASK_LOCK_STALE);
4032        let marker_retry = crate::lock_file::Retry::new(Some(started + TASK_LOCK_STALE));
4033        loop {
4034            match retry.create(&path) {
4035                Ok(mut file) => {
4036                    use std::io::Write;
4037                    let token = owner_token();
4038                    if let Err(e) = file.write_all(token.as_bytes()) {
4039                        drop(file);
4040                        let _ = std::fs::remove_file(&path);
4041                        return Err(e).with_context(|| format!("lock {}", path.display()));
4042                    }
4043                    return Ok(TaskLock { path, token });
4044                }
4045                Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4046                    // Content first, then age: a lock replaced in between
4047                    // reads fresh, never stale.
4048                    let judged = std::fs::read_to_string(&path).ok();
4049                    let broken = judged
4050                        .filter(|_| older_than_stale(&path))
4051                        .is_some_and(|judged| break_stale_with(&path, &judged, marker_retry));
4052                    // A break that does not happen (marker busy, recovery
4053                    // exhausted) is a wait like any other, so it meets the
4054                    // same deadline instead of spinning forever.
4055                    if !broken {
4056                        if started.elapsed() > TASK_LOCK_STALE {
4057                            bail!("could not lock task {id}");
4058                        }
4059                        std::thread::sleep(std::time::Duration::from_millis(15));
4060                    }
4061                }
4062                Err(e) => return Err(e).with_context(|| format!("lock {}", path.display())),
4063            }
4064        }
4065    }
4066
4067    /// Load a task by id or unambiguous id prefix.
4068    pub fn get(&self, id: &str) -> Result<Task> {
4069        let resolved = self.resolve_id(id)?;
4070        read_path(&self.path_of(&resolved))
4071    }
4072
4073    /// Remove a task, and the claim lock that belongs to it.
4074    ///
4075    /// `in_flight` comes from the caller — a live daemon's heartbeat naming
4076    /// this task — because the task's own `running` status cannot answer the
4077    /// question. A daemon killed mid-competition leaves the status at
4078    /// `running` and an orphaned `.lock` behind, and a guard that trusted
4079    /// either would make the task undeletable for good: the phone showed
4080    /// exactly that, refusing a task whose daemon had been gone for an hour.
4081    ///
4082    /// So the lock is removed with the task rather than respected. Any lock
4083    /// still there once no live daemon claims the task is by definition stale,
4084    /// and leaving it would make a deleted task look claimed to
4085    /// [`Queue::claim`] and to whoever reads the directory.
4086    ///
4087    /// A deletion is deliberate, so whatever was `blocked` on the id is
4088    /// resolved, not held: a `<id>.removed` tombstone is written first (it
4089    /// is what tells [`missing_blockers`] and the daemon's resolver that this
4090    /// id was deleted on purpose, so a pass that races this call cannot
4091    /// mistake it for a vanished dependency), the record is deleted (the
4092    /// tombstone is taken back if that fails), and then each dependent is
4093    /// rewritten under its claim - see [`Queue::release_dependents_of`].
4094    /// Best-effort for the dependents: one claimed by something else right
4095    /// now, or whose write fails, is released silently by
4096    /// `crate::daemon::resolve_blockers` (or `crate::triage::run_once`) on
4097    /// its next pass, because the tombstone is still there. It does not fail
4098    /// this removal.
4099    ///
4100    /// `questions` is the store [`missing_blockers`] checks a `blocked_by` id
4101    /// against - the same store the caller already resolves `id`'s own home
4102    /// from, passed in rather than reopened here so a test queue at an
4103    /// explicit root never reads the operator's real questions directory.
4104    pub fn remove(&self, id: &str, in_flight: bool, questions: &Questions) -> Result<Removal> {
4105        self.remove_with_receipt(id, in_flight, questions, None)
4106    }
4107
4108    /// Atomically retain the deleted task as the receipt for this triage inquiry.
4109    pub(crate) fn discard_triage(
4110        &self,
4111        id: &str,
4112        questions: &Questions,
4113        inquiry: &str,
4114    ) -> Result<Removal> {
4115        self.remove_with_receipt(id, false, questions, Some(inquiry))
4116    }
4117
4118    pub(crate) fn triage_discard_applied(&self, id: &str, inquiry: &str) -> Result<bool> {
4119        let path = self
4120            .root
4121            .join("triage-discard")
4122            .join(format!("{inquiry}.json"));
4123        let bytes = match std::fs::read(path) {
4124            Ok(bytes) => bytes,
4125            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(false),
4126            Err(e) => return Err(e.into()),
4127        };
4128        let receipt: Task = serde_json::from_slice(&bytes)?;
4129        Ok(receipt.id == id && !self.path_of(id).exists())
4130    }
4131
4132    fn remove_with_receipt(
4133        &self,
4134        id: &str,
4135        in_flight: bool,
4136        questions: &Questions,
4137        inquiry: Option<&str>,
4138    ) -> Result<Removal> {
4139        let resolved = self.resolve_id(id)?;
4140        if in_flight {
4141            bail!("task {resolved} is being run by a live daemon right now");
4142        }
4143        let receipt = inquiry.map(|q| self.root.join("triage-discard").join(format!("{q}.json")));
4144        if let Some(path) = &receipt {
4145            std::fs::create_dir_all(path.parent().expect("receipt directory"))?;
4146        }
4147        self.write_tombstone(&resolved)?;
4148        if let Err(e) = self.remove_record_with_attachments(&resolved, |p| match &receipt {
4149            Some(path) => std::fs::rename(p, path),
4150            None => std::fs::remove_file(p),
4151        }) {
4152            // A record that is still there was not deleted: take the marker
4153            // back. One already gone keeps it, so the deletion still reads
4154            // as deliberate.
4155            if self.path_of(&resolved).exists() {
4156                let _ = std::fs::remove_file(self.tombstone_path(&resolved));
4157            }
4158            return Err(e);
4159        }
4160        let (released, still_blocked) = self.release_dependents_of(&resolved, questions);
4161        Ok(Removal {
4162            id: resolved,
4163            released,
4164            still_blocked,
4165        })
4166    }
4167
4168    /// Path of the marker saying task `id` was deleted on purpose. Not a
4169    /// `*.json`, so [`Queue::list`] and [`Queue::revision`] never see it.
4170    fn tombstone_path(&self, id: &str) -> PathBuf {
4171        self.root.join(format!("{id}.removed"))
4172    }
4173
4174    fn write_tombstone(&self, id: &str) -> Result<()> {
4175        let path = self.tombstone_path(id);
4176        let tmp = self.root.join(format!("{id}.removed.tmp"));
4177        std::fs::write(&tmp, b"")
4178            .and_then(|()| std::fs::rename(&tmp, &path))
4179            .with_context(|| format!("write {}", path.display()))
4180    }
4181
4182    /// Was `id` deleted through [`Queue::remove`] (and is its record gone)?
4183    /// A live record always wins: a tombstone never makes an existing task
4184    /// look deleted.
4185    fn was_deleted(&self, id: &str) -> bool {
4186        self.tombstone_path(id).is_file() && !self.path_of(id).exists()
4187    }
4188
4189    /// Apply [`Task::dependency_deleted`] to `task` for every `blocked_by` id
4190    /// that [`Queue::remove`] deleted. Returns those ids. The caller holds
4191    /// the task's claim and saves it.
4192    pub fn apply_deleted_blockers(&self, task: &mut Task, questions: &Questions) -> Vec<String> {
4193        let deleted = deleted_blockers(self, questions, &task.blocked_by);
4194        deleted
4195            .into_iter()
4196            .filter(|id| task.dependency_deleted(id))
4197            .collect()
4198    }
4199
4200    /// Record, as a fixed-wording info notice, that `dependent` stopped
4201    /// waiting on the deleted task `deleted`. Best-effort and beside the
4202    /// queue, like the hold notice [`Queue::put`] files.
4203    pub fn note_dependency_deleted(&self, dependent: &Task, deleted: &str) {
4204        let Some(home) = self.root.parent().filter(|p| !p.as_os_str().is_empty()) else {
4205            return;
4206        };
4207        let ja = crate::lang::is_japanese(&crate::lang::of_repo(&dependent.repo));
4208        let waiting = dependent.status == TaskStatus::Blocked;
4209        let message = match (ja, waiting) {
4210            (true, false) => format!(
4211                "タスク {} は、待っていた {} が削除されたため待機を解除し、元の状態に戻しました",
4212                dependent.short(),
4213                short(deleted)
4214            ),
4215            (true, true) => format!(
4216                "タスク {} は、待っていた {} が削除されたため、残りの依存を待っています",
4217                dependent.short(),
4218                short(deleted)
4219            ),
4220            (false, false) => format!(
4221                "Task {} stopped waiting on {} because it was deleted, and returned to its previous state",
4222                dependent.short(),
4223                short(deleted)
4224            ),
4225            (false, true) => format!(
4226                "Task {} stopped waiting on {} because it was deleted, and is still waiting on its other dependencies",
4227                dependent.short(),
4228                short(deleted)
4229            ),
4230        };
4231        crate::notices::raise_in(
4232            home,
4233            crate::notices::Notice::info(
4234                &format!("unblocked:{}:{}", dependent.id, deleted),
4235                message,
4236            )
4237            .link(crate::notices::Link::Task {
4238                id: dependent.id.clone(),
4239            }),
4240        );
4241    }
4242
4243    /// Resolve every `blocked` task naming `dependency` (just deleted) with
4244    /// [`Task::dependency_deleted`]. Returns the ids released to another
4245    /// status and those that remain `blocked` on something else. Each
4246    /// dependent is re-read inside its claim, never written from a stale copy.
4247    fn release_dependents_of(
4248        &self,
4249        dependency: &str,
4250        questions: &Questions,
4251    ) -> (Vec<String>, Vec<String>) {
4252        let (mut released, mut still_blocked) = (Vec::new(), Vec::new());
4253        for listed in self.list() {
4254            if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| {
4255                matches!(crate::queue::dependency(self, questions, b), Dependency::Deleted(id) if id == dependency)
4256            }) {
4257                continue;
4258            }
4259            let Ok(_claim) = self.claim(&listed.id) else {
4260                continue;
4261            };
4262            let Ok(mut task) = self.get(&listed.id) else {
4263                continue;
4264            };
4265            let references: Vec<String> = task.blocked_by.iter().filter(|id| {
4266                matches!(crate::queue::dependency(self, questions, id), Dependency::Deleted(full) if full == dependency)
4267            }).cloned().collect();
4268            if references.is_empty() {
4269                continue;
4270            }
4271            for reference in references {
4272                task.dependency_deleted(&reference);
4273            }
4274            if self.put(&mut task).is_err() {
4275                continue;
4276            }
4277            self.note_dependency_deleted(&task, dependency);
4278            if task.status == TaskStatus::Blocked {
4279                still_blocked.push(task.id.clone());
4280            } else {
4281                released.push(task.id.clone());
4282            }
4283        }
4284        (released, still_blocked)
4285    }
4286
4287    /// The attachment-and-record half of [`Queue::remove`]. `remove_record` is
4288    /// how the record file is deleted; production passes `remove_file`, and a
4289    /// test passes a failing one to prove the attachments come back.
4290    fn remove_record_with_attachments(
4291        &self,
4292        resolved: &str,
4293        remove_record: impl FnOnce(&Path) -> std::io::Result<()>,
4294    ) -> Result<()> {
4295        // Neither step may strand the other. The attachments are set aside by a
4296        // rename (cheap, and undone if the record cannot be removed), then the
4297        // record goes, and only then is the set-aside directory deleted for
4298        // real. A failure before the record is gone loses nothing; a failure
4299        // after it leaves at most an orphan `.removing` directory, which the
4300        // next removal sweeps.
4301        self.sweep_removed_attachments();
4302        let attachments = self.attachments_dir(resolved);
4303        let aside = self.root.join(format!("{resolved}.attachments.removing"));
4304        let moved = match std::fs::rename(&attachments, &aside) {
4305            Ok(()) => true,
4306            Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
4307            Err(e) => {
4308                return Err(e).with_context(|| format!("remove {}", attachments.display()));
4309            }
4310        };
4311        let path = self.path_of(resolved);
4312        if let Err(e) = remove_record(&path) {
4313            if moved {
4314                let _ = std::fs::rename(&aside, &attachments);
4315            }
4316            return Err(e).with_context(|| format!("remove {}", path.display()));
4317        }
4318        if moved {
4319            if let Err(e) = std::fs::remove_dir_all(&aside) {
4320                tracing::warn!("leftover attachments {}: {e}", aside.display());
4321            }
4322        }
4323        let lock = self.lock_path(resolved);
4324        if let Err(e) = std::fs::remove_file(&lock) {
4325            if e.kind() != std::io::ErrorKind::NotFound {
4326                return Err(e).with_context(|| format!("remove {}", lock.display()));
4327            }
4328        }
4329        Ok(())
4330    }
4331
4332    /// Delete `*.attachments.removing` directories a previous [`Queue::remove`]
4333    /// could not finish deleting. The task record is already gone by then, so
4334    /// the id no longer resolves and the removal cannot be retried by name;
4335    /// every later removal sweeps them instead. A directory whose record still
4336    /// exists belongs to a removal in progress and is left alone. Best-effort.
4337    fn sweep_removed_attachments(&self) {
4338        let Ok(entries) = std::fs::read_dir(&self.root) else {
4339            return;
4340        };
4341        for entry in entries.flatten() {
4342            let name = entry.file_name();
4343            let name = name.to_string_lossy();
4344            let Some(id) = name.strip_suffix(".attachments.removing") else {
4345                continue;
4346            };
4347            // A record still on disk means a removal is mid-flight (or about
4348            // to roll back): the directory is its to delete or restore.
4349            if !self.path_of(id).exists() {
4350                if let Err(e) = std::fs::remove_dir_all(entry.path()) {
4351                    tracing::warn!("leftover attachments {}: {e}", entry.path().display());
4352                }
4353            }
4354        }
4355        self.sweep_tombstones();
4356    }
4357
4358    /// Delete `*.removed` markers that are no longer needed: the record is
4359    /// gone, no task's `blocked_by` names the id, and the marker is older than
4360    /// [`TOMBSTONE_GRACE`]. The age is what makes this safe against a
4361    /// concurrent writer: the task list read here can be stale, so a dependent
4362    /// that was just blocked on an id (a conductor applying a decision while a
4363    /// removal is under way) would otherwise lose the marker and be held as a
4364    /// vanished dependency. A marker whose record still exists belongs to a
4365    /// removal in progress and is never touched.
4366    fn sweep_tombstones(&self) {
4367        let Ok(entries) = std::fs::read_dir(&self.root) else {
4368            return;
4369        };
4370        let tasks = self.list();
4371        for entry in entries.flatten() {
4372            let name = entry.file_name();
4373            let name = name.to_string_lossy();
4374            let Some(id) = name.strip_suffix(".removed") else {
4375                continue;
4376            };
4377            if self.path_of(id).exists()
4378                || tasks.iter().any(|t| {
4379                    t.blocked_by
4380                        .iter()
4381                        .any(|b| id.starts_with(b) || id.ends_with(b))
4382                })
4383            {
4384                continue;
4385            }
4386            let old = entry
4387                .metadata()
4388                .and_then(|m| m.modified())
4389                .ok()
4390                .and_then(|m| m.elapsed().ok())
4391                .is_some_and(|age| age >= TOMBSTONE_GRACE);
4392            if old {
4393                let _ = std::fs::remove_file(entry.path());
4394            }
4395        }
4396    }
4397
4398    /// Path of the claim lock for a task. One definition, so `claim` and
4399    /// `remove` cannot end up naming different files.
4400    fn lock_path(&self, id: &str) -> PathBuf {
4401        self.root.join(format!("{id}.lock"))
4402    }
4403
4404    /// Every task on disk, highest priority first and newest first within a
4405    /// priority. This is what `magi task list` and `GET /api/queue` print, so
4406    /// a raised priority has to move a task here the moment it is saved, not
4407    /// only in [`Queue::next_runnable`]'s own ordering - the operator reading
4408    /// the backlog and the loop about to drain it must agree on what "first"
4409    /// means. Every existing task defaults to priority 0, so this is a no-op
4410    /// change from the old newest-first order for a queue nobody has
4411    /// reprioritised.
4412    ///
4413    /// Unreadable files are skipped rather than fatal: one corrupt task must
4414    /// not take the queue - or the web UI, or an unattended daemon - down
4415    /// with it.
4416    pub fn list(&self) -> Vec<Task> {
4417        #[cfg(test)]
4418        LIST_READS.with(|count| count.set(count.get() + 1));
4419        let mut tasks: Vec<Task> = std::fs::read_dir(&self.root)
4420            .into_iter()
4421            .flatten()
4422            .flatten()
4423            .map(|e| e.path())
4424            .filter(|p| p.extension().is_some_and(|x| x == "json"))
4425            .filter_map(|p| read_path(&p).ok())
4426            .collect();
4427        tasks.sort_unstable_by(|a, b| b.priority.cmp(&a.priority).then_with(|| b.id.cmp(&a.id)));
4428        tasks
4429    }
4430
4431    /// Task files [`Queue::list`] skips because they cannot be parsed (a
4432    /// newer schema, a torn write). A guard that looks a task up by scanning
4433    /// the list must treat any of these as "the task might be there".
4434    pub fn unreadable(&self) -> Vec<PathBuf> {
4435        std::fs::read_dir(&self.root)
4436            .into_iter()
4437            .flatten()
4438            .flatten()
4439            .map(|e| e.path())
4440            .filter(|p| p.extension().is_some_and(|x| x == "json"))
4441            .filter(|p| read_path(p).is_err())
4442            .collect()
4443    }
4444
4445    /// Runs that a later attempt at the same task replaced, mapped to the id
4446    /// of the attempt that replaced them.
4447    ///
4448    /// A task keeps its attempts in order, and the deck showed them as two
4449    /// cards with the same title and no hint which was which: yukimemi asked
4450    /// why `stalled` and `blocked` appeared twice for one task, and the
4451    /// answer - "those are two tries, and the second one exists because of a
4452    /// bug since fixed" - was not on the screen anywhere.
4453    ///
4454    /// Read from the queue rather than stored on the run, because the
4455    /// ordering is the queue's fact: a `RunState` has no idea another attempt
4456    /// happened after it.
4457    pub fn superseded(&self) -> HashMap<String, String> {
4458        let mut by = HashMap::new();
4459        for task in self.list() {
4460            for earlier in &task.runs {
4461                if let Some(later) = task.successor_of(earlier) {
4462                    by.insert(earlier.clone(), later.clone());
4463                }
4464            }
4465        }
4466        by
4467    }
4468
4469    /// Whether `run` is an earlier attempt a later one replaced, and if so
4470    /// the id of that later attempt.
4471    ///
4472    /// Same walk as [`Queue::superseded`], narrowed to one run: a run detail
4473    /// page asks about exactly one run at a time, and this keeps that call
4474    /// site from building (and discarding) the whole map's `HashMap` just to
4475    /// read one entry out of it.
4476    pub fn superseded_by(&self, run: &str) -> Option<String> {
4477        for task in self.list() {
4478            if task.runs.iter().any(|r| r == run) {
4479                return task.successor_of(run).cloned();
4480            }
4481        }
4482        None
4483    }
4484
4485    /// The task's own most recent attempt, when `run` belongs to that task
4486    /// but is not already that attempt.
4487    ///
4488    /// Distinct from [`Queue::superseded_by`], which names only the very
4489    /// next attempt: a chain of retries (A superseded by B superseded by C)
4490    /// leaves an older run pointing at an intermediate one that may itself
4491    /// be unresolved, and a run's own detail page needs to know where the
4492    /// task's story currently stands - the chain's current head, C - not an
4493    /// attempt in the middle of it that a client would otherwise have to
4494    /// walk to by hand.
4495    pub fn latest_attempt(&self, run: &str) -> Option<String> {
4496        for task in self.list() {
4497            if task.runs.iter().any(|r| r == run) {
4498                return task.runs.last().filter(|last| **last != run).cloned();
4499            }
4500        }
4501        None
4502    }
4503
4504    /// The task a daemon should run next, or `None` when the queue is idle.
4505    ///
4506    /// Upgrade resumes first, then highest priority and oldest id first.
4507    /// See [`dispatch_order`] for the durable ordering rule.
4508    pub fn next_runnable(&self) -> Option<Task> {
4509        let mut runnable: Vec<Task> = self
4510            .list()
4511            .into_iter()
4512            .filter(|t| t.status.runnable())
4513            .collect();
4514        runnable.sort_unstable_by(dispatch_order);
4515        runnable.into_iter().next()
4516    }
4517
4518    /// Take exclusive ownership of a task.
4519    ///
4520    /// The lock is a `create_new` file next to the task, which is atomic on
4521    /// every platform magi targets. It exists so two daemons - or a daemon and
4522    /// a human running `magi run` - cannot drive one task into two competing
4523    /// runs. The returned guard releases on drop, including on panic.
4524    pub fn claim(&self, id: &str) -> Result<Claim> {
4525        std::fs::create_dir_all(&self.root)
4526            .with_context(|| format!("create {}", self.root.display()))?;
4527        let path = self.lock_path(id);
4528        let retry = crate::lock_file::Retry::new(None);
4529        match retry.create(&path) {
4530            Ok(mut f) => {
4531                use std::io::Write as _;
4532                // Best effort: the pid is for the human looking at a stale lock.
4533                let _ = writeln!(f, "{}", std::process::id());
4534                Ok(Claim { path })
4535            }
4536            Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
4537                bail!("task {id} is already claimed ({} exists)", path.display())
4538            }
4539            Err(e) => Err(e).with_context(|| format!("lock {}", path.display())),
4540        }
4541    }
4542
4543    /// Read-only check for whether a queue claim lock file currently exists for
4544    /// `id`. Never acquires, modifies, or removes the lock.
4545    #[must_use]
4546    pub fn is_claimed(&self, id: &str) -> bool {
4547        self.lock_path(id).exists()
4548    }
4549
4550    /// Expand an id prefix to exactly one task id.
4551    pub fn resolve_id(&self, prefix: &str) -> Result<String> {
4552        if !prefix.is_empty()
4553            && prefix != "."
4554            && prefix != ".."
4555            && !prefix.contains(['/', '\\'])
4556            && self.path_of(prefix).is_file()
4557        {
4558            return Ok(prefix.to_owned());
4559        }
4560        let ids = record_ids(&self.root, "json")?;
4561        match resolve_reference(prefix, ids.iter().map(String::as_str)) {
4562            Reference::Found(id) => Ok(id),
4563            Reference::Missing => bail!("no task matches `{prefix}`"),
4564            Reference::Ambiguous => bail!("`{prefix}` matches multiple tasks"),
4565        }
4566    }
4567
4568    /// Change detection token for the queue.
4569    ///
4570    /// Combines file names and modification times of all task files in the
4571    /// queue, so adding, modifying, or deleting any task — even an older one —
4572    /// moves the revision and notifies connected clients via the change stream.
4573    /// Returns 0 when the queue is completely empty.
4574    pub fn revision(&self) -> u64 {
4575        self.revision_excluding(&std::collections::BTreeSet::new())
4576    }
4577
4578    /// [`Queue::revision`] ignoring the files of the named task ids, for a
4579    /// caller that tracks those tasks' content some other way.
4580    pub fn revision_excluding(&self, skip: &std::collections::BTreeSet<String>) -> u64 {
4581        use std::hash::{Hash as _, Hasher as _};
4582
4583        let mut entries: Vec<(String, u64)> = std::fs::read_dir(&self.root)
4584            .into_iter()
4585            .flatten()
4586            .flatten()
4587            .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))
4588            .filter(|e| {
4589                let path = e.path();
4590                !path
4591                    .file_stem()
4592                    .is_some_and(|stem| skip.contains(stem.to_string_lossy().as_ref()))
4593            })
4594            .filter_map(|e| {
4595                let name = e.file_name().to_string_lossy().into_owned();
4596                let mtime = e
4597                    .metadata()
4598                    .ok()?
4599                    .modified()
4600                    .ok()?
4601                    .duration_since(std::time::UNIX_EPOCH)
4602                    .ok()?
4603                    .as_millis() as u64;
4604                Some((name, mtime))
4605            })
4606            .collect();
4607
4608        if entries.is_empty() {
4609            return 0;
4610        }
4611
4612        entries.sort_unstable();
4613        let mut hasher = std::hash::DefaultHasher::new();
4614        for (name, mtime) in &entries {
4615            name.hash(&mut hasher);
4616            mtime.hash(&mut hasher);
4617        }
4618        let h = hasher.finish();
4619        if h == 0 { 1 } else { h }
4620    }
4621}
4622
4623/// How long a deletion marker is kept after its record is gone, even with
4624/// nothing referencing it. See [`Queue::sweep_tombstones`].
4625const TOMBSTONE_GRACE: std::time::Duration = std::time::Duration::from_secs(3600);
4626
4627/// What [`Queue::remove`] did, beyond deleting the named task's own file.
4628#[derive(Debug, Clone)]
4629pub struct Removal {
4630    /// The id actually removed - `id` expanded from a prefix, if it was one.
4631    pub id: String,
4632    /// Every task that was `blocked` on [`Removal::id`] and left the block
4633    /// (back to the status it interrupted) because that was its only
4634    /// remaining dependency.
4635    pub released: Vec<String>,
4636    /// Every task that named [`Removal::id`] and is still `blocked` on
4637    /// another dependency.
4638    pub still_blocked: Vec<String>,
4639}
4640
4641/// Exclusive ownership of a task, released on drop.
4642#[derive(Debug)]
4643pub struct Claim {
4644    path: PathBuf,
4645}
4646
4647impl Drop for Claim {
4648    fn drop(&mut self) {
4649        let _ = std::fs::remove_file(&self.path);
4650    }
4651}
4652
4653/// The first line of a task, trimmed to a title. Used when the caller gives a
4654/// body but no title, which is the normal case for an agent piping a file in.
4655pub fn title_from(instruction: &str, max: usize) -> String {
4656    let Some(line) = first_line(instruction) else {
4657        return "(empty task)".to_owned();
4658    };
4659    if line.chars().count() <= max {
4660        return line.to_owned();
4661    }
4662    let head: String = line.chars().take(max.saturating_sub(1)).collect();
4663    format!("{head}…")
4664}
4665
4666/// The first non-blank line, whatever it is. A markdown heading is the
4667/// task's own summary - agents pipe in `# Rework the config loader` and mean
4668/// exactly that - so it is preferred over the prose beneath it rather than
4669/// skipped as decoration. Leading list and heading markers are stripped
4670/// because they are syntax, not words. `None` when nothing is left.
4671pub(crate) fn first_line(instruction: &str) -> Option<&str> {
4672    let line = instruction
4673        .lines()
4674        .map(str::trim)
4675        .find(|l| !l.is_empty())?
4676        .trim_start_matches(['#', '-', '*', '>', ' '])
4677        .trim();
4678    (!line.is_empty()).then_some(line)
4679}
4680
4681#[cfg(test)]
4682thread_local! {
4683    pub(crate) static TASK_READS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
4684}
4685
4686fn read_path(path: &Path) -> Result<Task> {
4687    #[cfg(test)]
4688    TASK_READS.with(|count| count.set(count.get() + 1));
4689    let body = std::fs::read_to_string(path).with_context(|| format!("read {}", path.display()))?;
4690    let mut task: Task =
4691        serde_json::from_str(&body).with_context(|| format!("parse {}", path.display()))?;
4692    // Greater-than, not not-equal: every field added since schema 1 carries
4693    // `#[serde(default)]`, so an older task has nothing to say about it and
4694    // defaulting is exactly as good a reading as a value that build never had
4695    // a chance to write. Only a schema *ahead* of this build - a meaning it
4696    // cannot possibly know - is refused rather than guessed at.
4697    if task.schema > SCHEMA {
4698        bail!(
4699            "task {} was written by a different magi (schema {}, this build \
4700             speaks {SCHEMA})",
4701            task.id,
4702            task.schema
4703        );
4704    }
4705    task.preserve_legacy_build_cache();
4706    task.snapshot_legacy_reopen_hold();
4707    if task.schema < 22
4708        && task.status == TaskStatus::Held
4709        && task.hold_source == Some(HoldSource::Machine)
4710        && task.resume_override.is_none()
4711        && task
4712            .hold_reason
4713            .as_deref()
4714            .is_some_and(crate::disk::is_gate_reason)
4715    {
4716        task.mark_disk_capacity();
4717    }
4718    Ok(task)
4719}
4720
4721/// Resolution shared by queue lookups and dependency inventories. Exact ids
4722/// win; otherwise both the CLI prefix and displayed suffix are supported.
4723#[derive(Debug, PartialEq, Eq)]
4724pub(crate) enum Reference {
4725    Found(String),
4726    Missing,
4727    Ambiguous,
4728}
4729
4730pub(crate) fn resolve_reference<'a>(id: &str, ids: impl Iterator<Item = &'a str>) -> Reference {
4731    let mut hits = Vec::new();
4732    for candidate in ids {
4733        if candidate == id {
4734            return Reference::Found(candidate.to_owned());
4735        }
4736        if candidate.starts_with(id) || candidate.ends_with(id) {
4737            hits.push(candidate);
4738        }
4739    }
4740    match hits.as_slice() {
4741        [] => Reference::Missing,
4742        [one] => Reference::Found((*one).to_owned()),
4743        _ => Reference::Ambiguous,
4744    }
4745}
4746
4747/// Read names, not deserialized records: list() intentionally skips corrupt
4748/// and future-schema records, which still exist and must keep their waiters.
4749pub(crate) fn record_ids(root: &Path, extension: &str) -> Result<Vec<String>> {
4750    let entries = match std::fs::read_dir(root) {
4751        Ok(entries) => entries,
4752        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Vec::new()),
4753        Err(e) => return Err(e.into()),
4754    };
4755    let mut ids = Vec::new();
4756    for entry in entries {
4757        let path = entry?.path();
4758        if path.extension().is_some_and(|e| e == extension)
4759            && let Some(id) = path.file_stem().and_then(|s| s.to_str())
4760        {
4761            ids.push(id.to_owned());
4762        }
4763    }
4764    Ok(ids)
4765}
4766
4767/// Unknown and ambiguous dependencies stay waiting; neither is evidence that
4768/// the operator deleted a prerequisite or needs to supply its replacement.
4769#[derive(Debug, PartialEq, Eq)]
4770pub enum Dependency {
4771    /// Existing task record, with its canonical id; its contents may be unreadable.
4772    Task(String),
4773    /// Existing question record, with its canonical id.
4774    Question(String),
4775    /// Explicitly removed task, identified by its tombstone.
4776    Deleted(String),
4777    /// No matching record or tombstone after a successful inventory read.
4778    Missing,
4779    /// More than one record matches the reference.
4780    Ambiguous,
4781    /// The inventory cannot currently be read, so existence is unknown.
4782    Unknown,
4783}
4784
4785/// Resolve against authoritative task, question and deletion record names.
4786pub fn dependency(queue: &Queue, questions: &Questions, id: &str) -> Dependency {
4787    let (Ok(tasks), Ok(qs), Ok(removed)) = (
4788        record_ids(queue.root(), "json"),
4789        record_ids(questions.root(), "json"),
4790        record_ids(queue.root(), "removed"),
4791    ) else {
4792        return Dependency::Unknown;
4793    };
4794    // Include tombstones in ambiguity checks: a reused suffix must never
4795    // release a waiter on a different, still-live task.
4796    let mut ids = tasks
4797        .iter()
4798        .chain(qs.iter())
4799        .chain(removed.iter())
4800        .cloned()
4801        .collect::<Vec<_>>();
4802    ids.sort();
4803    ids.dedup();
4804    match resolve_reference(id, ids.iter().map(String::as_str)) {
4805        Reference::Found(id) if tasks.contains(&id) => Dependency::Task(id),
4806        Reference::Found(id) if qs.contains(&id) => Dependency::Question(id),
4807        Reference::Found(id) if queue.was_deleted(&id) => Dependency::Deleted(id),
4808        Reference::Found(_) => Dependency::Unknown,
4809        Reference::Missing => Dependency::Missing,
4810        Reference::Ambiguous => Dependency::Ambiguous,
4811    }
4812}
4813
4814/// Canonicalize only proven dependencies, preserving unknown legacy references.
4815pub fn normalize_blockers(queue: &Queue, questions: &Questions, ids: &mut [String]) {
4816    for id in ids {
4817        if let Dependency::Task(full) | Dependency::Question(full) | Dependency::Deleted(full) =
4818            dependency(queue, questions, id)
4819        {
4820            *id = full;
4821        }
4822    }
4823}
4824
4825/// Live queue facts for decision and deputy prompts. Historical hold reasons
4826/// and question text are claims, never an inventory of existing prerequisites.
4827pub fn dependency_facts(queue: &Queue, questions: &Questions) -> String {
4828    let inventory = crate::blockers::Inventory::load(queue, questions);
4829    let mut text = String::from(
4830        "Current authoritative queue (historical missing-task claims may be stale; unreadable or ambiguous references must keep waiting):\n",
4831    );
4832    match record_ids(queue.root(), "json") {
4833        Ok(ids) => {
4834            for id in ids {
4835                match queue.get(&id) {
4836                    Ok(task) => text.push_str(&format!(
4837                        "{}: {}; blocked_by={:?}; chain={:?}\n",
4838                        task.id,
4839                        task.status.as_str(),
4840                        task.blocked_by,
4841                        inventory.waits_on(&task)
4842                    )),
4843                    Err(_) => text.push_str(&format!("{id}: exists, state unreadable\n")),
4844                }
4845            }
4846        }
4847        Err(_) => text.push_str("Queue inventory unreadable: existence is unknown.\n"),
4848    }
4849    text
4850}
4851
4852/// Only a successful directory scan with no matching record proves absence.
4853pub fn missing_blockers(
4854    queue: &Queue,
4855    questions: &Questions,
4856    blocked_by: &[String],
4857) -> Vec<String> {
4858    blocked_by
4859        .iter()
4860        .filter(|id| dependency(queue, questions, id) == Dependency::Missing)
4861        .cloned()
4862        .collect()
4863}
4864
4865/// Return the original references, so legacy short ids are removed by the
4866/// same Task transition as full ids.
4867pub fn deleted_blockers(
4868    queue: &Queue,
4869    questions: &Questions,
4870    blocked_by: &[String],
4871) -> Vec<String> {
4872    blocked_by
4873        .iter()
4874        .filter(|id| matches!(dependency(queue, questions, id), Dependency::Deleted(_)))
4875        .cloned()
4876        .collect()
4877}
4878
4879/// The `hold_reason` text for a task quarantined because one or more of its
4880/// `blocked_by` ids no longer exist. Shared by `crate::daemon::resolve_blockers`,
4881/// `crate::triage::run_once`, and [`Queue::remove`]'s own dependent
4882/// quarantine, so the three call sites read as the same event to an operator
4883/// looking at `magi task show` rather than three different wordings for it.
4884///
4885/// Names the full original `blocked_by` list, not just `missing` - a task
4886/// quarantined here can also have named a dependency that was still
4887/// perfectly valid, and [`Task::hold_machine`] clears `blocked_by` on the way
4888/// in, so this text is the only place that information survives for an
4889/// operator deciding whether to release the task outright.
4890pub fn missing_blocker_hold_reason(blocked_by: &[String], missing: &[String]) -> String {
4891    missing_blocker_hold_reason_in(blocked_by, missing, "en")
4892}
4893
4894/// [`missing_blocker_hold_reason`] in `language` (Japanese, else English).
4895pub fn missing_blocker_hold_reason_in(
4896    blocked_by: &[String],
4897    missing: &[String],
4898    language: &str,
4899) -> String {
4900    if crate::lang::is_japanese(language) {
4901        format!(
4902            "{} を待っていましたが、{} はディスク上に存在しません - `magi task triage` を参照",
4903            blocked_by.join(", "),
4904            missing.join(", "),
4905        )
4906    } else {
4907        format!(
4908            "blocked on {} but {} no longer exist(s) on disk - see `magi task triage`",
4909            blocked_by.join(", "),
4910            missing.join(", "),
4911        )
4912    }
4913}
4914
4915/// The last dash-separated part of an id, the form people say aloud.
4916pub fn short(id: &str) -> &str {
4917    id.split('-').next_back().unwrap_or(id)
4918}
4919
4920fn new_id() -> String {
4921    let stamp = jiff::Zoned::now().strftime("%Y%m%d-%H%M%S");
4922    let seed = crate::rng::entropy();
4923    format!("{stamp}-{:04x}", (seed ^ (seed >> 32)) & 0xffff)
4924}
4925
4926#[cfg(test)]
4927mod tests {
4928    #[test]
4929    fn reassignment_clears_repository_bound_execution_selections() {
4930        let mut task = Task::new(
4931            "move".into(),
4932            "evidence".into(),
4933            "old".into(),
4934            Source::Human,
4935        );
4936        task.review_branch = Some("old-review".into());
4937        task.review_instruction = Some("old criteria".into());
4938        task.pr_recovery = Some(crate::pr_recovery::Selection {
4939            url: "https://example.invalid/pull/1".into(),
4940            branch: "old-pr".into(),
4941            head: "head".into(),
4942            source_head: None,
4943            source_run: None,
4944            source_proof: None,
4945            disposition: None,
4946            instruction: "old criteria".into(),
4947            approved_at: Timestamp::now(),
4948        });
4949        task.replacement = Some(crate::merge_decision::Replacement {
4950            question: "owner".into(),
4951            run: "old-run".into(),
4952            pr: "https://example.invalid/pull/1".into(),
4953            agent: "worker".into(),
4954            context: "evidence".into(),
4955        });
4956        task.resume_override = Some(OperatorResume {
4957            question_id: "old-question".into(),
4958            at: Timestamp::now(),
4959            conductor_rehold: None,
4960            forced: true,
4961            pinned_run: Some("old-run".into()),
4962        });
4963        task.interrupt = true;
4964        task.reassign_repository("new".into(), "test");
4965        assert!(task.review_branch.is_none());
4966        assert!(task.review_instruction.is_none());
4967        assert!(task.pr_recovery.is_none());
4968        assert!(task.replacement.is_none());
4969        assert!(task.resume_override.is_none());
4970        assert!(!task.interrupt);
4971        assert!(task.fresh_start);
4972        assert_eq!(task.instruction, "evidence");
4973    }
4974
4975    #[test]
4976    fn explicit_resumption_is_not_invented_for_legacy_or_automatic_release() {
4977        let t = Task::new(
4978            "retry".into(),
4979            "do it".into(),
4980            PathBuf::from("."),
4981            Source::Human,
4982        );
4983        let mut value = serde_json::to_value(&t).unwrap();
4984        for field in ["resumption", "resumption_history", "operator_decided_at"] {
4985            value.as_object_mut().unwrap().remove(field);
4986        }
4987        value["schema"] = serde_json::json!(15);
4988        let mut legacy: Task = serde_json::from_value(value).unwrap();
4989        legacy.hold_machine(Some("automatic retry".into()));
4990        legacy.release();
4991        assert!(legacy.resumption.is_none());
4992        assert!(legacy.resumption_history.is_empty());
4993        assert!(legacy.operator_decided_at.is_none());
4994        legacy.release_operator("cli", None);
4995        legacy.start("run".into());
4996        let reloaded: Task =
4997            serde_json::from_str(&serde_json::to_string(&legacy).unwrap()).unwrap();
4998        assert!(reloaded.resume_override.is_none());
4999        assert_eq!(reloaded.resumption.as_ref().unwrap().generation, 1);
5000    }
5001
5002    #[test]
5003    fn merge_over_lets_the_later_choice_win_and_keeps_the_rest() {
5004        let mut base = RunOverrides {
5005            merge: Some("pr".to_owned()),
5006            candidates: Some(3),
5007            ..RunOverrides::default()
5008        };
5009        base.merge_over(&RunOverrides {
5010            merge: Some("none".to_owned()),
5011            seed: Some(7),
5012            ..RunOverrides::default()
5013        });
5014        assert_eq!(base.merge.as_deref(), Some("none"));
5015        assert_eq!(base.candidates, Some(3));
5016        assert_eq!(base.seed, Some(7));
5017    }
5018
5019    #[test]
5020    fn an_already_landed_task_is_done_with_its_attempt_refunded() {
5021        let mut t = task("relanded");
5022        t.attempts = 1;
5023        t.status = TaskStatus::Running;
5024        t.already_landed("already in main as 0e368de", completion(&t));
5025        assert_eq!(t.status, TaskStatus::Done);
5026        assert_eq!(t.attempts, 0);
5027        assert!(t.hold_reason.is_none());
5028        assert_eq!(t.last_error.as_deref(), Some("already in main as 0e368de"));
5029    }
5030
5031    #[test]
5032    fn missing_blocker_reason_follows_the_language() {
5033        let b = vec!["a".to_owned()];
5034        let en = missing_blocker_hold_reason_in(&b, &b, "en");
5035        assert_eq!(en, missing_blocker_hold_reason(&b, &b));
5036        assert!(en.starts_with("blocked on a"));
5037        assert!(missing_blocker_hold_reason_in(&b, &b, "ja").contains("存在しません"));
5038        assert_eq!(missing_blocker_hold_reason_in(&b, &b, "de"), en);
5039    }
5040
5041    use super::*;
5042
5043    fn completion(task: &Task) -> CompletionContext {
5044        CompletionContext::new(CompletionActor::Cli, None, Path::new("."), task)
5045    }
5046
5047    #[test]
5048    fn completion_retains_the_hold_dependency_and_failure_it_clears() {
5049        let mut held = task("held evidence");
5050        held.hold_manual(Some("owner approval required".into()));
5051        held.last_error = Some("review budget exhausted".into());
5052        held.succeed(completion(&held));
5053        let event = held.completion_history.last().unwrap();
5054        assert_eq!(event.prior_status, TaskStatus::Held);
5055        assert_eq!(
5056            event.prior_hold_reason.as_deref(),
5057            Some("owner approval required")
5058        );
5059        assert_eq!(
5060            event.prior_error.as_deref(),
5061            Some("review budget exhausted")
5062        );
5063        assert!(held.hold_reason.is_none());
5064        assert!(held.last_error.is_none());
5065        let mut blocked = task("dependency evidence");
5066        blocked.block(
5067            vec!["dependency".into()],
5068            Some("waiting on migration".into()),
5069        );
5070        blocked.succeed(completion(&blocked));
5071        let event = blocked.completion_history.last().unwrap();
5072        assert_eq!(event.prior_status, TaskStatus::Blocked);
5073        assert_eq!(
5074            event.prior_block_reason.as_deref(),
5075            Some("waiting on migration")
5076        );
5077        assert!(blocked.block_reason.is_none());
5078        assert!(blocked.blocked_by.is_empty());
5079        let saved = serde_json::to_vec(&held).unwrap();
5080        let restored: Task = serde_json::from_slice(&saved).unwrap();
5081        assert_eq!(restored.completion_history, held.completion_history);
5082    }
5083
5084    #[test]
5085    fn completion_audit_is_append_only_under_stale_puts() {
5086        let dir = tempfile::tempdir().unwrap();
5087        let queue = Queue::at(dir.path().join("queue"));
5088        let mut current = task("audited");
5089        current.hold_manual(Some("inspect".into()));
5090        queue.put(&mut current).unwrap();
5091        let mut stale = queue.get(&current.id).unwrap();
5092        current.succeed(completion(&current));
5093        queue.put(&mut current).unwrap();
5094        let original = current.completion_history[0].clone();
5095        stale.last_error = Some("stale control state".into());
5096        queue.put(&mut stale).unwrap();
5097        assert_eq!(stale.status, TaskStatus::Done);
5098        assert_eq!(stale.completion_history, vec![original.clone()]);
5099        let mut context = completion(&current);
5100        context.reason = Some("not actually finished".into());
5101        current.reopen(context).unwrap();
5102        queue.put(&mut current).unwrap();
5103        stale.completion_history[0].actor = CompletionActor::Web;
5104        stale.completion_history[0].reason = Some("rewritten evidence".into());
5105        queue.put(&mut stale).unwrap();
5106        assert_eq!(stale.status, TaskStatus::Held);
5107        assert_eq!(stale.hold_reason.as_deref(), Some("not actually finished"));
5108        assert_eq!(stale.completion_history[0], original);
5109        assert_eq!(stale.completion_history, current.completion_history);
5110    }
5111
5112    #[test]
5113    fn a_writer_missing_a_reopen_contributes_receipts_but_not_authority() {
5114        let (_dir, q) = queue();
5115        let mut current = task("durable receipts");
5116        q.put(&mut current).unwrap();
5117        let mut stale = current.clone();
5118        let grant: crate::repair_budget::Receipt = serde_json::from_value(serde_json::json!({
5119            "request": {
5120                "task": current.id, "run": "old-run", "kind": "gate", "rounds": 1,
5121                "head": "old-head", "expect_pass": 0, "request": "old-grant", "reason": "retry"
5122            },
5123            "at": stale.updated_at, "contract": "old-contract"
5124        }))
5125        .unwrap();
5126        stale.release_operator("triage", Some("triage-question"));
5127        stale.queue_repair(&grant);
5128        let reconciliation: crate::repair_budget::reconcile::Receipt =
5129            serde_json::from_value(serde_json::json!({
5130                "request": {
5131                    "task": current.id, "run": "old-run", "head": "old-head", "expect_pass": 0,
5132                    "receipt": "old-grant", "question": "triage-question", "answer_at": grant.at,
5133                    "request": "reconciliation", "reason": "retain the answer"
5134                },
5135                "grant": grant, "source": "answer", "application": "release",
5136                "decision": grant.at, "superseded_questions": []
5137            }))
5138            .unwrap();
5139        stale.repair_reconciliations.push(reconciliation.clone());
5140        stale.triage_applied.push("triage-question".into());
5141        stale.actions_applied.push("choice".into());
5142        stale.base_recovery_requests.push("base-request".into());
5143        stale.chat_notices.push("delivery".into());
5144        stale.chat_notice = Some(ChatNotice {
5145            key: "other-delivery".into(),
5146            at: grant.at,
5147            outcome: ChatNoticeOutcome::Posted,
5148        });
5149        for ledger in [
5150            &mut stale.decision_effects,
5151            &mut stale.dispatched_resumes,
5152            &mut stale.superseded_resumes,
5153        ] {
5154            ledger.insert("shared".into(), "stale".into());
5155            ledger.insert("only-stale".into(), "receipt".into());
5156        }
5157
5158        let mut latest_grant = grant.clone();
5159        latest_grant.request.request = "new-grant".into();
5160        current.queue_repair(&latest_grant);
5161        for ledger in [
5162            &mut current.decision_effects,
5163            &mut current.dispatched_resumes,
5164            &mut current.superseded_resumes,
5165        ] {
5166            ledger.insert("shared".into(), "committed".into());
5167        }
5168        current.succeed(completion(&current));
5169        let mut context = completion(&current);
5170        context.reason = Some("inspect again".into());
5171        current.reopen(context).unwrap();
5172        q.put(&mut current).unwrap();
5173
5174        for _ in 0..2 {
5175            q.put(&mut stale.clone()).unwrap();
5176            let saved = q.get(&current.id).unwrap();
5177            assert_eq!(saved.status, TaskStatus::Held);
5178            assert_eq!(saved.hold_reason, current.hold_reason);
5179            assert_eq!(saved.operator_decided_at, current.operator_decided_at);
5180            assert_eq!(saved.completion_history, current.completion_history);
5181            assert!(saved.resume_override.is_none());
5182            assert!(saved.resumption.is_none());
5183            assert_eq!(
5184                saved.resumption_history,
5185                [stale.resumption.clone().unwrap()]
5186            );
5187            assert_eq!(saved.triage_applied, ["triage-question"]);
5188            assert_eq!(saved.actions_applied, ["choice"]);
5189            assert_eq!(saved.base_recovery_requests, ["base-request"]);
5190            assert_eq!(saved.chat_notices, ["delivery", "other-delivery"]);
5191            assert_eq!(saved.repair_grants, [grant.clone(), latest_grant.clone()]);
5192            assert_eq!(
5193                saved.repair_reconciliations,
5194                std::slice::from_ref(&reconciliation)
5195            );
5196            for ledger in [
5197                saved.decision_effects,
5198                saved.dispatched_resumes,
5199                saved.superseded_resumes,
5200            ] {
5201                assert_eq!(ledger["shared"], "committed");
5202                assert_eq!(ledger["only-stale"], "receipt");
5203            }
5204        }
5205    }
5206
5207    #[test]
5208    fn repeated_completion_only_notifies_for_new_occurrences() {
5209        let mut task = chat_task();
5210        task.succeed(completion(&task));
5211        let first = task.chat_notice_key().unwrap();
5212        task.chat_notices.push(first.clone());
5213        task.succeed(completion(&task));
5214        assert_eq!(task.completion_history.len(), 1, "idempotent while done");
5215        assert_eq!(task.chat_notice_due(), None);
5216        let mut context = completion(&task);
5217        context.reason = Some("inspect".into());
5218        task.reopen(context).unwrap();
5219        task.succeed(completion(&task));
5220        let second = task.chat_notice_key().unwrap();
5221        assert_ne!(first, second);
5222        assert_eq!(task.chat_notice_due(), Some(second));
5223        assert_eq!(task.completion_history.len(), 3);
5224    }
5225
5226    #[test]
5227    fn old_tasks_have_unknown_completion_provenance_not_invented_events() {
5228        let mut task = task("legacy");
5229        task.status = TaskStatus::Done;
5230        let mut value = serde_json::to_value(&task).unwrap();
5231        value.as_object_mut().unwrap().remove("completion_history");
5232        let task: Task = serde_json::from_value(value).unwrap();
5233        assert!(task.completion_history.is_empty());
5234        assert_eq!(task.chat_notice_key().as_deref(), Some("done"));
5235    }
5236
5237    #[test]
5238    fn triage_applied_survives_release_and_old_records_read_as_empty() {
5239        let mut t = Task::new(
5240            "t".to_owned(),
5241            "i".to_owned(),
5242            PathBuf::from("r"),
5243            Source::Human,
5244        );
5245        t.mark_triage_applied("q1");
5246        t.mark_triage_applied("q1");
5247        t.hold_machine(Some("x".to_owned()));
5248        t.release();
5249        assert_eq!(t.triage_applied, ["q1"]);
5250        assert!(t.triage_applied("q1") && !t.triage_applied("q2"));
5251
5252        let mut v = serde_json::to_value(&t).unwrap();
5253        v.as_object_mut().unwrap().remove("triage_applied");
5254        let old: Task = serde_json::from_value(v).unwrap();
5255        assert!(old.triage_applied.is_empty());
5256    }
5257
5258    #[test]
5259    fn task_counts_of_empty_is_all_zero() {
5260        assert_eq!(TaskCounts::of(&[]), TaskCounts::default());
5261    }
5262
5263    #[test]
5264    fn task_counts_of_tallies_every_status() {
5265        let mut queued = Task::new(
5266            "q".to_owned(),
5267            "i".to_owned(),
5268            PathBuf::from("."),
5269            Source::Human,
5270        );
5271        queued.status = TaskStatus::Queued;
5272        let mut running = queued.clone();
5273        running.status = TaskStatus::Running;
5274        let mut done = queued.clone();
5275        done.status = TaskStatus::Done;
5276        let mut failed = queued.clone();
5277        failed.status = TaskStatus::Failed;
5278        let mut held = queued.clone();
5279        held.status = TaskStatus::Held;
5280        let mut blocked = queued.clone();
5281        blocked.status = TaskStatus::Blocked;
5282
5283        let mut parked = queued.clone();
5284        parked.status = TaskStatus::Parked;
5285
5286        let counts = TaskCounts::of(&[
5287            queued,
5288            running,
5289            done.clone(),
5290            done,
5291            failed,
5292            held,
5293            blocked,
5294            parked,
5295        ]);
5296        assert_eq!(
5297            counts,
5298            TaskCounts {
5299                queued: 1,
5300                running: 1,
5301                done: 2,
5302                failed: 1,
5303                held: 1,
5304                blocked: 1,
5305                parked: 1,
5306            }
5307        );
5308    }
5309
5310    #[test]
5311    fn task_implementers_persist_normalized_without_losing_history() {
5312        let (_dir, q) = queue();
5313        let mut t = task("keep me");
5314        t.hold_manual(Some("waiting".into()));
5315        t.runs.push("earlier-run".into());
5316        t.attachments.push("reference.txt".into());
5317        let cfg: crate::config::Config =
5318            toml::from_str("[[agents]]\nid = 'mock'\nkind = 'command'\ncommand = ['true']\n")
5319                .unwrap();
5320        q.put(&mut t).unwrap();
5321        let original = serde_json::to_value(&t).unwrap();
5322        for n in [2, 1, 2] {
5323            t.set_implementers(n, &cfg).unwrap();
5324            q.put(&mut t).unwrap();
5325            t = q.get(&t.id).unwrap();
5326            assert_eq!(t.implementers(), Some(usize::from(n)));
5327            assert_eq!(t.solo, n == 1);
5328            if n == 1 {
5329                assert!(t.overrides.is_none());
5330            }
5331            let mut actual = serde_json::to_value(&t).unwrap();
5332            for field in ["solo", "overrides", "updated_at"] {
5333                actual[field] = original[field].clone();
5334            }
5335            assert_eq!(actual, original);
5336        }
5337        t.overrides.as_mut().unwrap().judges = Some(2);
5338        t.set_implementers(1, &cfg).unwrap();
5339        assert_eq!(t.overrides.as_ref().unwrap().judges, Some(2));
5340        assert_eq!(t.overrides.as_ref().unwrap().candidates, None);
5341    }
5342
5343    #[test]
5344    fn task_implementers_old_records_keep_inheritance_until_changed() {
5345        let mut value = serde_json::to_value(task("old task")).unwrap();
5346        value.as_object_mut().unwrap().remove("solo");
5347        value.as_object_mut().unwrap().remove("overrides");
5348        let mut old: Task = serde_json::from_value(value).unwrap();
5349        assert_eq!(old.implementers(), None);
5350        old.set_implementers(1, &crate::config::Config::default())
5351            .unwrap();
5352        assert!(old.solo);
5353        assert!(old.overrides.is_none());
5354    }
5355
5356    #[test]
5357    fn task_implementers_reject_invalid_counts_and_states() {
5358        let cfg = crate::config::Config::default();
5359        let mut t = task("unchanged");
5360        for n in [0, 4, 255] {
5361            assert!(t.set_implementers(n, &cfg).is_err());
5362        }
5363        for status in [
5364            TaskStatus::Running,
5365            TaskStatus::Done,
5366            TaskStatus::Failed,
5367            TaskStatus::Blocked,
5368            TaskStatus::Parked,
5369        ] {
5370            t.status = status;
5371            let before = serde_json::to_value(&t).unwrap();
5372            assert!(t.set_implementers(1, &cfg).is_err());
5373            assert_eq!(serde_json::to_value(&t).unwrap(), before);
5374        }
5375    }
5376
5377    /// A queue of its own, with no process-global state - which is the point of
5378    /// `Queue::at`, and why these can run in parallel.
5379    fn queue() -> (tempfile::TempDir, Queue) {
5380        let dir = tempfile::tempdir().unwrap();
5381        let q = Queue::at(dir.path().join("queue"));
5382        (dir, q)
5383    }
5384
5385    #[test]
5386    fn base_recovery_commit_retains_decision_and_superseded_resume_evidence() {
5387        let (_dir, q) = queue();
5388        let mut original = task("base recovery");
5389        original
5390            .decision_effects
5391            .insert("old-effect".into(), "receipt".into());
5392        original
5393            .dispatched_resumes
5394            .insert("dispatched".into(), "prior-run".into());
5395        original.resume_override = Some(OperatorResume {
5396            question_id: "prior-decision".into(),
5397            at: Timestamp::now(),
5398            conductor_rehold: None,
5399            forced: true,
5400            pinned_run: Some("retained-run".into()),
5401        });
5402        q.put(&mut original).unwrap();
5403        let expected = serde_json::to_value(&original).unwrap();
5404        let mut recovered = original.clone();
5405        recovered.base_recovery_requests.push("chat/request".into());
5406        recovered
5407            .resume_override
5408            .as_mut()
5409            .unwrap()
5410            .question_id
5411            .clear();
5412        q.commit_base_recovery(&mut recovered, &expected).unwrap();
5413        let saved = q.get(&original.id).unwrap();
5414        assert_eq!(saved.decision_effects, original.decision_effects);
5415        assert_eq!(saved.dispatched_resumes, original.dispatched_resumes);
5416        assert_eq!(
5417            saved
5418                .superseded_resumes
5419                .get("prior-decision")
5420                .map(String::as_str),
5421            Some("retained-run")
5422        );
5423        assert_eq!(saved.base_recovery_requests, ["chat/request"]);
5424        assert!(saved.resume_override.unwrap().question_id.is_empty());
5425        assert!(q.commit_base_recovery(&mut recovered, &expected).is_err());
5426    }
5427
5428    #[test]
5429    fn a_stale_write_does_not_drop_the_recorded_task_chat() {
5430        let (_dir, q) = queue();
5431        let mut stale = task("chat");
5432        q.put(&mut stale).unwrap();
5433        let mut fresh = q.get(&stale.id).unwrap();
5434        fresh.chat = Some("talk-1".to_owned());
5435        q.put(&mut fresh).unwrap();
5436        q.put(&mut stale).unwrap();
5437        assert_eq!(q.get(&stale.id).unwrap().chat.as_deref(), Some("talk-1"));
5438    }
5439
5440    #[test]
5441    fn putting_a_machine_held_task_files_a_notification_beside_the_queue() {
5442        let dir = tempfile::tempdir().unwrap();
5443        let q = Queue::at(dir.path().join("queue"));
5444        let mut t = task("held");
5445        q.put(&mut t).unwrap();
5446        assert_eq!(
5447            crate::notices::Notices::at(dir.path().join("notifications"))
5448                .list()
5449                .len(),
5450            0
5451        );
5452        t.hold_machine(Some("out of attempts".to_owned()));
5453        q.put(&mut t).unwrap();
5454        let listed = crate::notices::Notices::at(dir.path().join("notifications")).list();
5455        assert_eq!(listed.len(), 1);
5456        assert!(listed[0].message.contains("out of attempts"));
5457    }
5458
5459    #[test]
5460    fn start_consumes_the_disk_resume_pin() {
5461        let mut t = task("pin");
5462        t.disk_resume_run = Some("run-1".into());
5463        t.start("run-1".into());
5464        assert!(t.disk_resume_run.is_none());
5465    }
5466
5467    fn task(title: &str) -> Task {
5468        Task::new(
5469            title.to_owned(),
5470            format!("do {title}"),
5471            PathBuf::from("."),
5472            Source::Human,
5473        )
5474    }
5475
5476    #[test]
5477    fn issue_provenance_survives_queue_round_trip_without_inventing_chat() {
5478        let dir = tempfile::tempdir().unwrap();
5479        let q = Queue::at(dir.path().to_path_buf());
5480        let issue = IssueRef {
5481            number: 42,
5482            repo: "owner/repo".into(),
5483        };
5484        for source in [
5485            Source::Human,
5486            Source::Agent {
5487                run: "20260101-010101-abcd".into(),
5488                node: CHAT_NODE.into(),
5489            },
5490        ] {
5491            let mut t = task("issue");
5492            t.source = source;
5493            t.issue = Some(issue.clone());
5494            q.put(&mut t).unwrap();
5495            let saved = q.get(&t.id).unwrap();
5496            assert_eq!(saved.issue_ref(), Some(issue.clone()));
5497            assert_eq!(saved.source, t.source);
5498            assert_eq!(saved.filed_by_chat(), t.filed_by_chat());
5499            assert_eq!(saved.chat_talk(), t.filed_by_chat());
5500            if saved.source == Source::Human {
5501                assert_eq!(saved.source_label(), "issue #42");
5502            } else {
5503                assert!(saved.source_label().contains("issue #42"));
5504            }
5505            let mut stale = saved;
5506            stale.issue = None;
5507            q.put(&mut stale).unwrap();
5508            assert_eq!(q.get(&t.id).unwrap().issue_ref(), Some(issue.clone()));
5509        }
5510        let mut old = serde_json::to_value(task("legacy")).unwrap();
5511        old["schema"] = serde_json::json!(26);
5512        old["source"] = serde_json::json!({"kind":"issue","number":42,"repo":"owner/repo"});
5513        let legacy: Task = serde_json::from_value(old).unwrap();
5514        assert_eq!(legacy.issue_ref(), Some(issue));
5515        assert_eq!(legacy.filed_by_chat(), None);
5516        assert_eq!(legacy.chat_talk(), None);
5517        assert_eq!(legacy.source_label(), "issue #42");
5518    }
5519
5520    #[test]
5521    fn attempt_limit_inherits_old_records_and_controls_failure() {
5522        let mut t = task("budget");
5523        let mut old = serde_json::to_value(&t).unwrap();
5524        old.as_object_mut().unwrap().remove("attempt_limit");
5525        old["schema"] = serde_json::json!(15);
5526        let legacy: Task = serde_json::from_value(old).unwrap();
5527        assert_eq!(legacy.attempt_limit, None);
5528        assert_eq!(legacy.effective_attempt_limit(2), 2);
5529        t.attempts = 2;
5530        t.change_attempt_limit(NonZeroUsize::new(3)).unwrap();
5531        t.fail("retry", 1);
5532        assert_eq!(t.status, TaskStatus::Failed);
5533        t.attempts = 3;
5534        t.fail("stop", 10);
5535        assert_eq!(t.status, TaskStatus::Held);
5536        t.change_attempt_limit(None).unwrap();
5537        assert_eq!(t.status, TaskStatus::Held);
5538        assert_eq!(t.attempts, 3);
5539        t.fail("inherit", 4);
5540        assert_eq!(t.status, TaskStatus::Failed);
5541        for status in [
5542            TaskStatus::Running,
5543            TaskStatus::Done,
5544            TaskStatus::Failed,
5545            TaskStatus::Blocked,
5546            TaskStatus::Parked,
5547        ] {
5548            t.status = status;
5549            assert!(t.change_attempt_limit(NonZeroUsize::new(1)).is_err());
5550            assert_eq!(t.attempt_limit, None);
5551        }
5552    }
5553
5554    #[test]
5555    fn earlier_attempts_is_every_recorded_run_and_agrees_with_the_display() {
5556        let mut t = task("retried");
5557        assert!(
5558            t.earlier_attempts().is_empty(),
5559            "a first attempt takes nothing over"
5560        );
5561        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5562        assert_eq!(t.earlier_attempts(), ["aaaa", "bbbb"]);
5563        // What the web note shows and what a takeover acts on are one rule.
5564        assert_eq!(t.successor_of("aaaa"), Some(&"bbbb".to_owned()));
5565        assert_eq!(t.successor_of("bbbb"), None);
5566        assert_eq!(t.successor_of("zzzz"), None);
5567    }
5568
5569    #[test]
5570    fn resumed_runs_are_superseded_only_after_their_last_occurrence() {
5571        let (_dir, q) = queue();
5572        let mut t = task("resumed");
5573        for (runs, successor) in [
5574            (vec!["aaaa", "aaaa"], None),
5575            (vec!["aaaa", "bbbb", "aaaa"], None),
5576            (vec!["aaaa", "aaaa", "bbbb"], Some("bbbb")),
5577            (vec!["aaaa", "bbbb", "aaaa", "cccc"], Some("cccc")),
5578        ] {
5579            t.runs = runs.into_iter().map(str::to_owned).collect();
5580            q.put(&mut t).unwrap();
5581
5582            assert_eq!(t.successor_of("aaaa").map(String::as_str), successor);
5583            assert_eq!(q.superseded_by("aaaa").as_deref(), successor);
5584            assert_eq!(q.superseded().get("aaaa").map(String::as_str), successor);
5585        }
5586    }
5587
5588    #[test]
5589    fn superseded_by_names_the_next_attempt_and_none_for_the_last() {
5590        let (_dir, q) = queue();
5591        let mut t = task("retried");
5592        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5593        q.put(&mut t).unwrap();
5594
5595        assert_eq!(q.superseded_by("aaaa"), Some("bbbb".to_owned()));
5596        assert_eq!(q.superseded_by("bbbb"), Some("cccc".to_owned()));
5597        assert_eq!(
5598            q.superseded_by("cccc"),
5599            None,
5600            "the latest attempt replaces nothing"
5601        );
5602        assert_eq!(
5603            q.superseded_by("never-heard-of-it"),
5604            None,
5605            "a run belonging to no task on this queue is not superseded"
5606        );
5607
5608        let mut by = HashMap::new();
5609        by.insert("aaaa".to_owned(), "bbbb".to_owned());
5610        by.insert("bbbb".to_owned(), "cccc".to_owned());
5611        assert_eq!(
5612            q.superseded(),
5613            by,
5614            "the whole-map and single-run forms must agree"
5615        );
5616    }
5617
5618    #[test]
5619    fn superseded_attempts_is_empty_until_the_task_is_done() {
5620        let mut t = task("retried");
5621        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5622        t.status = TaskStatus::Failed;
5623        assert_eq!(
5624            t.superseded_attempts(true),
5625            &[] as &[String],
5626            "a task still retrying has no attempt yet that a later one made moot"
5627        );
5628
5629        t.status = TaskStatus::Running;
5630        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5631    }
5632
5633    #[test]
5634    fn superseded_attempts_names_every_run_before_the_one_that_succeeded() {
5635        let mut t = task("retried");
5636        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5637        t.status = TaskStatus::Done;
5638        assert_eq!(
5639            t.superseded_attempts(true),
5640            &["aaaa".to_owned(), "bbbb".to_owned()],
5641            "cccc is the attempt whose success made the task done, and stays out"
5642        );
5643    }
5644
5645    #[test]
5646    fn superseded_attempts_is_empty_for_a_done_task_with_only_one_attempt() {
5647        let mut t = task("first try landed");
5648        t.runs = vec!["aaaa".to_owned()];
5649        t.status = TaskStatus::Done;
5650        assert_eq!(t.superseded_attempts(true), &[] as &[String]);
5651    }
5652
5653    #[test]
5654    fn superseded_attempts_is_empty_when_the_last_run_never_actually_succeeded() {
5655        // `succeed` is reachable directly - `magi task done`, its web
5656        // equivalent, and the conductor's `Recovery::Done` - on a task in
5657        // any status, including one whose last recorded attempt is itself
5658        // `Blocked`/`Failed`/anything but `Merged`/`Ready`. `runs.last()`
5659        // alone cannot tell that apart from the loop's own settle path, so
5660        // the caller's own read of that run's status is what decides this.
5661        let mut t = task("closed by hand after a manual merge");
5662        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned()];
5663        t.status = TaskStatus::Done;
5664        assert_eq!(
5665            t.superseded_attempts(false),
5666            &[] as &[String],
5667            "nothing here is provably why the task is done, so nothing is superseded"
5668        );
5669    }
5670
5671    #[test]
5672    fn latest_attempt_names_the_chain_s_current_head_not_just_the_next_one() {
5673        let (_dir, q) = queue();
5674        let mut t = task("retried twice");
5675        t.runs = vec!["aaaa".to_owned(), "bbbb".to_owned(), "cccc".to_owned()];
5676        q.put(&mut t).unwrap();
5677
5678        assert_eq!(
5679            q.latest_attempt("aaaa"),
5680            Some("cccc".to_owned()),
5681            "an old attempt points straight at the chain's current head, not the \
5682             next attempt in the middle of it"
5683        );
5684        assert_eq!(q.latest_attempt("bbbb"), Some("cccc".to_owned()));
5685        assert_eq!(
5686            q.latest_attempt("cccc"),
5687            None,
5688            "the latest attempt is not superseded by anything"
5689        );
5690        assert_eq!(
5691            q.latest_attempt("never-heard-of-it"),
5692            None,
5693            "a run belonging to no task on this queue is not superseded"
5694        );
5695    }
5696
5697    #[test]
5698    fn a_markdown_heading_is_the_title_not_decoration() {
5699        // A task file's heading is the summary its author already wrote, so it
5700        // beats the prose underneath. Getting this backwards was visible in the
5701        // first smoke test: a task titled "# Rework the config loader" listed
5702        // as "It re-reads the file on every lookup".
5703        assert_eq!(
5704            title_from("# Rework the config loader\n\nIt re-reads it.\n", 40),
5705            "Rework the config loader"
5706        );
5707        assert_eq!(title_from("- fix the thing", 40), "fix the thing");
5708        assert_eq!(title_from("> quoted task", 40), "quoted task");
5709        // Nothing usable at all still has to produce something printable.
5710        assert_eq!(title_from("   \n\n", 40), "(empty task)");
5711        assert_eq!(title_from("###\n", 40), "(empty task)");
5712    }
5713
5714    #[test]
5715    fn a_long_title_is_elided_by_characters_not_bytes() {
5716        // Byte truncation would split a multi-byte character and panic.
5717        let long = "課題".repeat(30);
5718        let title = title_from(&long, 10);
5719        assert_eq!(title.chars().count(), 10);
5720        assert!(title.ends_with('…'));
5721    }
5722
5723    #[test]
5724    fn priority_wins_and_ties_break_oldest_first() {
5725        let (_dir, q) = queue();
5726        let mut a = task("first");
5727        let mut b = task("second");
5728        let mut c = task("urgent");
5729        // Ids carry a timestamp, so force a known order.
5730        a.id = "20260101-000001-aaaa".to_owned();
5731        b.id = "20260101-000002-bbbb".to_owned();
5732        c.id = "20260101-000003-cccc".to_owned();
5733        c.priority = 5;
5734        for t in [&mut a, &mut b, &mut c] {
5735            q.put(t).unwrap();
5736        }
5737
5738        // Priority first...
5739        assert_eq!(q.next_runnable().unwrap().id, c.id);
5740        c.hold_machine(None);
5741        q.put(&mut c).unwrap();
5742        // ...then oldest, so a burst of new work cannot starve older work.
5743        assert_eq!(q.next_runnable().unwrap().id, a.id);
5744        assert_eq!(q.list().len(), 3, "b is still waiting its turn");
5745    }
5746
5747    #[test]
5748    fn a_blocked_task_never_starves_another_runnable_one() {
5749        let (_dir, q) = queue();
5750        let mut blocked = task("blocked");
5751        blocked.block(vec!["something".to_owned()], None);
5752        q.put(&mut blocked).unwrap();
5753
5754        let mut runnable = task("free to go");
5755        q.put(&mut runnable).unwrap();
5756
5757        let next = q.next_runnable().expect("a runnable task is still offered");
5758        assert_eq!(next.id, runnable.id);
5759    }
5760
5761    #[test]
5762    fn a_held_task_is_never_offered_to_the_loop() {
5763        let (_dir, q) = queue();
5764        let mut t = task("held");
5765        q.put(&mut t).unwrap();
5766        assert!(q.next_runnable().is_some());
5767
5768        t.hold_machine(None);
5769        q.put(&mut t).unwrap();
5770        assert!(
5771            q.next_runnable().is_none(),
5772            "a held task must wait for a human"
5773        );
5774
5775        // A failed task, by contrast, is exactly what the loop should retry.
5776        t.status = TaskStatus::Failed;
5777        q.put(&mut t).unwrap();
5778        assert!(q.next_runnable().is_some());
5779    }
5780
5781    #[test]
5782    fn attempts_are_capped_and_then_the_task_is_held() {
5783        let mut t = task("doomed");
5784
5785        t.start("run-1".to_owned());
5786        t.fail("gate red", 2);
5787        assert_eq!(t.status, TaskStatus::Failed, "one attempt of two: retry");
5788
5789        t.start("run-2".to_owned());
5790        t.fail("gate red", 2);
5791        assert_eq!(
5792            t.status,
5793            TaskStatus::Held,
5794            "out of attempts: stop spending money on it"
5795        );
5796        assert_eq!(t.runs, ["run-1", "run-2"]);
5797        assert_eq!(t.last_error.as_deref(), Some("gate red"));
5798        assert_eq!(
5799            t.hold_reason.as_deref(),
5800            Some("gate red"),
5801            "the hold must say why, not leave hold_reason null next to a \
5802             populated last_error"
5803        );
5804    }
5805
5806    #[test]
5807    fn handing_off_a_task_records_a_hold_reason_too() {
5808        let mut t = task("left a pull request");
5809        t.start("run-1".to_owned());
5810        t.handed_off("run ended with a pull request open [run run-1]");
5811        assert_eq!(t.status, TaskStatus::Held);
5812        assert_eq!(t.hold_source, Some(HoldSource::Machine));
5813        assert_eq!(
5814            t.hold_reason.as_deref(),
5815            Some("run ended with a pull request open [run run-1]")
5816        );
5817        assert_eq!(t.hold_reason, t.last_error);
5818    }
5819
5820    #[test]
5821    fn a_quota_stall_is_refunded_so_the_backlog_survives_the_night() {
5822        let mut t = task("stalled by quota");
5823
5824        t.start("run-1".to_owned());
5825        assert_eq!(t.attempts, 1);
5826        t.stall("judge-1, judge-2 out of quota");
5827        assert_eq!(
5828            t.attempts, 0,
5829            "a closed quota window must not spend the task's retry budget"
5830        );
5831        assert_eq!(t.status, TaskStatus::Failed, "the loop should retry it");
5832        assert_eq!(
5833            t.last_error.as_deref(),
5834            Some("judge-1, judge-2 out of quota")
5835        );
5836
5837        // A task can therefore stall all night and still get its real attempts
5838        // once the quota resets - which is the whole point.
5839        for _ in 0..20 {
5840            t.start("run-n".to_owned());
5841            t.stall("still out of quota");
5842        }
5843        t.start("run-real".to_owned());
5844        t.fail("gate red", 2);
5845        assert_eq!(
5846            t.status,
5847            TaskStatus::Failed,
5848            "the first attempt that was really judged is attempt one"
5849        );
5850    }
5851
5852    #[test]
5853    fn releasing_a_held_task_gives_it_a_real_second_chance() {
5854        let mut t = task("retry me");
5855        t.start("run-1".to_owned());
5856        t.fail("gate red", 1);
5857        assert_eq!(t.status, TaskStatus::Held);
5858
5859        t.release();
5860        assert_eq!(t.status, TaskStatus::Queued);
5861        // Without resetting attempts the next failure would re-hold at once,
5862        // and a release would be a no-op the operator cannot see.
5863        assert_eq!(t.attempts, 0);
5864        assert!(t.last_error.is_none());
5865        assert_eq!(
5866            t.runs.len(),
5867            1,
5868            "history is kept: attempts reset, evidence does not"
5869        );
5870    }
5871
5872    #[test]
5873    fn a_hold_reason_survives_and_a_release_clears_it() {
5874        let mut t = task("waiting on something else");
5875        t.hold_manual(Some(
5876            "waiting for 20260101-000000-aaaa to land first".to_owned(),
5877        ));
5878        assert_eq!(t.status, TaskStatus::Held);
5879        assert_eq!(
5880            t.hold_reason.as_deref(),
5881            Some("waiting for 20260101-000000-aaaa to land first")
5882        );
5883
5884        // Holding again with no reason must not erase the one already there.
5885        t.hold_manual(None);
5886        assert_eq!(
5887            t.hold_reason.as_deref(),
5888            Some("waiting for 20260101-000000-aaaa to land first"),
5889            "a bare re-hold keeps whatever a human already wrote down"
5890        );
5891
5892        // A hold with no reason at all is still an ordinary, allowed hold.
5893        let mut plain = task("no reason given");
5894        plain.hold_manual(None);
5895        assert_eq!(plain.status, TaskStatus::Held);
5896        assert!(plain.hold_reason.is_none());
5897
5898        t.release();
5899        assert_eq!(t.status, TaskStatus::Queued);
5900        assert!(
5901            t.hold_reason.is_none(),
5902            "a stale reason must not greet the next person who holds this task"
5903        );
5904    }
5905
5906    #[test]
5907    fn closing_a_held_task_as_done_clears_its_hold_reason_too() {
5908        // `done` can close a held task directly - neither `magi task done`
5909        // nor `POST /api/queue/{id}/done` requires a release first - so a
5910        // task held for "waiting on 3ed9" and then closed without ever being
5911        // released must not still read as waiting on it afterwards.
5912        let mut t = task("landed by hand while held");
5913        t.hold_manual(Some("waiting on 3ed9".to_owned()));
5914        assert_eq!(t.hold_reason.as_deref(), Some("waiting on 3ed9"));
5915
5916        t.succeed(completion(&t));
5917        assert_eq!(t.status, TaskStatus::Done);
5918        assert!(
5919            t.hold_reason.is_none(),
5920            "a done task cannot still be waiting on something"
5921        );
5922    }
5923
5924    #[test]
5925    fn holding_or_closing_a_blocked_task_clears_its_dependency_too() {
5926        // The web UI's "Hold" and "Mark done" buttons are both reachable on a
5927        // `blocked` task, not just on `queued`/`held` ones - neither requires
5928        // a release first. A task moved off `Blocked` that way must not still
5929        // carry the dependency it was waiting on: a dependency graph built
5930        // from `blocked_by` would otherwise keep drawing an edge for a task
5931        // that is not blocked on anything any more.
5932        let mut held = task("held straight out of blocked");
5933        held.block(
5934            vec!["20260101-000000-dead".to_owned()],
5935            Some("waiting on the migration script".to_owned()),
5936        );
5937        assert_eq!(held.status, TaskStatus::Blocked);
5938
5939        held.hold_manual(None);
5940        assert_eq!(held.status, TaskStatus::Held);
5941        assert!(
5942            held.blocked_by.is_empty(),
5943            "hold overrides the wait, same as release"
5944        );
5945        assert!(held.block_reason.is_none());
5946
5947        let mut done = task("closed straight out of blocked");
5948        done.block(
5949            vec!["20260101-000000-dead".to_owned()],
5950            Some("waiting on the migration script".to_owned()),
5951        );
5952        done.succeed(completion(&done));
5953        assert_eq!(done.status, TaskStatus::Done);
5954        assert!(
5955            done.blocked_by.is_empty(),
5956            "a done task cannot still be waiting on a dependency"
5957        );
5958        assert!(done.block_reason.is_none());
5959    }
5960
5961    #[test]
5962    fn a_blocked_task_is_never_offered_to_the_loop() {
5963        let mut t = task("blocked");
5964        assert!(t.status.runnable());
5965        t.block(
5966            vec!["dep-id".to_owned()],
5967            Some("waits on dep-id".to_owned()),
5968        );
5969        assert_eq!(t.status, TaskStatus::Blocked);
5970        assert!(!t.status.runnable());
5971        assert_eq!(TaskStatus::Blocked.as_str(), "blocked");
5972    }
5973
5974    #[test]
5975    fn unblocking_the_last_dependency_returns_the_task_to_queued() {
5976        let mut t = task("blocked on two");
5977        t.block(
5978            vec!["a".to_owned(), "b".to_owned()],
5979            Some("waits on a and b".to_owned()),
5980        );
5981
5982        t.unblock("a");
5983        assert_eq!(t.status, TaskStatus::Blocked, "b is still outstanding");
5984        assert_eq!(t.blocked_by, ["b"]);
5985
5986        t.unblock("b");
5987        assert_eq!(t.status, TaskStatus::Queued);
5988        assert!(t.blocked_by.is_empty());
5989        assert!(t.block_reason.is_none());
5990    }
5991
5992    #[test]
5993    fn unblocking_an_id_on_a_task_that_is_not_blocked_is_a_no_op() {
5994        let mut t = task("never blocked");
5995        t.unblock("whatever");
5996        assert_eq!(t.status, TaskStatus::Queued);
5997    }
5998
5999    #[test]
6000    fn a_held_task_blocked_on_a_question_returns_to_held_not_queued() {
6001        // The bug this guards: a task an operator (or `crate::triage`) has
6002        // deliberately held, once `crate::conduct` blocks it on a follow-up
6003        // question, must not silently re-enter the competition queue the
6004        // moment that question is answered - whatever the answer said.
6005        let mut t = task("held, then asked about");
6006        t.hold_machine(Some("out of attempts".to_owned()));
6007        assert_eq!(t.status, TaskStatus::Held);
6008
6009        t.block(vec!["q1".to_owned()], Some("what now?".to_owned()));
6010        assert_eq!(t.status, TaskStatus::Blocked);
6011
6012        t.record_answer("what now?".to_owned(), "leave it held".to_owned());
6013        t.unblock("q1");
6014        assert_eq!(t.status, TaskStatus::Held, "must restore, not requeue");
6015        assert_eq!(t.hold_reason.as_deref(), Some("out of attempts"));
6016        assert_eq!(t.hold_source, Some(HoldSource::Machine));
6017        assert!(t.blocked_from.is_none(), "consumed once restored");
6018    }
6019
6020    #[test]
6021    fn a_manually_held_task_blocked_on_a_question_returns_to_held() {
6022        let mut t = task("manually held, then asked about");
6023        t.hold_manual(Some("waiting on a dependency".to_owned()));
6024
6025        t.block(vec!["q1".to_owned()], None);
6026        t.unblock("q1");
6027
6028        assert_eq!(t.status, TaskStatus::Held);
6029        assert_eq!(t.hold_source, Some(HoldSource::Manual));
6030    }
6031
6032    #[test]
6033    fn re_blocking_an_already_blocked_task_keeps_the_original_blocked_from() {
6034        // A second `Task::block` call - `crate::conduct` adding a question on
6035        // top of an existing block - must not overwrite `blocked_from` with
6036        // `Blocked` itself, or the task would restore into itself.
6037        let mut t = task("held, blocked twice");
6038        t.hold_machine(None);
6039        t.block(vec!["q1".to_owned()], Some("first".to_owned()));
6040        t.block(
6041            vec!["q1".to_owned(), "q2".to_owned()],
6042            Some("second".to_owned()),
6043        );
6044
6045        t.unblock("q1");
6046        assert_eq!(t.status, TaskStatus::Blocked, "q2 still outstanding");
6047        t.unblock("q2");
6048        assert_eq!(t.status, TaskStatus::Held);
6049    }
6050
6051    #[test]
6052    fn unblocking_a_task_blocked_while_running_lands_on_queued_not_running() {
6053        // Whatever process was driving the run is gone by the time a
6054        // conductor's question about it gets answered - there is nothing left
6055        // to resume into.
6056        let mut t = task("blocked mid-run");
6057        t.start("run-1".to_owned());
6058        assert_eq!(t.status, TaskStatus::Running);
6059
6060        t.block(vec!["q1".to_owned()], None);
6061        t.unblock("q1");
6062        assert_eq!(t.status, TaskStatus::Queued);
6063    }
6064
6065    #[test]
6066    fn a_pre_schema_4_blocked_record_with_hold_evidence_restores_to_held() {
6067        // `blocked_from` is `None` for a record written before schema 4 (or,
6068        // equivalently, deserialized straight from an on-disk file that never
6069        // had the field). Held evidence surviving on the task - never cleared
6070        // by `block` - is the only way left to tell such a record apart from
6071        // one blocked straight out of `Queued`.
6072        let mut t = task("legacy record, held before it was blocked");
6073        t.hold_source = Some(HoldSource::Machine);
6074        t.hold_reason = Some("legacy hold reason".to_owned());
6075        t.status = TaskStatus::Blocked;
6076        t.blocked_by = vec!["q1".to_owned()];
6077        t.blocked_from = None;
6078
6079        t.unblock("q1");
6080        assert_eq!(t.status, TaskStatus::Held);
6081    }
6082
6083    #[test]
6084    fn a_pre_schema_4_blocked_record_with_no_hold_evidence_restores_to_queued() {
6085        let mut t = task("legacy record, ordinary dependency block");
6086        t.status = TaskStatus::Blocked;
6087        t.blocked_by = vec!["dep".to_owned()];
6088        t.blocked_from = None;
6089
6090        t.unblock("dep");
6091        assert_eq!(t.status, TaskStatus::Queued);
6092    }
6093
6094    #[test]
6095    fn answering_a_question_is_recorded_and_survives_a_release() {
6096        let mut t = task("asked something");
6097        t.block(vec!["q1".to_owned()], Some("which backend?".to_owned()));
6098        t.record_answer("Which backend?".to_owned(), "SQLite".to_owned());
6099        t.unblock("q1");
6100        assert_eq!(t.status, TaskStatus::Queued);
6101        assert_eq!(t.answers.len(), 1);
6102        assert_eq!(t.answers[0].answer, "SQLite");
6103
6104        // A release resets attempts, not evidence - the same rule
6105        // `releasing_a_held_task_gives_it_a_real_second_chance` asserts for
6106        // `runs`.
6107        t.release();
6108        assert_eq!(t.answers.len(), 1, "the answer is not lost on release");
6109    }
6110
6111    #[test]
6112    fn resumption_review_branch_requires_unchanged_authored_criteria() {
6113        for source in ["cli", "web"] {
6114            let mut t = task("review old candidate");
6115            t.request_review("candidate-A".into());
6116            t.hold_for_handover(Some("candidate-A".into()), "handover refused".into());
6117            let mut unchanged = t.clone();
6118            unchanged.release_operator(source, None);
6119            assert_eq!(unchanged.review_branch.as_deref(), Some("candidate-A"));
6120            t.edit(
6121                "review approved head".into(),
6122                "Reuse measured PR head B; fix Clippy; review".into(),
6123            )
6124            .unwrap();
6125            t.release_operator(source, None);
6126            assert!(t.review_branch.is_none());
6127            assert!(t.review_instruction.is_none());
6128            // Legacy records capture their old criteria at the supported edit.
6129            let mut legacy = unchanged;
6130            legacy.review_instruction = None;
6131            legacy.hold_for_handover(None, "still checked out".into());
6132            legacy
6133                .edit("new plan".into(), "Reuse measured PR head B".into())
6134                .unwrap();
6135            legacy.release_operator(source, None);
6136            assert!(legacy.review_branch.is_none());
6137        }
6138    }
6139
6140    #[test]
6141    fn a_refused_handover_keeps_the_review_branch_across_release() {
6142        let mut t = task("refused takeover");
6143        t.start("run-1".to_owned());
6144        t.hold_for_handover(Some("magi/eba2/A".to_owned()), "checked out".to_owned());
6145        assert_eq!(t.status, TaskStatus::Held);
6146        assert_eq!(t.attempts, 1);
6147        t.release();
6148        assert_eq!(t.status, TaskStatus::Queued);
6149        assert_eq!(t.attempts, 0);
6150        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6151
6152        // A fresh competition chosen afterwards is not a review.
6153        t.hold_for_handover(None, "again".to_owned());
6154        t.requeue();
6155        assert!(t.review_branch.is_none());
6156
6157        // A manual hold never keeps one.
6158        let mut m = task("manual");
6159        m.review_branch = Some("magi/x/A".to_owned());
6160        m.hold_manual(None);
6161        m.release();
6162        assert!(m.review_branch.is_none());
6163    }
6164
6165    #[test]
6166    fn requesting_review_requeues_the_task_and_remembers_the_branch() {
6167        let mut t = task("blocked run with a surviving branch");
6168        t.start("run-1".to_owned());
6169        t.fail("blocked with major findings", 5);
6170        assert_eq!(t.status, TaskStatus::Failed);
6171
6172        t.request_review("magi/eba2/A".to_owned());
6173        assert_eq!(t.status, TaskStatus::Queued);
6174        assert_eq!(t.attempts, 0);
6175        assert_eq!(t.review_branch.as_deref(), Some("magi/eba2/A"));
6176
6177        // An ordinary release (a human overriding the choice) drops it again.
6178        t.release();
6179        assert!(t.review_branch.is_none());
6180    }
6181
6182    #[test]
6183    fn conductor_requeue_but_not_an_ordinary_release_forces_a_fresh_start() {
6184        let mut t = task("retry");
6185        t.start("run-1".to_owned());
6186        t.requeue();
6187        assert!(t.fresh_start);
6188
6189        t.release();
6190        assert!(!t.fresh_start);
6191    }
6192
6193    #[test]
6194    fn urgent_only_changes_queued_or_held_and_preserves_settings() {
6195        for status in [
6196            TaskStatus::Queued,
6197            TaskStatus::Held,
6198            TaskStatus::Running,
6199            TaskStatus::Done,
6200            TaskStatus::Failed,
6201            TaskStatus::Blocked,
6202            TaskStatus::Parked,
6203        ] {
6204            let mut t = task("urgent settings");
6205            t.status = status;
6206            t.attempts = 2;
6207            t.hold_reason = Some("waiting".into());
6208            t.priority = 7;
6209            t.interrupt = true;
6210            let before = serde_json::to_value(&t).unwrap();
6211            for urgent in [true, true, false, false] {
6212                let result = t.set_urgent(urgent);
6213                let mut expected = before.clone();
6214                if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6215                    result.unwrap();
6216                    expected["urgent"] = urgent.into();
6217                } else {
6218                    let error = result.unwrap_err().to_string();
6219                    assert!(error.contains(status.as_str()), "{error}");
6220                    assert!(error.contains("queued or held"), "{error}");
6221                }
6222                assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6223            }
6224        }
6225    }
6226
6227    #[test]
6228    fn immediate_only_changes_queued_or_held_and_preserves_settings() {
6229        for status in [
6230            TaskStatus::Queued,
6231            TaskStatus::Held,
6232            TaskStatus::Running,
6233            TaskStatus::Done,
6234            TaskStatus::Failed,
6235            TaskStatus::Blocked,
6236            TaskStatus::Parked,
6237        ] {
6238            let mut t = task("immediate settings");
6239            t.status = status;
6240            t.attempts = 2;
6241            t.hold_reason = Some("waiting".into());
6242            t.priority = 7;
6243            t.interrupt = true;
6244            t.urgent = true;
6245            let before = serde_json::to_value(&t).unwrap();
6246            for immediate in [true, true, false, false] {
6247                let result = t.set_immediate(immediate);
6248                let mut expected = before.clone();
6249                if matches!(status, TaskStatus::Queued | TaskStatus::Held) {
6250                    result.unwrap();
6251                    expected["immediate"] = immediate.into();
6252                } else {
6253                    let error = result.unwrap_err().to_string();
6254                    assert!(error.contains(status.as_str()), "{error}");
6255                    assert!(error.contains("queued or held"), "{error}");
6256                }
6257                assert_eq!(serde_json::to_value(&t).unwrap(), expected);
6258                assert!(t.urgent, "changing immediate must preserve saved urgent");
6259            }
6260        }
6261    }
6262
6263    #[test]
6264    fn a_task_recorded_without_an_immediate_field_still_reads_as_not_immediate() {
6265        let (_dir, q) = queue();
6266        let path = q.path_of("20260101-000000-imm0");
6267        std::fs::create_dir_all(q.root()).unwrap();
6268        std::fs::write(
6269            &path,
6270            serde_json::json!({
6271                "schema": SCHEMA,
6272                "id": "20260101-000000-imm0",
6273                "title": "from before immediate existed",
6274                "instruction": "from before immediate existed",
6275                "repo": ".",
6276                "source": { "kind": "human" },
6277                "status": "queued",
6278                "urgent": true,
6279                "created_at": Timestamp::now().to_string(),
6280                "updated_at": Timestamp::now().to_string(),
6281            })
6282            .to_string(),
6283        )
6284        .unwrap();
6285
6286        let task = q.get("20260101-000000-imm0").expect("must still read");
6287        assert!(!task.immediate);
6288        assert!(task.urgent);
6289    }
6290
6291    #[test]
6292    fn immediate_reuses_urgent_isolation_and_explicit_cache_wins() {
6293        let mut cfg = crate::config::Config::default();
6294        cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test".into()];
6295        let mut t = task("immediate cache");
6296
6297        t.set_immediate(true).unwrap();
6298        assert_eq!(
6299            t.build_cache_override(&cfg),
6300            Some((BuildCache::Isolated, "immediate"))
6301        );
6302
6303        // Coexisting with urgent still attributes isolation to immediate.
6304        t.set_urgent(true).unwrap();
6305        assert_eq!(
6306            t.build_cache_override(&cfg),
6307            Some((BuildCache::Isolated, "immediate"))
6308        );
6309
6310        // Explicit task cache override always wins over immediate.
6311        t.change_build_cache(Some(BuildCache::Shared)).unwrap();
6312        assert_eq!(
6313            t.build_cache_override(&cfg),
6314            Some((BuildCache::Shared, "task-override"))
6315        );
6316
6317        // Clearing explicit override restores immediate; clearing immediate reverts to urgent.
6318        t.change_build_cache(None).unwrap();
6319        assert_eq!(
6320            t.build_cache_override(&cfg),
6321            Some((BuildCache::Isolated, "immediate"))
6322        );
6323        t.set_immediate(false).unwrap();
6324        assert_eq!(
6325            t.build_cache_override(&cfg),
6326            Some((BuildCache::Isolated, "urgent"))
6327        );
6328
6329        // Unsupported isolation falls back cleanly even for immediate tasks.
6330        t.set_immediate(true).unwrap();
6331        cfg.verify.e2e = vec!["CARGO_TARGET_DIR=/tmp/shared-target cargo test | tee log".into()];
6332        assert_eq!(t.build_cache_override(&cfg), None);
6333    }
6334
6335    #[test]
6336    fn priority_can_be_changed_while_queued_but_not_while_running() {
6337        let mut t = task("reprioritise me");
6338        t.set_priority(5).unwrap();
6339        assert_eq!(t.priority, 5);
6340
6341        t.start("run-1".to_owned());
6342        let err = t.set_priority(9).unwrap_err().to_string();
6343        assert!(err.contains("running"), "{err}");
6344        assert_eq!(t.priority, 5, "the rejected write must not partially apply");
6345    }
6346
6347    #[test]
6348    fn interrupt_can_be_marked_while_queued_but_not_while_running() {
6349        let mut t = task("interrupt me");
6350        assert!(!t.interrupt, "off unless asked, same as any other task");
6351
6352        t.set_interrupt(true).unwrap();
6353        assert!(t.interrupt);
6354
6355        t.start("run-1".to_owned());
6356        assert!(
6357            !t.interrupt,
6358            "the mark is one-shot: dispatching the task fulfils it, \
6359             whatever the run that follows ends up doing"
6360        );
6361        let err = t.set_interrupt(true).unwrap_err().to_string();
6362        assert!(err.contains("running"), "{err}");
6363        // Clearing is always allowed, even on a running task - there is
6364        // nothing left for it to interrupt once it has been claimed.
6365        t.set_interrupt(false).unwrap();
6366        assert!(!t.interrupt);
6367    }
6368
6369    /// R2-1-1: a task whose run fails and requeues must not go on
6370    /// re-triggering `crate::daemon`'s interrupt scheduler on every later
6371    /// boundary, attempt after attempt, until it exhausts its budget.
6372    #[test]
6373    fn a_failed_run_does_not_leave_the_task_still_marked_to_interrupt() {
6374        let mut t = task("interrupt me");
6375        t.set_interrupt(true).unwrap();
6376        t.start("run-1".to_owned());
6377        t.fail("mock failure", 5);
6378        assert_eq!(t.status, TaskStatus::Failed);
6379        assert!(
6380            !t.interrupt,
6381            "one attempt already spent the mark; a retry is an ordinary \
6382             requeue, not a fresh interrupt request"
6383        );
6384    }
6385
6386    #[test]
6387    fn changing_priority_moves_a_task_ahead_in_the_real_queue_order() {
6388        let (_dir, q) = queue();
6389        let mut a = task("first filed");
6390        let mut b = task("second filed");
6391        a.id = "20260101-000001-aaaa".to_owned();
6392        b.id = "20260101-000002-bbbb".to_owned();
6393        q.put(&mut a).unwrap();
6394        q.put(&mut b).unwrap();
6395
6396        assert_eq!(
6397            q.next_runnable().unwrap().id,
6398            a.id,
6399            "with equal priority the older task goes first, so a burst of \
6400             new work cannot starve it"
6401        );
6402        assert_eq!(
6403            q.list()[0].id,
6404            b.id,
6405            "but the list an operator reads is newest first, the same as \
6406             before priority existed - a's turn to run does not make it the \
6407             newest task"
6408        );
6409
6410        let mut a = q.get(&a.id).unwrap();
6411        a.set_priority(10).unwrap();
6412        q.put(&mut a).unwrap();
6413
6414        assert_eq!(
6415            q.next_runnable().unwrap().id,
6416            a.id,
6417            "a raised priority must be reflected the moment it is saved"
6418        );
6419        // `magi task list` and `GET /api/queue` both print `Queue::list()`
6420        // directly, so the raised task has to lead there too - not only in
6421        // what the loop would claim next.
6422        assert_eq!(
6423            q.list()[0].id,
6424            a.id,
6425            "the raised task must sort first in the list an operator reads, \
6426             not only in next_runnable's own ordering"
6427        );
6428    }
6429
6430    #[test]
6431    fn editing_replaces_title_and_instruction_but_keeps_identity_and_history() {
6432        let mut t = Task::new(
6433            "old title".to_owned(),
6434            "old instruction".to_owned(),
6435            PathBuf::from("/repo"),
6436            Source::Agent {
6437                run: "20260101-000000-beef".to_owned(),
6438                node: "implement".to_owned(),
6439            },
6440        );
6441        let id = t.id.clone();
6442        let created_at = t.created_at;
6443        t.runs.push("20260101-000000-beef".to_owned());
6444
6445        t.edit("new title".to_owned(), "new instruction".to_owned())
6446            .unwrap();
6447
6448        assert_eq!(t.title, "new title");
6449        assert_eq!(t.instruction, "new instruction");
6450        assert_eq!(t.id, id, "editing must not mint a new id");
6451        assert_eq!(t.created_at, created_at);
6452        assert_eq!(
6453            t.source,
6454            Source::Agent {
6455                run: "20260101-000000-beef".to_owned(),
6456                node: "implement".to_owned(),
6457            },
6458            "editing must not turn agent attribution into human"
6459        );
6460        assert_eq!(t.runs, ["20260101-000000-beef"]);
6461    }
6462
6463    #[test]
6464    fn editing_is_refused_once_a_task_is_running_or_finished() {
6465        let mut running = task("in flight");
6466        running.start("run-1".to_owned());
6467        let err = running
6468            .edit("x".to_owned(), "y".to_owned())
6469            .unwrap_err()
6470            .to_string();
6471        assert!(err.contains("running"), "{err}");
6472
6473        let mut done = task("finished");
6474        done.succeed(completion(&done));
6475        let err = done
6476            .edit("x".to_owned(), "y".to_owned())
6477            .unwrap_err()
6478            .to_string();
6479        assert!(err.contains("done"), "{err}");
6480
6481        // Both queued and held are the point of the feature and must work.
6482        let mut queued = task("waiting");
6483        queued.edit("x".to_owned(), "y".to_owned()).unwrap();
6484        let mut held = task("parked");
6485        held.hold_machine(None);
6486        held.edit("x".to_owned(), "y".to_owned()).unwrap();
6487    }
6488
6489    #[test]
6490    fn a_task_recorded_without_a_hold_reason_still_reads_as_none() {
6491        let (_dir, q) = queue();
6492        let path = q.path_of("20260101-000000-aaaa");
6493        std::fs::create_dir_all(q.root()).unwrap();
6494        std::fs::write(
6495            &path,
6496            serde_json::json!({
6497                "schema": SCHEMA,
6498                "id": "20260101-000000-aaaa",
6499                "title": "from before hold reasons existed",
6500                "instruction": "from before hold reasons existed",
6501                "repo": ".",
6502                "source": { "kind": "human" },
6503                "status": "held",
6504                "created_at": Timestamp::now().to_string(),
6505                "updated_at": Timestamp::now().to_string(),
6506            })
6507            .to_string(),
6508        )
6509        .unwrap();
6510
6511        let task = q.get("20260101-000000-aaaa").expect("must still read");
6512        assert!(task.hold_reason.is_none());
6513        assert!(task.operator_held());
6514    }
6515
6516    #[test]
6517    fn a_legacy_reasoned_hold_defaults_to_operator_protection() {
6518        let (_dir, q) = queue();
6519        let path = q.path_of("20260101-000000-bbbb");
6520        std::fs::create_dir_all(q.root()).unwrap();
6521        std::fs::write(
6522            &path,
6523            serde_json::json!({
6524                "schema": 2,
6525                "id": "20260101-000000-bbbb",
6526                "title": "old manual recovery",
6527                "instruction": "old manual recovery",
6528                "repo": ".",
6529                "source": { "kind": "human" },
6530                "status": "held",
6531                "hold_reason": "active manual recovery run20260912-224242-daf5",
6532                "created_at": Timestamp::now().to_string(),
6533                "updated_at": Timestamp::now().to_string(),
6534            })
6535            .to_string(),
6536        )
6537        .unwrap();
6538
6539        let task = q.get("20260101-000000-bbbb").expect("must still read");
6540        assert_eq!(task.hold_source, None);
6541        assert!(task.operator_held());
6542    }
6543
6544    #[test]
6545    fn a_task_recorded_without_a_diagnostic_still_reads_as_none() {
6546        let (_dir, q) = queue();
6547        let path = q.path_of("20260101-000000-aaaa");
6548        std::fs::create_dir_all(q.root()).unwrap();
6549        std::fs::write(
6550            &path,
6551            serde_json::json!({
6552                "schema": SCHEMA,
6553                "id": "20260101-000000-aaaa",
6554                "title": "from before diagnostics existed",
6555                "instruction": "from before diagnostics existed",
6556                "repo": ".",
6557                "source": { "kind": "human" },
6558                "status": "held",
6559                "created_at": Timestamp::now().to_string(),
6560                "updated_at": Timestamp::now().to_string(),
6561            })
6562            .to_string(),
6563        )
6564        .unwrap();
6565
6566        let task = q.get("20260101-000000-aaaa").expect("must still read");
6567        assert!(task.diagnostic.is_none());
6568    }
6569
6570    #[test]
6571    fn a_schema_1_task_with_no_blocking_fields_still_reads() {
6572        // Written by a build that predates `blocked_by`, `block_reason`,
6573        // `answers` and `review_branch` entirely - literal `"schema": 1`,
6574        // not `SCHEMA`, since the whole point is a build older than this one.
6575        let (_dir, q) = queue();
6576        let path = q.path_of("20260101-000000-aaaa");
6577        std::fs::create_dir_all(q.root()).unwrap();
6578        std::fs::write(
6579            &path,
6580            serde_json::json!({
6581                "schema": 1,
6582                "id": "20260101-000000-aaaa",
6583                "title": "from before blocking existed",
6584                "instruction": "from before blocking existed",
6585                "repo": ".",
6586                "source": { "kind": "human" },
6587                "status": "queued",
6588                "created_at": Timestamp::now().to_string(),
6589                "updated_at": Timestamp::now().to_string(),
6590            })
6591            .to_string(),
6592        )
6593        .unwrap();
6594
6595        let task = q.get("20260101-000000-aaaa").expect("must still read");
6596        assert!(task.blocked_by.is_empty());
6597        assert!(task.block_reason.is_none());
6598        assert!(task.answers.is_empty());
6599        assert!(task.review_branch.is_none());
6600    }
6601
6602    #[test]
6603    fn releasing_or_finishing_a_task_clears_its_stale_diagnostic() {
6604        // A diagnostic belongs to the run that produced it. Left in place
6605        // across a release, an unrelated later failure - a config error, say -
6606        // would go on showing evidence for a problem that is no longer why the
6607        // task is stuck.
6608        let mut held = task("diagnosed");
6609        held.start("run-1".to_owned());
6610        held.fail("gate red", 1);
6611        held.diagnostic = Some("cargo test failed: ...".to_owned());
6612        assert_eq!(held.status, TaskStatus::Held);
6613
6614        held.release();
6615        assert!(held.diagnostic.is_none());
6616
6617        held.diagnostic = Some("cargo test failed: ...".to_owned());
6618        held.succeed(completion(&held));
6619        assert!(held.diagnostic.is_none());
6620    }
6621
6622    #[test]
6623    fn failing_a_task_always_clears_whatever_diagnostic_it_carried() {
6624        let mut t = task("retried");
6625        t.start("run-1".to_owned());
6626        t.diagnostic = Some("stale evidence from a previous hold".to_owned());
6627        t.fail("unrelated config error", 5);
6628        assert_eq!(t.status, TaskStatus::Failed);
6629        assert!(
6630            t.diagnostic.is_none(),
6631            "fail() must not let an old diagnostic outlive the run that produced it"
6632        );
6633    }
6634
6635    #[test]
6636    fn a_claim_is_exclusive_and_releases_on_drop() {
6637        let (_dir, q) = queue();
6638        let mut t = task("contended");
6639        q.put(&mut t).unwrap();
6640
6641        let held = q.claim(&t.id).unwrap();
6642        assert!(
6643            q.claim(&t.id).is_err(),
6644            "two daemons must not drive one task into two runs"
6645        );
6646        drop(held);
6647        assert!(q.claim(&t.id).is_ok(), "a released claim is reclaimable");
6648    }
6649
6650    #[test]
6651    fn a_round_trip_survives_disk() {
6652        let (_dir, q) = queue();
6653        let mut t = Task::new(
6654            "titled".to_owned(),
6655            "body".to_owned(),
6656            PathBuf::from("/repo"),
6657            Source::Agent {
6658                run: "20260101-000000-beef".to_owned(),
6659                node: "implement".to_owned(),
6660            },
6661        );
6662        t.priority = 3;
6663        q.put(&mut t).unwrap();
6664
6665        let back = q.get(&t.id).unwrap();
6666        assert_eq!(back.id, t.id);
6667        assert_eq!(back.priority, 3);
6668        assert_eq!(back.source.label(), "implement@beef");
6669        // A prefix is enough, the way run ids work everywhere else.
6670        assert_eq!(q.get(t.short()).unwrap().id, t.id);
6671    }
6672
6673    #[test]
6674    fn an_unreadable_task_does_not_take_the_queue_down() {
6675        let (_dir, q) = queue();
6676        let mut t = task("fine");
6677        q.put(&mut t).unwrap();
6678        std::fs::write(q.root().join("broken.json"), "{ not json").unwrap();
6679
6680        let listed = q.list();
6681        assert_eq!(listed.len(), 1, "the readable task still lists");
6682        assert_eq!(listed[0].id, t.id);
6683    }
6684
6685    #[test]
6686    fn a_task_recorded_without_a_solo_field_still_reads_as_not_solo() {
6687        let (_dir, q) = queue();
6688        let path = q.path_of("20260101-000000-aaaa");
6689        std::fs::create_dir_all(q.root()).unwrap();
6690        std::fs::write(
6691            &path,
6692            serde_json::json!({
6693                "schema": SCHEMA,
6694                "id": "20260101-000000-aaaa",
6695                "title": "from before solo existed",
6696                "instruction": "from before solo existed",
6697                "repo": ".",
6698                "source": { "kind": "human" },
6699                "status": "queued",
6700                "created_at": Timestamp::now().to_string(),
6701                "updated_at": Timestamp::now().to_string(),
6702            })
6703            .to_string(),
6704        )
6705        .unwrap();
6706
6707        let task = q.get("20260101-000000-aaaa").expect("must still read");
6708        assert!(!task.solo, "a queue file with no `solo` field means false");
6709    }
6710
6711    #[test]
6712    fn a_task_recorded_without_an_urgent_field_still_reads_as_not_urgent() {
6713        let (_dir, q) = queue();
6714        let path = q.path_of("20260101-000000-bbbb");
6715        std::fs::create_dir_all(q.root()).unwrap();
6716        std::fs::write(
6717            &path,
6718            serde_json::json!({
6719                "schema": SCHEMA,
6720                "id": "20260101-000000-bbbb",
6721                "title": "from before urgent existed",
6722                "instruction": "from before urgent existed",
6723                "repo": ".",
6724                "source": { "kind": "human" },
6725                "status": "queued",
6726                "created_at": Timestamp::now().to_string(),
6727                "updated_at": Timestamp::now().to_string(),
6728            })
6729            .to_string(),
6730        )
6731        .unwrap();
6732
6733        let task = q.get("20260101-000000-bbbb").expect("must still read");
6734        assert!(
6735            !task.urgent,
6736            "a queue file with no `urgent` field means false, same as `solo`"
6737        );
6738    }
6739
6740    #[test]
6741    fn a_task_from_a_future_schema_is_refused_rather_than_guessed_at() {
6742        let (_dir, q) = queue();
6743        let mut t = task("from the future");
6744        q.put(&mut t).unwrap();
6745        let path = q.path_of(&t.id);
6746        let body = std::fs::read_to_string(&path)
6747            .unwrap()
6748            .replace(&format!("\"schema\": {SCHEMA}"), "\"schema\": 99");
6749        std::fs::write(&path, body).unwrap();
6750
6751        let err = q.get(&t.id).unwrap_err().to_string();
6752        assert!(err.contains("schema 99"), "{err}");
6753    }
6754
6755    #[test]
6756    fn revision_moves_when_the_queue_changes() {
6757        let (_dir, q) = queue();
6758        assert_eq!(q.revision(), 0, "an empty queue has no revision");
6759        let mut t = task("first");
6760        q.put(&mut t).unwrap();
6761        assert!(q.revision() > 0, "a written task moves the revision");
6762    }
6763
6764    #[test]
6765    fn revision_moves_when_deleting_an_older_task() {
6766        let (dir, q) = queue();
6767        let questions = Questions::at(dir.path().join("questions"));
6768        let mut t1 = task("older");
6769        q.put(&mut t1).unwrap();
6770        // Ensure mtime ticks forward.
6771        std::thread::sleep(std::time::Duration::from_millis(10));
6772        let mut t2 = task("newer");
6773        q.put(&mut t2).unwrap();
6774
6775        let rev_before = q.revision();
6776        q.remove(&t1.id, false, &questions).unwrap();
6777        let rev_after = q.revision();
6778
6779        assert_ne!(
6780            rev_before, rev_after,
6781            "deleting an older task must change the revision so other clients see the deletion"
6782        );
6783    }
6784
6785    #[test]
6786    fn removing_a_task_takes_it_out_of_the_listing() {
6787        let (dir, q) = queue();
6788        let questions = Questions::at(dir.path().join("questions"));
6789        let mut t = task("delete me");
6790        q.put(&mut t).unwrap();
6791        let removed = q.remove(t.short(), false, &questions).unwrap();
6792        assert_eq!(removed.id, t.id, "a prefix resolves before deleting");
6793        assert!(removed.released.is_empty() && removed.still_blocked.is_empty());
6794        assert!(q.list().is_empty());
6795        assert!(
6796            q.remove(&t.id, false, &questions).is_err(),
6797            "removing twice is an error"
6798        );
6799    }
6800
6801    #[test]
6802    fn removing_a_task_takes_its_stale_lock_with_it() {
6803        let (dir, q) = queue();
6804        let questions = Questions::at(dir.path().join("questions"));
6805        let mut t = task("interrupted");
6806        q.put(&mut t).unwrap();
6807
6808        // A daemon killed mid-run leaves this behind. Nothing holds it: the
6809        // process that would have dropped the guard is gone.
6810        let claim = q.claim(&t.id).unwrap();
6811        std::mem::forget(claim);
6812        assert!(
6813            q.claim(&t.id).is_err(),
6814            "the orphaned lock is what makes the task look claimed"
6815        );
6816
6817        // A live daemon on this task is refused, whatever the lock says.
6818        let err = q.remove(&t.id, true, &questions).unwrap_err().to_string();
6819        assert!(err.contains("live daemon"), "{err}");
6820        assert!(q.get(&t.id).is_ok(), "a refused delete keeps the task");
6821
6822        // With no daemon behind it, the lock is stale and goes with the task.
6823        q.remove(&t.id, false, &questions).unwrap();
6824        assert!(q.list().is_empty());
6825        let mut again = task("interrupted");
6826        again.id = t.id.clone();
6827        q.put(&mut again).unwrap();
6828        assert!(
6829            q.claim(&t.id).is_ok(),
6830            "a task that comes back must be claimable, which a left-behind lock would prevent"
6831        );
6832    }
6833
6834    fn notices_of(dir: &Path) -> Vec<crate::notices::Notice> {
6835        crate::notices::Notices::at(dir.join("notifications")).list()
6836    }
6837
6838    #[test]
6839    fn removing_a_sole_dependency_releases_the_dependent_without_a_hold() {
6840        let (dir, q) = queue();
6841        let questions = Questions::at(dir.path().join("questions"));
6842        let mut dep = task("dependency");
6843        q.put(&mut dep).unwrap();
6844        let mut blocked = task("waiting");
6845        blocked.block(vec![dep.id.clone()], Some("waits".to_owned()));
6846        q.put(&mut blocked).unwrap();
6847
6848        let removed = q.remove(&dep.id, false, &questions).unwrap();
6849        assert_eq!(removed.released, [blocked.id.clone()]);
6850        assert!(removed.still_blocked.is_empty());
6851
6852        let after = q.get(&blocked.id).unwrap();
6853        assert_eq!(after.status, TaskStatus::Queued);
6854        assert!(after.blocked_by.is_empty());
6855        assert!(after.block_reason.is_none());
6856        let notes = notices_of(dir.path());
6857        assert_eq!(notes.len(), 1, "{notes:?}");
6858        assert_eq!(notes[0].severity, crate::notices::Severity::Info);
6859        assert_eq!(
6860            notes[0].link,
6861            Some(crate::notices::Link::Task {
6862                id: blocked.id.clone(),
6863            })
6864        );
6865    }
6866
6867    #[test]
6868    fn removing_one_of_two_dependencies_keeps_the_other() {
6869        let (dir, q) = queue();
6870        let questions = Questions::at(dir.path().join("questions"));
6871        let mut dep = task("dependency");
6872        q.put(&mut dep).unwrap();
6873        let mut other = task("other");
6874        q.put(&mut other).unwrap();
6875        let mut blocked = task("waiting");
6876        blocked.block(
6877            vec![dep.id.clone(), other.id.clone()],
6878            Some("waits on both".to_owned()),
6879        );
6880        q.put(&mut blocked).unwrap();
6881
6882        let removed = q.remove(&dep.id, false, &questions).unwrap();
6883        assert!(removed.released.is_empty());
6884        assert_eq!(removed.still_blocked, [blocked.id.clone()]);
6885
6886        let after = q.get(&blocked.id).unwrap();
6887        assert_eq!(after.status, TaskStatus::Blocked);
6888        assert_eq!(after.blocked_by, [other.id.clone()]);
6889        // The tombstone stays while a task still names the id... only this
6890        // one's dependency is gone, so nothing references it and it may go.
6891        assert!(missing_blockers(&q, &questions, &after.blocked_by).is_empty());
6892    }
6893
6894    #[test]
6895    fn a_dependency_deleted_before_its_dependents_were_rewritten_is_released_later() {
6896        let (dir, q) = queue();
6897        let questions = Questions::at(dir.path().join("questions"));
6898        let mut dep = task("dependency");
6899        q.put(&mut dep).unwrap();
6900        let mut blocked = task("waiting");
6901        blocked.block(vec![dep.id.clone()], None);
6902        q.put(&mut blocked).unwrap();
6903
6904        // The dependent is claimed elsewhere, so `remove` has to skip it.
6905        let claim = q.claim(&blocked.id).unwrap();
6906        let removed = q.remove(&dep.id, false, &questions).unwrap();
6907        assert!(removed.released.is_empty());
6908        drop(claim);
6909
6910        let mut task = q.get(&blocked.id).unwrap();
6911        assert_eq!(task.status, TaskStatus::Blocked);
6912        assert!(missing_blockers(&q, &questions, &task.blocked_by).is_empty());
6913        assert_eq!(
6914            q.apply_deleted_blockers(&mut task, &questions),
6915            [dep.id.clone()]
6916        );
6917        assert_eq!(task.status, TaskStatus::Queued);
6918    }
6919
6920    #[test]
6921    fn dependency_resolution_short_deleted_reference_releases_only_its_waiters() {
6922        let (dir, q) = queue();
6923        let questions = Questions::at(dir.path().join("questions"));
6924        let mut dep = task("dependency");
6925        dep.id = "20261013-193611-ca5b".into();
6926        q.put(&mut dep).unwrap();
6927        let mut waiting = task("waiting");
6928        waiting.block(vec!["ca5b".into()], None);
6929        q.put(&mut waiting).unwrap();
6930        q.remove(&dep.id, false, &questions).unwrap();
6931        assert_eq!(q.get(&waiting.id).unwrap().status, TaskStatus::Queued);
6932        assert_eq!(
6933            dependency(&q, &questions, "ca5b"),
6934            Dependency::Deleted(dep.id)
6935        );
6936    }
6937
6938    #[test]
6939    fn dependency_resolution_preserves_cross_store_ambiguity_and_exact_ids() {
6940        let (dir, queue) = queue();
6941        let questions = Questions::at(dir.path().join("questions"));
6942        let mut dep = task("dependency");
6943        dep.id = "20261013-193611-ca5b".into();
6944        queue.put(&mut dep).unwrap();
6945        std::fs::create_dir_all(questions.root()).unwrap();
6946        let question_id = "20261014-193611-ca5b";
6947        std::fs::write(questions.path_of(question_id), "unreadable question").unwrap();
6948        assert_eq!(questions.resolve_id("ca5b").unwrap(), question_id);
6949        assert_eq!(
6950            dependency(&queue, &questions, "ca5b"),
6951            Dependency::Ambiguous
6952        );
6953        assert_eq!(
6954            dependency(&queue, &questions, &dep.id),
6955            Dependency::Task(dep.id)
6956        );
6957        assert_eq!(
6958            dependency(&queue, &questions, question_id),
6959            Dependency::Question(question_id.into())
6960        );
6961        assert_eq!(
6962            dependency(&queue, &questions, "missing"),
6963            Dependency::Missing
6964        );
6965    }
6966
6967    #[test]
6968    fn dependency_resolution_directory_errors_are_unknown_not_missing() {
6969        let dir = tempfile::tempdir().unwrap();
6970        let q = Queue::at(dir.path().join("not-a-directory"));
6971        std::fs::write(q.root(), "file").unwrap();
6972        let questions = Questions::at(dir.path().join("questions"));
6973        assert_eq!(dependency(&q, &questions, "ca5b"), Dependency::Unknown);
6974        assert!(missing_blockers(&q, &questions, &["ca5b".into()]).is_empty());
6975    }
6976
6977    #[test]
6978    fn a_dependency_without_a_tombstone_is_still_missing() {
6979        let (dir, q) = queue();
6980        let questions = Questions::at(dir.path().join("questions"));
6981        let mut dep = task("dependency");
6982        q.put(&mut dep).unwrap();
6983        std::fs::remove_file(q.path_of(&dep.id)).unwrap();
6984        assert_eq!(
6985            missing_blockers(&q, &questions, std::slice::from_ref(&dep.id)),
6986            [dep.id.clone()]
6987        );
6988        assert!(deleted_blockers(&q, &questions, std::slice::from_ref(&dep.id)).is_empty());
6989    }
6990
6991    #[test]
6992    fn a_held_dependent_is_left_alone_by_a_dependency_deletion() {
6993        let mut t = task("held");
6994        t.hold_machine(Some("because".to_owned()));
6995        t.blocked_by = vec!["gone".to_owned()];
6996        assert!(!t.dependency_deleted("gone"));
6997        assert_eq!(t.status, TaskStatus::Held);
6998    }
6999
7000    #[test]
7001    fn a_failed_record_removal_takes_the_tombstone_back() {
7002        let (_dir, q) = queue();
7003        let mut t = task("stays");
7004        q.put(&mut t).unwrap();
7005        q.write_tombstone(&t.id).unwrap();
7006        let err = q.remove_record_with_attachments(&t.id, |_| Err(std::io::Error::other("nope")));
7007        assert!(err.is_err());
7008        // `remove` is what withdraws the marker; a live record is never
7009        // treated as deleted whatever is on disk.
7010        assert!(!q.was_deleted(&t.id));
7011    }
7012
7013    fn source_file(dir: &Path, name: &str, body: &str) -> PathBuf {
7014        let p = dir.join(name);
7015        std::fs::write(&p, body).unwrap();
7016        p
7017    }
7018
7019    #[test]
7020    fn an_attachment_copy_survives_deleting_its_source() {
7021        let (dir, q) = queue();
7022        let src = source_file(dir.path(), "shot.png", "pixels");
7023        let mut t = task("with a picture");
7024        let names = q.attach(&mut t, std::slice::from_ref(&src)).unwrap();
7025        q.put(&mut t).unwrap();
7026        std::fs::remove_file(&src).unwrap();
7027        assert_eq!(names, ["shot.png"]);
7028        let loaded = q.get(&t.id).unwrap();
7029        let paths = q.attachment_paths(&loaded);
7030        assert_eq!(paths.len(), 1);
7031        assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "pixels");
7032    }
7033
7034    #[test]
7035    fn attachment_names_that_could_traverse_or_are_odd_are_refused() {
7036        let (dir, q) = queue();
7037        let mut t = task("bad names");
7038        for name in ["a..b.png", ".hidden", "with space.png", "-x.png"] {
7039            let src = source_file(dir.path(), name, "x");
7040            assert!(
7041                q.attach(&mut t, &[src]).is_err(),
7042                "`{name}` must be refused"
7043            );
7044        }
7045        // A drive-qualified name cannot exist as a file on Windows (joining it
7046        // to a directory yields a drive-relative path to `foo.png` instead),
7047        // so the rule is asserted on the name itself, everywhere.
7048        assert!(!crate::ask::valid_asset_name("C:foo.png"));
7049        #[cfg(not(windows))]
7050        {
7051            let src = source_file(dir.path(), "C:foo.png", "x");
7052            assert!(q.attach(&mut t, &[src]).is_err());
7053        }
7054        let long = format!("{}.png", "a".repeat(70));
7055        let src = source_file(dir.path(), &long, "x");
7056        assert!(q.attach(&mut t, &[src]).is_err());
7057        assert!(t.attachments.is_empty());
7058        assert!(!q.attachments_dir(&t.id).exists());
7059    }
7060
7061    #[test]
7062    fn a_taken_attachment_name_is_numbered_not_overwritten() {
7063        let (dir, q) = queue();
7064        let a = source_file(dir.path(), "shot.png", "one");
7065        let sub = dir.path().join("other");
7066        std::fs::create_dir_all(&sub).unwrap();
7067        let b = source_file(&sub, "shot.png", "two");
7068        let mut t = task("collision");
7069        q.attach(&mut t, &[a]).unwrap();
7070        q.attach(&mut t, &[b]).unwrap();
7071        assert_eq!(t.attachments, ["shot.png", "shot-2.png"]);
7072        let paths = q.attachment_paths(&t);
7073        assert_eq!(std::fs::read_to_string(&paths[0]).unwrap(), "one");
7074        assert_eq!(std::fs::read_to_string(&paths[1]).unwrap(), "two");
7075    }
7076
7077    #[test]
7078    fn a_renumbered_name_stays_inside_the_length_bound() {
7079        let (dir, q) = queue();
7080        let name = format!("{}.png", "a".repeat(60));
7081        assert_eq!(name.len(), 64);
7082        let a = source_file(dir.path(), &name, "one");
7083        let sub = dir.path().join("other");
7084        std::fs::create_dir_all(&sub).unwrap();
7085        let b = source_file(&sub, &name, "two");
7086        let mut t = task("long");
7087        q.attach(&mut t, &[a, b]).unwrap();
7088        assert_eq!(t.attachments.len(), 2);
7089        assert!(
7090            t.attachments
7091                .iter()
7092                .all(|n| crate::ask::valid_asset_name(n))
7093        );
7094        assert!(t.attachments[1].ends_with("-2.png"));
7095    }
7096
7097    #[test]
7098    fn a_failed_attach_keeps_existing_attachments_and_leaves_no_partial_copy() {
7099        let (dir, q) = queue();
7100        let good = source_file(dir.path(), "good.png", "ok");
7101        let mut t = task("partial");
7102        q.attach(&mut t, &[good]).unwrap();
7103        let more = source_file(dir.path(), "more.png", "ok");
7104        let missing = dir.path().join("missing.png");
7105        assert!(q.attach(&mut t, &[more, missing]).is_err());
7106        assert_eq!(t.attachments, ["good.png"]);
7107        let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7108            .unwrap()
7109            .flatten()
7110            .collect();
7111        assert_eq!(on_disk.len(), 1);
7112    }
7113
7114    /// Make the next `put` of `t` fail: its temp file's path is a directory.
7115    fn block_put(q: &Queue, t: &Task) -> PathBuf {
7116        let tmp = q.path_of(&t.id).with_extension("json.tmp");
7117        std::fs::create_dir_all(&tmp).unwrap();
7118        tmp
7119    }
7120
7121    #[test]
7122    fn a_failed_put_leaves_no_new_attachment_directory() {
7123        let (dir, q) = queue();
7124        let mut t = task("fresh");
7125        let tmp = block_put(&q, &t);
7126        let src = source_file(dir.path(), "shot.png", "x");
7127        assert!(q.attach_and_put(&mut t, &[src]).is_err());
7128        assert!(t.attachments.is_empty());
7129        assert!(!q.attachments_dir(&t.id).exists());
7130        assert!(!q.path_of(&t.id).exists());
7131        std::fs::remove_dir(tmp).unwrap();
7132    }
7133
7134    #[test]
7135    fn a_failed_put_removes_only_the_copy_it_just_made() {
7136        let (dir, q) = queue();
7137        let mut t = task("edited");
7138        let first = source_file(dir.path(), "first.png", "1");
7139        q.attach_and_put(&mut t, &[first]).unwrap();
7140        block_put(&q, &t);
7141        let second = source_file(dir.path(), "second.png", "2");
7142        assert!(q.attach_and_put(&mut t, &[second]).is_err());
7143        assert_eq!(t.attachments, ["first.png"]);
7144        let on_disk: Vec<_> = std::fs::read_dir(q.attachments_dir(&t.id))
7145            .unwrap()
7146            .flatten()
7147            .map(|e| e.file_name().to_string_lossy().into_owned())
7148            .collect();
7149        assert_eq!(on_disk, ["first.png"]);
7150        assert_eq!(q.get(&t.id).unwrap().attachments, ["first.png"]);
7151    }
7152
7153    #[test]
7154    fn a_leftover_removing_directory_is_swept_by_the_next_removal() {
7155        let (dir, q) = queue();
7156        let questions = Questions::at(dir.path().join("questions"));
7157        let gone = task("gone");
7158        let mut other = task("other");
7159        let mut live = task("live");
7160        q.put(&mut other).unwrap();
7161        q.put(&mut live).unwrap();
7162        // `gone` has no record: its removal finished deleting the record but
7163        // not the set-aside attachments.
7164        let orphan = q.root.join(format!("{}.attachments.removing", gone.id));
7165        std::fs::create_dir_all(&orphan).unwrap();
7166        std::fs::write(orphan.join("shot.png"), "x").unwrap();
7167        // `live` still has a record, so its `.removing` belongs to a removal
7168        // in progress and must be left alone.
7169        let busy = q.root.join(format!("{}.attachments.removing", live.id));
7170        std::fs::create_dir_all(&busy).unwrap();
7171
7172        q.remove(&other.id, false, &questions).unwrap();
7173        assert!(!orphan.exists(), "an orphan is swept");
7174        assert!(busy.exists(), "a removal in progress is left alone");
7175    }
7176
7177    #[test]
7178    fn a_blocked_aside_rename_fails_the_removal_and_loses_nothing() {
7179        let (dir, q) = queue();
7180        let questions = Questions::at(dir.path().join("questions"));
7181        let mut t = task("stuck");
7182        let src = source_file(dir.path(), "shot.png", "x");
7183        q.attach_and_put(&mut t, &[src]).unwrap();
7184        // A non-empty directory already at the set-aside name makes the rename
7185        // fail; its record is present, so the sweep leaves it in place.
7186        let aside = q.root.join(format!("{}.attachments.removing", t.id));
7187        std::fs::create_dir_all(&aside).unwrap();
7188        std::fs::write(aside.join("old.png"), "o").unwrap();
7189        assert!(q.remove(&t.id, false, &questions).is_err());
7190        assert!(q.path_of(&t.id).exists());
7191        assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7192    }
7193
7194    #[test]
7195    fn a_failed_record_removal_puts_the_attachments_back() {
7196        let (dir, q) = queue();
7197        let mut t = task("rollback");
7198        let src = source_file(dir.path(), "shot.png", "x");
7199        q.attach_and_put(&mut t, &[src]).unwrap();
7200        let err = q
7201            .remove_record_with_attachments(&t.id, |_| {
7202                Err(std::io::Error::other("injected failure"))
7203            })
7204            .unwrap_err();
7205        assert!(format!("{err:#}").contains("injected failure"));
7206        assert!(q.path_of(&t.id).exists());
7207        assert!(q.attachments_dir(&t.id).join("shot.png").is_file());
7208        assert!(
7209            !q.root
7210                .join(format!("{}.attachments.removing", t.id))
7211                .exists()
7212        );
7213    }
7214
7215    #[test]
7216    fn editing_a_task_keeps_its_attachments() {
7217        let (dir, q) = queue();
7218        let src = source_file(dir.path(), "shot.png", "x");
7219        let mut t = task("editable");
7220        q.attach(&mut t, &[src]).unwrap();
7221        t.edit("new".to_owned(), "new text".to_owned()).unwrap();
7222        q.put(&mut t).unwrap();
7223        assert_eq!(q.get(&t.id).unwrap().attachments, ["shot.png"]);
7224    }
7225
7226    #[test]
7227    fn removing_a_task_deletes_its_attachments() {
7228        let (dir, q) = queue();
7229        let questions = Questions::at(dir.path().join("questions"));
7230        let src = source_file(dir.path(), "shot.png", "x");
7231        let mut t = task("doomed");
7232        q.attach(&mut t, &[src]).unwrap();
7233        q.put(&mut t).unwrap();
7234        assert!(q.attachments_dir(&t.id).is_dir());
7235        q.remove(&t.id, false, &questions).unwrap();
7236        assert!(!q.attachments_dir(&t.id).exists());
7237        assert!(q.list().is_empty());
7238    }
7239
7240    #[test]
7241    fn a_task_written_before_attachments_still_reads() {
7242        let (_dir, q) = queue();
7243        let mut t = task("old");
7244        q.put(&mut t).unwrap();
7245        let path = q.path_of(&t.id);
7246        let mut v: serde_json::Value =
7247            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
7248        v.as_object_mut().unwrap().remove("attachments");
7249        std::fs::write(&path, v.to_string()).unwrap();
7250        assert!(q.get(&t.id).unwrap().attachments.is_empty());
7251    }
7252
7253    #[test]
7254    fn attachment_paths_are_absolute_even_when_the_root_is_relative() {
7255        let q = Queue::at(PathBuf::from("relative-queue"));
7256        let mut t = task("rel");
7257        t.attachments.push("shot.png".to_owned());
7258        let paths = q.attachment_paths(&t);
7259        assert!(paths[0].is_absolute(), "{}", paths[0].display());
7260        assert!(paths[0].ends_with(format!("{}.attachments/shot.png", t.id)));
7261    }
7262
7263    fn upgrade_parked(id: &str, started: &str) -> Task {
7264        let mut t = task(id);
7265        t.id = id.into();
7266        t.start(format!("run-{id}"));
7267        t.park("upgrade");
7268        t.record_pass_at(
7269            &format!("run-{id}"),
7270            0,
7271            Some(started.parse().unwrap()),
7272            1,
7273            Some(crate::run::ParkCause::Upgrade {
7274                from: "old".into(),
7275                to: None,
7276            }),
7277        );
7278        t
7279    }
7280
7281    #[test]
7282    fn upgrade_resume_order_follows_dispatch_claim_not_graph_start() {
7283        // A was claimed first but its graph pass started later (slow start-up).
7284        let stamp = |id: &str, dispatched: &str, started: &str| {
7285            let mut t = task(id);
7286            t.id = id.into();
7287            t.start(format!("run-{id}"));
7288            t.park("upgrade");
7289            t.dispatched_at = Some(dispatched.parse().unwrap());
7290            t.record_pass_at(
7291                &format!("run-{id}"),
7292                0,
7293                Some(started.parse().unwrap()),
7294                1,
7295                Some(crate::run::ParkCause::Upgrade {
7296                    from: "old".into(),
7297                    to: None,
7298                }),
7299            );
7300            t
7301        };
7302        let a = stamp("a", "2026-10-22T00:00:01Z", "2026-10-22T00:00:09Z");
7303        let b = stamp("b", "2026-10-22T00:00:02Z", "2026-10-22T00:00:03Z");
7304        assert!(dispatch_order(&a, &b).is_lt());
7305    }
7306
7307    #[test]
7308    fn upgrade_resume_order_survives_queue_reload_and_reversed_settlement() {
7309        let (_dir, q) = queue();
7310        let mut later = upgrade_parked("later", "2026-10-22T00:00:02Z");
7311        let mut earlier = upgrade_parked("earlier", "2026-10-22T00:00:01Z");
7312        earlier.priority = -10;
7313        let mut fresh = task("fresh");
7314        fresh.id = "newer".into();
7315        fresh.priority = 100;
7316        for t in [&mut fresh, &mut later, &mut earlier] {
7317            q.put(t).unwrap();
7318        }
7319        let reloaded = Queue::at(q.root().to_owned());
7320        let mut tasks = reloaded.list();
7321        tasks.sort_unstable_by(dispatch_order);
7322        assert_eq!(
7323            tasks.iter().map(|t| t.id.as_str()).collect::<Vec<_>>(),
7324            vec!["earlier", "later", "newer"]
7325        );
7326        assert_eq!(reloaded.next_runnable().unwrap().id, "earlier");
7327        assert_eq!(reloaded.get("earlier").unwrap().attempts, 0);
7328    }
7329
7330    #[test]
7331    fn upgrade_resume_legacy_order_uses_settlement_and_id() {
7332        let mut a = upgrade_parked("a", "2026-10-22T00:00:02Z");
7333        let mut b = upgrade_parked("b", "2026-10-22T00:00:01Z");
7334        for t in [&mut a, &mut b] {
7335            let mut value = serde_json::to_value(&*t).unwrap();
7336            value["passes"][0]
7337                .as_object_mut()
7338                .unwrap()
7339                .remove("started_at");
7340            *t = serde_json::from_value(value).unwrap();
7341        }
7342        assert!(dispatch_order(&a, &b).is_lt());
7343        b.passes[0].settled_at = a.passes[0].settled_at;
7344        assert!(dispatch_order(&a, &b).is_lt());
7345    }
7346
7347    #[test]
7348    fn upgrade_resume_key_excludes_other_parks_and_explicit_task_changes() {
7349        let original = upgrade_parked("a", "2026-10-22T00:00:01Z");
7350        assert!(original.upgrade_resume_key().is_some());
7351        for cause in [
7352            crate::run::ParkCause::Operator,
7353            crate::run::ParkCause::Question,
7354            crate::run::ParkCause::Interrupt {
7355                reason: "interrupt".into(),
7356            },
7357            crate::run::ParkCause::Unspecified,
7358        ] {
7359            let mut t = original.clone();
7360            t.passes[0].parked = Some(cause);
7361            assert!(t.upgrade_resume_key().is_none());
7362            let mut fresh = task("fresh");
7363            fresh.priority = 1;
7364            assert!(dispatch_order(&fresh, &t).is_lt());
7365        }
7366        let mut t = original.clone();
7367        t.release();
7368        assert!(t.upgrade_resume_key().is_none());
7369        t.edit("edited".into(), "new instruction".into()).unwrap();
7370        assert!(t.upgrade_resume_key().is_none());
7371        let mut t = original.clone();
7372        t.requeue();
7373        t.status = TaskStatus::Parked;
7374        assert!(t.upgrade_resume_key().is_none());
7375        let mut t = original.clone();
7376        t.start("different-run".into());
7377        t.park("no upgrade");
7378        assert!(t.upgrade_resume_key().is_none());
7379    }
7380
7381    #[test]
7382    fn explicitly_resumed_older_run_becomes_current_without_duplicate_history() {
7383        let dir = tempfile::tempdir().unwrap();
7384        let q = Queue::at(dir.path().join("queue"));
7385        let mut t = task("resume");
7386        t.start("A".into());
7387        t.record_pass("A", 0, 1, None);
7388        t.start("B".into());
7389        q.put(&mut t).unwrap();
7390        assert_eq!(t.runs, vec!["A", "B"]);
7391        t.start("A".into());
7392        t.record_pass("A", 1, 3, None);
7393        q.put(&mut t).unwrap();
7394        let saved = q.get(&t.id).unwrap();
7395        assert_eq!(saved.runs, vec!["B", "A"]);
7396        assert_eq!(saved.runs.last().map(String::as_str), Some("A"));
7397        assert_eq!(saved.attempts, 3);
7398        assert_eq!(saved.passes.len(), 2);
7399        assert_eq!(saved.passes[0].run, "A");
7400        assert_eq!(saved.passes[1].run, "A");
7401    }
7402
7403    #[test]
7404    fn repeated_start_records_one_run_and_separate_passes() {
7405        let mut t = task("resume");
7406        t.start("same-run".into());
7407        t.record_pass("same-run", 0, 1, None);
7408        t.start("same-run".into());
7409        t.record_pass("same-run", 1, 2, None);
7410        assert_eq!(t.runs, vec!["same-run"]);
7411        assert_eq!(t.attempts, 2);
7412        assert_eq!(t.passes.len(), 2);
7413    }
7414
7415    #[test]
7416    fn link_run_adds_a_run_once_and_touches_nothing_else() {
7417        let dir = tempfile::tempdir().unwrap();
7418        let queue = Queue::at(dir.path().join("queue"));
7419        let mut t = Task::new(
7420            "t".to_owned(),
7421            "do it".to_owned(),
7422            PathBuf::from("."),
7423            Source::Human,
7424        );
7425        queue.put(&mut t).unwrap();
7426        let before = queue.get(&t.id).unwrap();
7427
7428        let linked = queue.link_run(&t.id[..4], "20260930-092817-ec34").unwrap();
7429        assert_eq!(linked.runs, vec!["20260930-092817-ec34".to_owned()]);
7430        assert_eq!(linked.status, before.status);
7431        assert_eq!(linked.attempts, before.attempts);
7432        assert_eq!(linked.interrupt, before.interrupt);
7433
7434        let again = queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7435        assert_eq!(again.runs.len(), 1, "linking twice must not duplicate");
7436        assert_eq!(queue.get(&t.id).unwrap().runs.len(), 1);
7437        assert!(queue.link_run("no-such-task", "r").is_err());
7438    }
7439
7440    #[test]
7441    fn put_keeps_a_run_linked_after_the_writer_took_its_snapshot() {
7442        let dir = tempfile::tempdir().unwrap();
7443        let queue = Queue::at(dir.path().join("queue"));
7444        let mut t = Task::new(
7445            "t".to_owned(),
7446            "do it".to_owned(),
7447            PathBuf::from("."),
7448            Source::Human,
7449        );
7450        queue.put(&mut t).unwrap();
7451        // The daemon's copy, taken before the link.
7452        let mut snapshot = queue.get(&t.id).unwrap();
7453        queue.link_run(&t.id, "20260930-092817-ec34").unwrap();
7454
7455        snapshot.start("20260930-000000-aaaa".to_owned());
7456        queue.put(&mut snapshot).unwrap();
7457
7458        let stored = queue.get(&t.id).unwrap();
7459        assert!(stored.runs.contains(&"20260930-092817-ec34".to_owned()));
7460        assert!(stored.runs.contains(&"20260930-000000-aaaa".to_owned()));
7461        assert_eq!(stored.attempts, 1);
7462    }
7463
7464    #[test]
7465    fn concurrent_links_and_daemon_saves_lose_nothing() {
7466        let dir = tempfile::tempdir().unwrap();
7467        let queue = Queue::at(dir.path().join("queue"));
7468        let mut t = Task::new(
7469            "t".to_owned(),
7470            "do it".to_owned(),
7471            PathBuf::from("."),
7472            Source::Human,
7473        );
7474        queue.put(&mut t).unwrap();
7475        let id = t.id.clone();
7476
7477        let linkers: Vec<_> = (0..4)
7478            .map(|n| {
7479                let (queue, id) = (queue.clone(), id.clone());
7480                std::thread::spawn(move || {
7481                    for k in 0..10 {
7482                        queue
7483                            .link_run(&id, &format!("20260930-00000{n}-l{k:03}"))
7484                            .unwrap();
7485                    }
7486                })
7487            })
7488            .collect();
7489        // The daemon's side: transitions saved from its own, ever staler,
7490        // copy of the task.
7491        let mut mine = queue.get(&id).unwrap();
7492        for k in 0..10 {
7493            mine.start(format!("20260930-000009-d{k:03}"));
7494            queue.put(&mut mine).unwrap();
7495        }
7496        for l in linkers {
7497            l.join().unwrap();
7498        }
7499
7500        let stored = queue.get(&id).unwrap();
7501        assert_eq!(stored.runs.len(), 50, "{:?}", stored.runs);
7502        assert_eq!(
7503            stored.attempts, 10,
7504            "linking never rewinds the daemon's work"
7505        );
7506    }
7507
7508    fn age_lock(path: &Path) {
7509        let f = std::fs::OpenOptions::new().write(true).open(path).unwrap();
7510        f.set_modified(std::time::SystemTime::now() - std::time::Duration::from_secs(60))
7511            .unwrap();
7512    }
7513
7514    #[test]
7515    fn concurrent_stale_takeover_yields_one_holder() {
7516        use std::sync::atomic::{AtomicUsize, Ordering};
7517        use std::sync::{Arc, Barrier};
7518        for _ in 0..5 {
7519            let dir = tempfile::tempdir().unwrap();
7520            let q = Queue::at(dir.path().to_path_buf());
7521            let lock = dir.path().join("t.write-lock");
7522            std::fs::write(&lock, "dead-0000").unwrap();
7523            age_lock(&lock);
7524            let n = 6;
7525            let barrier = Arc::new(Barrier::new(n));
7526            let (now, max) = (Arc::new(AtomicUsize::new(0)), Arc::new(AtomicUsize::new(0)));
7527            let handles: Vec<_> = (0..n)
7528                .map(|_| {
7529                    let (q, b, now, max) = (q.clone(), barrier.clone(), now.clone(), max.clone());
7530                    std::thread::spawn(move || {
7531                        b.wait();
7532                        let g = q.lock_task("t").unwrap();
7533                        let held = now.fetch_add(1, Ordering::SeqCst) + 1;
7534                        max.fetch_max(held, Ordering::SeqCst);
7535                        std::thread::sleep(std::time::Duration::from_millis(20));
7536                        now.fetch_sub(1, Ordering::SeqCst);
7537                        drop(g);
7538                    })
7539                })
7540                .collect();
7541            for h in handles {
7542                h.join().unwrap();
7543            }
7544            assert_eq!(max.load(Ordering::SeqCst), 1);
7545            assert!(!lock.exists());
7546        }
7547    }
7548
7549    #[test]
7550    fn dropping_a_replaced_lock_leaves_the_new_holders_token() {
7551        let dir = tempfile::tempdir().unwrap();
7552        let q = Queue::at(dir.path().to_path_buf());
7553        let lock = dir.path().join("t.write-lock");
7554        let a = q.lock_task("t").unwrap();
7555        // Simulate a foreign/legacy writer replacing the file. A modern
7556        // writer cannot acquire it while this guard's process is alive.
7557        let replacement = owner_token();
7558        std::fs::write(&lock, &replacement).unwrap();
7559        drop(a);
7560        assert_eq!(std::fs::read_to_string(&lock).unwrap(), replacement);
7561    }
7562
7563    #[test]
7564    fn aged_live_task_lock_excludes_updates_until_retirement_releases_it() {
7565        let dir = tempfile::tempdir().unwrap();
7566        let q = Queue::at(dir.path().to_path_buf());
7567        let held = q.lock_task("t").unwrap();
7568        let path = dir.path().join("t.write-lock");
7569        age_lock(&path);
7570        assert!(!break_stale(&path, &held.token));
7571        let (started_tx, started_rx) = std::sync::mpsc::channel();
7572        let (acquired_tx, acquired_rx) = std::sync::mpsc::channel();
7573        let updater = std::thread::spawn(move || {
7574            started_tx.send(()).unwrap();
7575            let _write = q.lock_task("t").unwrap();
7576            acquired_tx.send(()).unwrap();
7577        });
7578        started_rx.recv().unwrap();
7579        assert!(
7580            acquired_rx
7581                .recv_timeout(std::time::Duration::from_millis(100))
7582                .is_err()
7583        );
7584        assert_eq!(std::fs::read_to_string(&path).unwrap(), held.token);
7585        drop(held);
7586        acquired_rx
7587            .recv_timeout(std::time::Duration::from_secs(2))
7588            .unwrap();
7589        updater.join().unwrap();
7590        assert!(!path.exists());
7591    }
7592
7593    #[test]
7594    fn break_stale_leaves_a_lock_that_replaced_the_one_judged() {
7595        let dir = tempfile::tempdir().unwrap();
7596        let lock = dir.path().join("t.write-lock");
7597        std::fs::write(&lock, "new-token").unwrap();
7598        assert!(!break_stale(&lock, "old-token"));
7599        assert_eq!(std::fs::read_to_string(&lock).unwrap(), "new-token");
7600        // Same token but fresh: not stale any more, so also left alone.
7601        assert!(!break_stale(&lock, "new-token"));
7602        assert!(lock.exists());
7603        age_lock(&lock);
7604        assert!(break_stale(&lock, "new-token"));
7605        assert!(!lock.exists());
7606    }
7607
7608    #[test]
7609    fn a_stale_break_marker_is_recovered_and_a_fresh_one_is_respected() {
7610        let dir = tempfile::tempdir().unwrap();
7611        let lock = dir.path().join("t.write-lock");
7612        std::fs::write(&lock, "dead-1").unwrap();
7613        age_lock(&lock);
7614        let marker = break_marker(&lock, "dead-1");
7615        std::fs::write(&marker, "crashed-remover").unwrap();
7616        // Fresh marker: another remover is working, so nothing is broken.
7617        assert!(!break_stale(&lock, "dead-1"));
7618        assert!(lock.exists());
7619        // Stale marker: recovered, then the lock is broken.
7620        age_lock(&marker);
7621        assert!(break_stale(&lock, "dead-1"));
7622        assert!(!lock.exists());
7623        assert!(!marker.exists());
7624    }
7625
7626    fn chat_task() -> Task {
7627        Task::new(
7628            "t".to_owned(),
7629            "do t".to_owned(),
7630            PathBuf::from("."),
7631            Source::Agent {
7632                run: "20260902-000000-beef".to_owned(),
7633                node: CHAT_NODE.to_owned(),
7634            },
7635        )
7636    }
7637
7638    #[test]
7639    fn a_blocked_hold_keeps_its_anchor_but_a_new_run_starts_a_new_hold() {
7640        let mut t = chat_task();
7641        t.hold_machine(Some("waiting".into()));
7642        let old: Timestamp = "2020-01-01T00:00:00Z".parse().unwrap();
7643        t.held_at = Some(old);
7644        t.block(vec!["decision".into()], None);
7645        t.hold_machine(Some("same waiting decision".into()));
7646        assert_eq!(t.held_at, Some(old));
7647        t.start("real-new-run".into());
7648        t.fail("new failure", 1);
7649        assert_ne!(
7650            t.held_at,
7651            Some(old),
7652            "old answers cannot approve a new hold"
7653        );
7654    }
7655
7656    #[test]
7657    fn legacy_delivery_survives_upgrade_and_a_no_progress_run_link() {
7658        let (_dir, queue) = queue();
7659        let mut t = chat_task();
7660        t.start("old-run".into());
7661        t.hold_machine(Some("operator is considering recovery".into()));
7662        t.chat_notice = Some(ChatNotice {
7663            key: format!("held#{}", t.held_at.unwrap()),
7664            at: Timestamp::now(),
7665            outcome: ChatNoticeOutcome::Posted,
7666        });
7667        let mut raw = serde_json::to_value(&t).unwrap();
7668        raw.as_object_mut().unwrap().remove("chat_notices");
7669        raw.as_object_mut().unwrap().remove("hold_notice_cause");
7670        std::fs::create_dir_all(queue.path_of(&t.id).parent().unwrap()).unwrap();
7671        std::fs::write(queue.path_of(&t.id), serde_json::to_string(&raw).unwrap()).unwrap();
7672        assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7673        queue
7674            .modify(&t.id, |task| {
7675                task.requeue();
7676                task.link_run("unprepared-run");
7677                task.startup_notice_cause("startup-source");
7678                task.fail("same unresolved preflight", 0);
7679                true
7680            })
7681            .unwrap();
7682        assert_eq!(queue.get(&t.id).unwrap().chat_notice_due(), None);
7683        queue
7684            .modify(&t.id, |task| {
7685                task.succeed(completion(task));
7686                true
7687            })
7688            .unwrap();
7689        assert!(
7690            queue
7691                .get(&t.id)
7692                .unwrap()
7693                .chat_notice_due()
7694                .unwrap()
7695                .starts_with("done:")
7696        );
7697    }
7698
7699    #[test]
7700    fn a_dependency_wait_does_not_change_when_released_and_blocked_again() {
7701        let mut t = chat_task();
7702        t.block(vec!["a".into(), "b".into()], Some("waiting".into()));
7703        let key = t.chat_notice_key().unwrap();
7704        t.chat_notices.push(key);
7705        t.release();
7706        t.block(
7707            vec!["b".into(), "a".into(), "a".into()],
7708            Some("still waiting on prerequisites".into()),
7709        );
7710        assert_eq!(t.chat_notice_due(), None);
7711        t.block(
7712            vec!["new-question".into()],
7713            Some("different decision".into()),
7714        );
7715        assert!(t.chat_notice_due().is_some());
7716    }
7717
7718    #[test]
7719    fn running_startup_failures_preserve_stage_and_report_distinct_blockers() {
7720        let mut t = chat_task();
7721        t.start("existing-run".into());
7722        t.fail("implementation failed", 1);
7723        let failed = t.chat_notice_key().unwrap();
7724        t.chat_notices.push(failed.clone());
7725        t.release_operator("test", None);
7726        t.start("existing-run".into());
7727        t.fail_startup("startup-source", "same unresolved recovery source", 1);
7728        assert_eq!(
7729            t.chat_notice_due(),
7730            None,
7731            "no-progress recovery stays quiet"
7732        );
7733        t.release_operator("test", None);
7734        t.start("existing-run".into());
7735        t.fail_startup("startup-attachments", "attachment missing", 1);
7736        let attachments = t.chat_notice_due().expect("new attachment blocker");
7737        assert_ne!(attachments, failed);
7738        assert_eq!(
7739            t.hold_notice_cause.as_ref().unwrap().stage,
7740            "startup-attachments"
7741        );
7742        t.chat_notices.push(attachments);
7743        t.release_operator("test", None);
7744        t.start("existing-run".into());
7745        t.fail_startup(
7746            "startup-attachments",
7747            "same missing attachment, reworded",
7748            1,
7749        );
7750        assert_eq!(
7751            t.chat_notice_due(),
7752            None,
7753            "same stage after attempt counter reset"
7754        );
7755        t.release_operator("test", None);
7756        t.start("existing-run".into());
7757        t.fail_startup("startup-config", "different preflight stage", 1);
7758        assert!(t.chat_notice_due().is_some());
7759        assert_eq!(
7760            t.hold_notice_cause.as_ref().unwrap().stage,
7761            "startup-config"
7762        );
7763    }
7764
7765    #[test]
7766    fn structured_causes_preserve_no_progress_retries_and_report_new_passes() {
7767        let mut t = chat_task();
7768        t.hold_machine(Some("startup source missing".into()));
7769        t.startup_notice_cause("startup-source");
7770        let first = t.chat_notice_key().unwrap();
7771        t.chat_notices.push(first.clone());
7772        t.release_operator("test", None);
7773        t.startup_notice_cause("startup-source");
7774        t.hold_machine(Some("same source cannot be read".into()));
7775        assert_eq!(t.chat_notice_due(), None);
7776        t.startup_notice_cause("startup-config");
7777        assert!(t.chat_notice_due().is_some(), "different startup stage");
7778        t.notice_cause("failed", Some("existing-run"), Some(0));
7779        let run_failure = t.chat_notice_key().unwrap();
7780        t.chat_notices.push(run_failure.clone());
7781        t.release_operator("test", None);
7782        t.startup_notice_cause("startup-source");
7783        t.hold_machine(Some("no new work happened".into()));
7784        assert_eq!(t.chat_notice_due(), None);
7785        t.notice_cause("failed", Some("existing-run"), Some(1));
7786        assert!(t.chat_notice_due().is_some(), "a real resumed pass failed");
7787        assert_ne!(t.chat_notice_key().unwrap(), run_failure);
7788    }
7789
7790    #[test]
7791    fn legacy_hold_baseline_does_not_replay_or_hide_new_failures_and_completion() {
7792        let mut t = chat_task();
7793        t.hold_machine(Some("still waiting".into()));
7794        t.chat_notice = Some(ChatNotice {
7795            key: "held#2026-10-14T00:00:00Z".into(),
7796            at: Timestamp::now(),
7797            outcome: ChatNoticeOutcome::Posted,
7798        });
7799        assert_eq!(t.chat_notice_due(), None, "old hold baseline");
7800        t.import_chat_notice();
7801        t.notice_cause("failed", Some("new-run"), Some(0));
7802        assert!(t.chat_notice_due().is_some(), "new producer evidence");
7803        t.succeed(completion(&t));
7804        assert!(t.chat_notice_due().unwrap().starts_with("done:"));
7805    }
7806
7807    #[test]
7808    fn a_chat_notice_is_due_only_for_a_final_state_and_only_once() {
7809        let mut t = chat_task();
7810        assert_eq!(t.chat_notice_due(), None, "queued");
7811        t.start("r1".to_owned());
7812        assert_eq!(t.chat_notice_due(), None, "running");
7813        t.fail("boom", 3);
7814        assert_eq!(t.status, TaskStatus::Failed);
7815        assert_eq!(t.chat_notice_due(), None, "a retried failure is not final");
7816        t.start("r2".to_owned());
7817        t.park("upgrade");
7818        assert_eq!(t.chat_notice_due(), None, "parked");
7819        t.fail("boom", 1);
7820        assert_eq!(t.status, TaskStatus::Held);
7821        let key = t
7822            .chat_notice_due()
7823            .expect("held on the last attempt is final");
7824        t.chat_notice = Some(ChatNotice {
7825            key,
7826            at: Timestamp::now(),
7827            outcome: ChatNoticeOutcome::Posted,
7828        });
7829        assert_eq!(t.chat_notice_due(), None, "same hold, no second notice");
7830        t.release();
7831        assert_eq!(t.chat_notice_due(), None, "requeued after a release");
7832        t.start("r3".to_owned());
7833        t.succeed(completion(&t));
7834        assert!(t.chat_notice_due().is_some(), "done is a new final state");
7835    }
7836
7837    #[test]
7838    fn legacy_completion_receipts_do_not_suppress_new_occurrences() {
7839        for key in ["done", "done#0", "done#1", "done#12"] {
7840            let mut t = chat_task();
7841            t.status = TaskStatus::Done;
7842            t.chat_notice = Some(ChatNotice {
7843                key: key.to_owned(),
7844                at: Timestamp::now(),
7845                outcome: ChatNoticeOutcome::Posted,
7846            });
7847            assert_eq!(t.chat_notice_key().as_deref(), Some("done"));
7848            assert_eq!(t.chat_notice_due(), None, "legacy recorded key: {key}");
7849            let mut context = completion(&t);
7850            context.reason = Some("inspect again".into());
7851            t.reopen(context).unwrap();
7852            t.start("r2".to_owned());
7853            t.succeed(completion(&t));
7854            assert!(t.chat_notice_key().unwrap().starts_with("done:"));
7855            assert!(
7856                t.chat_notice_due().is_some(),
7857                "new occurrence, old receipt: {key}"
7858            );
7859        }
7860    }
7861
7862    #[test]
7863    fn a_release_without_progress_keeps_the_unresolved_notice_cause() {
7864        let mut t = chat_task();
7865        t.hold_manual(Some("wait".to_owned()));
7866        let first = t.chat_notice_due().expect("held");
7867        t.chat_notice = Some(ChatNotice {
7868            key: first.clone(),
7869            at: Timestamp::now(),
7870            outcome: ChatNoticeOutcome::Posted,
7871        });
7872        t.hold_manual(Some("still waiting".to_owned()));
7873        assert_eq!(t.chat_notice_due(), None, "a re-hold keeps its start");
7874        t.release();
7875        std::thread::sleep(std::time::Duration::from_millis(5));
7876        t.hold_manual(None);
7877        assert_eq!(t.chat_notice_due(), None, "no progress, same cause");
7878    }
7879
7880    #[test]
7881    fn a_chat_notice_needs_a_chat_source_and_a_current_schema() {
7882        let mut human = task("h");
7883        human.succeed(completion(&human));
7884        assert_eq!(human.chat_notice_due(), None);
7885        // A follow-up only inherits the chat; it did not file the task.
7886        let mut inherited = task("i");
7887        inherited.origin_chat = Some("20260902-000000-beef".to_owned());
7888        inherited.succeed(completion(&inherited));
7889        assert_eq!(inherited.chat_notice_due(), None);
7890        let mut old = chat_task();
7891        old.schema = 12;
7892        old.status = TaskStatus::Done;
7893        assert_eq!(old.chat_notice_due(), None, "history is not replayed");
7894        let mut live = chat_task();
7895        live.schema = 12;
7896        live.start("r1".to_owned());
7897        live.succeed(completion(&live));
7898        assert!(live.chat_notice_due().is_some(), "started by this build");
7899        let mut held = chat_task();
7900        held.schema = 12;
7901        held.hold_machine(Some("config".to_owned()));
7902        assert!(held.chat_notice_due().is_some(), "held before any start");
7903    }
7904
7905    #[test]
7906    fn a_stale_snapshot_does_not_rewind_a_recorded_chat_notice() {
7907        let tmp = tempfile::tempdir().expect("tempdir");
7908        let q = Queue::at(tmp.path().join("queue"));
7909        let mut t = chat_task();
7910        t.succeed(completion(&t));
7911        q.put(&mut t).expect("put");
7912        let mut stale = q.get(&t.id).expect("get");
7913        let key = t.chat_notice_due().expect("due");
7914        q.modify(&t.id, |x| {
7915            x.chat_notice = Some(ChatNotice {
7916                key: key.clone(),
7917                at: Timestamp::now(),
7918                outcome: ChatNoticeOutcome::Posted,
7919            });
7920            true
7921        })
7922        .expect("modify");
7923        q.put(&mut stale).expect("stale put");
7924        assert_eq!(q.get(&t.id).expect("get").chat_notice_due(), None);
7925    }
7926
7927    #[test]
7928    fn empty_sources_are_omitted_so_older_builds_still_read_the_task() {
7929        // `Task` rejects unknown fields, so a build without `sources` cannot
7930        // read a record that carries the key, even an empty one.
7931        let mut t = task("plain");
7932        let value = serde_json::to_value(&t).unwrap();
7933        assert!(value.get("sources").is_none(), "{value}");
7934        t.sources.pick_commits.push(crate::refs::Input {
7935            token: "abc1234".into(),
7936            sha: "a".repeat(40),
7937            provenance: crate::refs::Provenance::ExplicitCli,
7938        });
7939        let value = serde_json::to_value(&t).unwrap();
7940        assert_eq!(value["sources"]["pick_commits"][0]["sha"], "a".repeat(40));
7941        let restored: Task = serde_json::from_value(value).unwrap();
7942        assert_eq!(restored.sources, t.sources);
7943    }
7944
7945    /// A queue whose id source yields `ids` in order, then fresh ones.
7946    fn queue_with_ids(dir: &Path, ids: &[&str]) -> Queue {
7947        let ids: Vec<String> = ids.iter().map(|s| (*s).to_owned()).collect();
7948        let n = std::sync::atomic::AtomicUsize::new(0);
7949        Queue::at(dir.join("queue")).with_id_source(move || {
7950            let i = n.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
7951            ids.get(i)
7952                .cloned()
7953                .unwrap_or_else(|| format!("20260101-000000-f{i:03x}"))
7954        })
7955    }
7956
7957    const TAKEN: &str = "20260101-000000-aaaa";
7958
7959    #[test]
7960    fn a_new_task_never_merges_into_a_record_with_its_candidate_id() {
7961        let dir = tempfile::tempdir().unwrap();
7962        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
7963        let mut first = task("first");
7964        first.start("run-1".into());
7965        first.succeed(completion(&first));
7966        q.put(&mut first).unwrap();
7967        assert_eq!(first.id, TAKEN);
7968        let stored_before = q.get(&first.id).unwrap();
7969        assert!(!stored_before.runs.is_empty());
7970
7971        let mut second = task("second");
7972        q.put(&mut second).unwrap();
7973
7974        assert_ne!(second.id, first.id);
7975        assert!(second.runs.is_empty());
7976        assert!(second.passes.is_empty());
7977        assert!(second.chat_notices.is_empty());
7978        assert!(second.chat_notice.is_none());
7979        assert_eq!(second.chat_notice_due(), task("fresh").chat_notice_due());
7980        let a = q.get(&first.id).unwrap();
7981        let b = q.get(&second.id).unwrap();
7982        assert_eq!(a.title, "first");
7983        assert_eq!(a.runs, stored_before.runs);
7984        assert_eq!(a.passes, stored_before.passes);
7985        assert_eq!(a.chat_notices, stored_before.chat_notices);
7986        assert_eq!(a.chat_notice, stored_before.chat_notice);
7987        assert_eq!(a.chat_notice_due(), stored_before.chat_notice_due());
7988        assert_eq!(b.title, "second");
7989        assert!(b.runs.is_empty());
7990        assert!(b.passes.is_empty());
7991        assert!(b.chat_notice.is_none());
7992
7993        // A later save is an update: it still merges.
7994        let mut again = q.get(&second.id).unwrap();
7995        again.title = "second, edited".into();
7996        q.put(&mut again).unwrap();
7997        assert_eq!(q.get(&second.id).unwrap().title, "second, edited");
7998        assert_eq!(q.list().len(), 2);
7999    }
8000
8001    #[test]
8002    fn a_new_task_skips_an_id_with_an_orphaned_claim_or_attachments() {
8003        let dir = tempfile::tempdir().unwrap();
8004        let q = queue_with_ids(dir.path(), &["orphan-lock", "orphan-dir", "free"]);
8005        std::fs::create_dir_all(q.root()).unwrap();
8006        std::fs::write(q.root().join("orphan-lock.lock"), "x").unwrap();
8007        std::fs::create_dir_all(q.attachments_dir("orphan-dir")).unwrap();
8008        let mut t = task("t");
8009        q.put(&mut t).unwrap();
8010        assert_eq!(t.id, "free");
8011    }
8012
8013    #[test]
8014    fn a_claimed_new_task_holds_the_claim_on_the_reserved_id() {
8015        let dir = tempfile::tempdir().unwrap();
8016        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8017        let mut first = task("first");
8018        q.put(&mut first).unwrap();
8019        let mut second = task("second");
8020        let claim = q.file_claimed(&mut second).unwrap();
8021        assert_ne!(second.id, first.id);
8022        assert!(q.claim(&second.id).is_err());
8023        assert!(q.claim(&first.id).is_ok(), "the first task was not claimed");
8024        drop(claim);
8025    }
8026
8027    #[test]
8028    fn an_attached_new_task_skips_a_taken_id() {
8029        let dir = tempfile::tempdir().unwrap();
8030        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8031        let mut first = task("first");
8032        q.put(&mut first).unwrap();
8033        let src = source_file(dir.path(), "shot.png", "x");
8034        let mut second = task("second");
8035        q.attach_and_put(&mut second, &[src]).unwrap();
8036        assert_ne!(second.id, first.id);
8037        assert!(!q.attachments_dir(&first.id).exists());
8038        assert_eq!(q.attachment_paths(&second).len(), 1);
8039        assert!(q.attachment_paths(&second)[0].is_file());
8040    }
8041
8042    #[test]
8043    fn attaching_before_putting_a_new_task_reserves_the_id() {
8044        let dir = tempfile::tempdir().unwrap();
8045        let q = queue_with_ids(dir.path(), &[TAKEN, TAKEN]);
8046        let mut first = task("first");
8047        q.put(&mut first).unwrap();
8048        let src = source_file(dir.path(), "shot.png", "x");
8049        let mut second = task("second");
8050        q.attach(&mut second, &[src]).unwrap();
8051        assert_ne!(second.id, first.id);
8052        assert!(q.attachments_dir(&second.id).is_dir());
8053        q.put(&mut second).unwrap();
8054        assert_eq!(q.get(&second.id).unwrap().attachments.len(), 1);
8055        assert_eq!(q.get(&first.id).unwrap().title, "first");
8056        assert!(q.get(&first.id).unwrap().attachments.is_empty());
8057    }
8058
8059    #[test]
8060    fn create_new_keeps_its_already_exists_meaning() {
8061        let dir = tempfile::tempdir().unwrap();
8062        let q = Queue::at(dir.path().join("queue"));
8063        let mut a = task("a");
8064        a.id = "fixed-id".into();
8065        assert!(q.create_new(&mut a).unwrap());
8066        let mut b = task("b");
8067        b.id = "fixed-id".into();
8068        assert!(!q.create_new(&mut b).unwrap());
8069        assert_eq!(q.get("fixed-id").unwrap().title, "a");
8070    }
8071
8072    #[test]
8073    fn filing_gives_up_when_no_id_is_ever_free() {
8074        let dir = tempfile::tempdir().unwrap();
8075        let q = Queue::at(dir.path().join("queue")).with_id_source(|| TAKEN.to_owned());
8076        let mut first = task("first");
8077        q.put(&mut first).unwrap();
8078        let mut second = task("second");
8079        assert!(q.put(&mut second).is_err());
8080        assert_eq!(q.get(&first.id).unwrap().title, "first");
8081    }
8082}