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