Skip to main content

magi/
queue.rs

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