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