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