Skip to main content

magi/
triage.rs

1//! Held-task triage: walking `held` tasks so a hold left by an accident does
2//! not sit unread forever next to one a human placed on purpose.
3//!
4//! [`crate::queue::HoldSource`] already distinguishes "the daemon or
5//! conductor held this during its own recovery" ([`HoldSource::Machine`],
6//! documented as recoverable) from "an operator held this on purpose"
7//! ([`HoldSource::Manual`]). What was missing was anything that actually acts
8//! on that distinction: nothing walked the held list and asked whether a
9//! machine hold's cause was still true, and a record written before
10//! `hold_source` existed (schema < 3, `None`) was silently protected forever
11//! by [`Task::operator_held`]'s conservative default - never wrong, but also
12//! never looked at again by anything.
13//!
14//! [`run_once`] is that walk. For every `held` task it finds:
15//!
16//! - [`HoldSource::Machine`]: if [`machine_cause_resolved`] can tell the
17//!   cause is gone, the task goes straight back to `queued` - the same effect
18//!   as `magi task release`, just automatic. When it cannot tell, a
19//!   [`Question`] is filed once and the task stays held until answered.
20//! - `None` (a legacy record, or a hold nobody explained): always a question,
21//!   exactly once - the whole point being that "protected forever" must not
22//!   mean "never shown to anyone" either.
23//! - [`HoldSource::Manual`]: never touched automatically. Only once the hold
24//!   has sat untouched past [`MANUAL_STALE_AFTER`] does it earn a question of
25//!   its own, asking whether it is still wanted.
26//!
27//! Every question this module files carries [`NODE`] and uses the task id as
28//! [`Question::run`] - the same convention `crate::conduct`'s own questions
29//! use for a task rather than a run (see `conduct::apply_one`'s own comment
30//! on why the dedupe check there also filters on `node`, not `run` alone: an
31//! ordinary graph question's `run` is a real run id, and a coincidental
32//! equality with some task's id must not be read as "about this task").
33//! [`latest_triage_question`] follows the identical rule.
34//!
35//! # Why answers apply here rather than through `crate::queue::Task::block`
36//!
37//! `crate::conduct` blocks a task on its own question
38//! (`Task::block(vec![question_id], …)`), and `crate::daemon::resolve_blockers`
39//! unblocks it - unconditionally, back to `queued` - the moment that question
40//! is answered, whatever the answer actually said. That is correct for
41//! `conduct`: the *content* of the answer is meant for whoever reads
42//! `Task::answers` next, not for the resolver.
43//!
44//! A triage question's answer is different: "not yet" and "discard it" do two
45//! entirely different, non-resuming things, and only "resume it" may put the
46//! task back in line. Reusing the generic blocked/unblock path would resume
47//! every answer alike, so this module never calls [`Task::block`] and never
48//! leaves a triaged task anything but `held` while its question is open.
49//! [`interpret_answer`] reads [`Question::resolution`] itself and
50//! [`run_once`] acts on it directly: [`Task::release`] for an actual "resume
51//! it" choice, [`Queue::remove`] for "discard it" (捨ててよい really means
52//! "you may throw this away", not "leave it sitting held" - the English
53//! wording must say the same thing, not "leave it held"), and
54//! [`Task::hold_manual`] for anything else - which both keeps the task held
55//! and reclassifies it as a hold an operator has now actually seen, one
56//! `crate::conduct` and a later triage pass leave alone.
57//!
58//! The choice is read by its **position** in [`Question::choices`]
59//! ([`Wording::choices3`]/[`Wording::choices2`] always put "resume" first and
60//! "discard" third), never by comparing the answer text against [`Wording`]'s
61//! own strings picked from whatever config is in force *now* - the language a
62//! question was filed in and the language a later `run_once` call happens to
63//! read back are not guaranteed to be the same call's [`Config`], and a text
64//! comparison would silently misread a real "resume" answer as "keep held"
65//! the moment they disagree.
66//!
67//! # Idempotency
68//!
69//! [`run_once`] runs on every daemon idle tick (see `crate::daemon::poll`)
70//! and on every `magi task triage`, so an answered question must be applied to
71//! a task **at most once**, and a *fresh* question for the same task (once it
72//! is held again, or goes stale) must still be possible. The record is
73//! [`Task::triage_applied`], the question ids already applied. It cannot live
74//! in [`Task::hold_reason`]: [`Task::release`] clears that, so a "resume"
75//! answer left no trace, and a released task that failed back to `held` was
76//! released again by the same old answer with its attempts reset - forever.
77//! A task that comes back to `held` after an applied answer is therefore a
78//! new hold, handled per [`HoldSource`] (a fresh question for a machine hold).
79//! [`already_applied`] also still reads the `[triage:<short>]` marker
80//! [`keep_held_note`] appends to the hold reason, for records that pre-date
81//! the field.
82
83use std::path::{Path, PathBuf};
84use std::time::Duration;
85
86use jiff::Timestamp;
87
88use crate::ask::{Question, QuestionStatus, Questions};
89use crate::config::Config;
90use crate::disk;
91use crate::queue::{HoldSource, OperatorResume, Queue, Task, TaskStatus};
92
93/// Node recorded on every question this module files - `crate::conduct::NODE`
94/// for the same idea applied to a `crate::conduct` decision instead.
95pub const NODE: &str = "triage";
96
97/// Node on the question filed about a stuck dependency root - see
98/// [`ask_about_stuck_roots`]. Separate from [`NODE`] because the choices mean
99/// something else (position 2 is "detach the dependants", not "discard").
100pub const DEPS_NODE: &str = "triage-deps";
101
102/// Seat name on a filed question. Not a real agent seat - there is no model
103/// call anywhere in this module - but every [`Question`] needs one, and every
104/// other deterministic filer (`crate::land`'s merge approval) names itself
105/// the same way.
106const SEAT: &str = "triage";
107
108/// How long a [`HoldSource::Manual`] hold sits untouched before triage asks
109/// whether it is still wanted.
110///
111/// A judgement call, not a `magi.toml` setting - the same reasoning
112/// `ask::REPLY_QUIET_WINDOW` documents for itself: there is no operator
113/// preference for "how long is too long to ignore my own hold" that a
114/// per-repository config could be *right* about. Seven days is long enough
115/// that an ordinary multi-day hold (waiting on a dependency, waiting on the
116/// operator's own schedule) never gets nagged, and short enough that a hold
117/// nobody has looked at in a week surfaces again rather than aging into the
118/// kind of silent backlog this feature exists to prevent.
119const MANUAL_STALE_AFTER: Duration = Duration::from_secs(7 * 24 * 60 * 60);
120
121/// Localised strings for a filed question, the same idea as `crate::land`'s
122/// own `Words`/`words()` - only the languages magi can actually check are
123/// translated, and anything else falls back to English.
124struct Wording {
125    lang: &'static str,
126    resume: &'static str,
127    wait: &'static str,
128    discard: &'static str,
129    resume_now: &'static str,
130    keep_held: &'static str,
131}
132
133const EN: Wording = Wording {
134    lang: "en",
135    resume: "resume it",
136    wait: "not yet",
137    discard: "discard it",
138    resume_now: "resume it",
139    keep_held: "keep it held",
140};
141
142const JA: Wording = Wording {
143    lang: "ja",
144    resume: "再開してよい",
145    wait: "まだ待って",
146    discard: "捨ててよい",
147    resume_now: "再開する",
148    keep_held: "まだ止めておく",
149};
150
151/// Pick the wording. Codes and names both, the same acceptance
152/// `crate::land::words` gives `[graph] language`.
153fn wording(language: &str) -> &'static Wording {
154    if crate::lang::is_japanese(language) {
155        &JA
156    } else {
157        &EN
158    }
159}
160
161impl Wording {
162    fn choices3(&self) -> Vec<String> {
163        vec![
164            self.resume.to_owned(),
165            self.wait.to_owned(),
166            self.discard.to_owned(),
167        ]
168    }
169
170    fn choices2(&self) -> Vec<String> {
171        vec![self.resume_now.to_owned(), self.keep_held.to_owned()]
172    }
173
174    fn source_label(&self, source: Option<HoldSource>) -> &'static str {
175        match (self.lang, source) {
176            ("ja", Some(HoldSource::Machine)) => "machine(機械による自動保留)",
177            ("ja", Some(HoldSource::Manual)) => "manual(操作者による手動保留)",
178            ("ja", None) => "unknown(schema 3 未満の旧レコード、または理由未記録)",
179            (_, Some(HoldSource::Machine)) => "machine (automatic recovery hold)",
180            (_, Some(HoldSource::Manual)) => "manual (an operator held this)",
181            (_, None) => "unknown (pre-schema-3 record, or never recorded)",
182        }
183    }
184
185    /// The body under the summary: everything an operator needs to judge this
186    /// without opening a terminal - id, title, hold reason, hold source.
187    ///
188    /// Falls back to [`Task::last_error`] when [`Task::hold_reason`] is empty:
189    /// a record written before `Task::fail`/`Task::handed_off` started
190    /// copying `why` into `hold_reason` too, or one written by a still older
191    /// build, would otherwise leave the question blank for exactly the case
192    /// requirement 4 exists for.
193    fn detail(&self, task: &Task, why: &str) -> String {
194        let none = if self.lang == "ja" {
195            "(記録なし)"
196        } else {
197            "(none recorded)"
198        };
199        let reason = task
200            .hold_reason
201            .as_deref()
202            .or(task.last_error.as_deref())
203            .unwrap_or(none);
204        format!(
205            "task: {} ({})\ntitle: {}\nhold source: {}\nhold reason: {reason}\n\n{why}",
206            task.id,
207            task.short(),
208            task.title,
209            self.source_label(task.hold_source),
210        )
211    }
212
213    fn summary_machine_unknown(&self, task: &Task) -> String {
214        if self.lang == "ja" {
215            format!("保留タスク {} の再開可否を判断してください", task.short())
216        } else {
217            format!("decide whether to resume held task {}", task.short())
218        }
219    }
220
221    fn why_machine(&self) -> &'static str {
222        if self.lang == "ja" {
223            "機械的な保留(machine hold)ですが、原因がすでに解消しているかを自動では判断できませんでした。"
224        } else {
225            "This is a machine hold, but whether its cause has resolved could not be \
226             checked automatically."
227        }
228    }
229
230    fn summary_conductor_override(&self, task: &Task) -> String {
231        if self.lang == "ja" {
232            format!(
233                "再開と回答済みのタスク {} を conductor が再び保留しました",
234                task.short()
235            )
236        } else {
237            format!(
238                "task {} was resumed at your word, but the conductor held it again",
239                task.short()
240            )
241        }
242    }
243
244    fn why_conductor_override(&self, o: &OperatorResume) -> String {
245        let reason = o.conductor_rehold.as_deref().unwrap_or_default();
246        if self.lang == "ja" {
247            format!(
248                "{} に再開と回答済みですが、conductor が再び hold しました。conductor の理由: \
249                 {reason}\n\n強制再キューを選ぶと、以後 conductor はこのタスクを hold できません。",
250                o.at
251            )
252        } else {
253            format!(
254                "You answered \"resume\" at {}, but the conductor held the task again. \
255                 Its reason: {reason}\n\nForcing a requeue stops the conductor from \
256                 holding this task again.",
257                o.at
258            )
259        }
260    }
261
262    /// Positions match [`AnswerAction`]: 0 resume, 1 keep held, 2 discard.
263    fn choices_conductor_override(&self) -> Vec<String> {
264        if self.lang == "ja" {
265            vec![
266                "強制再キュー(conductor は再 hold 不可)".to_owned(),
267                "手動 hold のまま".to_owned(),
268                "捨ててよい".to_owned(),
269            ]
270        } else {
271            vec![
272                "force requeue (conductor must not hold again)".to_owned(),
273                "keep held (manual)".to_owned(),
274                "discard".to_owned(),
275            ]
276        }
277    }
278
279    fn summary_legacy(&self, task: &Task) -> String {
280        if self.lang == "ja" {
281            format!(
282                "hold_source が不明な保留タスク {} を確認してください",
283                task.short()
284            )
285        } else {
286            format!(
287                "held task {} has no recorded hold source - please take a look",
288                task.short()
289            )
290        }
291    }
292
293    fn why_legacy(&self) -> &'static str {
294        if self.lang == "ja" {
295            "hold_source が記録されていません。schema 3 より前のレコードか、理由が記録されなかった \
296             holdです。人が意図して止めたのか、クラッシュや強制再起動で宙に浮いただけなのか、\
297             このデータからは区別できません。"
298        } else {
299            "No hold_source was recorded - either a pre-schema-3 record, or a hold whose \
300             reason was never written down. Whether this was a deliberate hold or the \
301             leftover of a crash cannot be told from the data alone."
302        }
303    }
304
305    fn summary_manual_stale(&self, task: &Task, days: i64) -> String {
306        if self.lang == "ja" {
307            format!(
308                "{days}日間 保留されたままの手動保留タスク {} を確認してください",
309                task.short()
310            )
311        } else {
312            format!(
313                "held task {} has been on a manual hold for {days} day(s)",
314                task.short()
315            )
316        }
317    }
318
319    fn why_manual(&self) -> &'static str {
320        if self.lang == "ja" {
321            "操作者が明示的に止めた保留ですが、長期間そのままになっています。まだ止めておくか、\
322             再開するか教えてください。"
323        } else {
324            "An operator held this on purpose, but it has sat untouched for a while. Say \
325             whether to keep holding it or resume it."
326        }
327    }
328}
329
330/// Which of the three situations this module recognises a held task is in.
331#[derive(Debug, Clone, Copy, PartialEq, Eq)]
332enum Bucket {
333    /// `HoldSource::Machine`, cause not verifiably resolved.
334    MachineUnknown,
335    /// `HoldSource::Machine`, held by the conductor after the operator
336    /// answered "resume" (see [`Task::resume_override`]).
337    ConductorOverride,
338    /// `hold_source` is `None`.
339    Legacy,
340    /// `HoldSource::Manual`, held past [`MANUAL_STALE_AFTER`].
341    ManualStale,
342}
343
344/// What one [`run_once`] pass did, task ids in each list.
345#[derive(Debug, Clone, Default)]
346pub struct Report {
347    /// A `HoldSource::Machine` hold whose cause was found resolved, put back
348    /// in line automatically.
349    pub resumed: Vec<String>,
350    /// A fresh question was filed this pass.
351    pub asked: Vec<String>,
352    /// An operator's answer to an earlier triage question was applied.
353    pub answered: Vec<String>,
354    /// A `blocked` task whose `blocked_by` named an id that no longer exists
355    /// was moved to a machine hold this pass - see
356    /// [`quarantine_orphaned_blocked`]. Distinct from `asked`: the question
357    /// about it, if any, is filed in the same pass and only counted there.
358    pub quarantined: Vec<String>,
359}
360
361impl Report {
362    /// Is there nothing to report? Callers use this to skip logging an empty
363    /// pass rather than repeating "triaged 0 held task(s)" on every idle tick.
364    pub fn is_empty(&self) -> bool {
365        self.resumed.is_empty()
366            && self.asked.is_empty()
367            && self.answered.is_empty()
368            && self.quarantined.is_empty()
369    }
370}
371
372/// The repository a task's config and disk check should read from. Mirrors
373/// `crate::conduct::repo_for`'s own fallback, duplicated rather than shared
374/// because that one is private to its module and the two are one `if` each.
375fn repo_for(task: &Task) -> PathBuf {
376    if task.repo.as_os_str().is_empty() {
377        PathBuf::from(".")
378    } else {
379        task.repo.clone()
380    }
381}
382
383/// Recognise a `HoldSource::Machine` hold caused by the free-space gate
384/// (`crate::disk::gate`'s message, or `daemon::disk_gate`'s "could not
385/// measure" fallback) from `hold_reason` text alone.
386///
387/// There is no field recording *why* a machine hold happened - `hold_machine`
388/// takes only a reason string - so this is the one signal available, and disk
389/// pressure is the one cause this module can safely re-measure without
390/// touching git, a run, or an agent CLI. Keep the two prefixes here in sync
391/// with `crate::disk::gate`'s formatted string and `daemon::disk_gate`'s own
392/// message if either changes; nothing else ties them together.
393fn is_disk_hold(task: &Task) -> bool {
394    task.hold_reason
395        .as_deref()
396        .is_some_and(crate::disk::is_gate_reason)
397}
398
399/// Has a `HoldSource::Machine` hold's cause resolved? `Some(true)` means yes -
400/// safe to requeue. `Some(false)` means the same cause was checked and is
401/// still in force. `None` means this hold's cause is not one this module
402/// knows how to re-check at all, and a human has to look.
403fn machine_cause_resolved(task: &Task, cfg: &Config) -> Option<bool> {
404    if task
405        .hold_reason
406        .as_deref()
407        .is_some_and(|r| r.starts_with(crate::cache::RESOURCE_HOLD))
408    {
409        // The shared build cache's lease: free again (or no cache at all)
410        // means the same run can resume.
411        return Some(
412            cfg.cache_dir()
413                .is_none_or(|dir| !crate::cache::in_use(&crate::run::home(), &dir)),
414        );
415    }
416    if !is_disk_hold(task) {
417        return None;
418    }
419    let min = cfg.disk.min_free_bytes;
420    if min == 0 {
421        // The operator turned the gate off since this hold was placed - its
422        // one possible cause is gone by construction, no measurement needed.
423        return Some(true);
424    }
425    let free = disk::free_bytes(&repo_for(task)).ok()?;
426    Some(disk::gate(free, min).is_none())
427}
428
429/// Is a `HoldSource::Manual` hold old enough to earn a "still wanted?"
430/// question? Same comparison `crate::clean::due` uses for a run's fold grace,
431/// against [`MANUAL_STALE_AFTER`] instead of a configured one.
432fn manual_is_stale(task: &Task, now: Timestamp) -> bool {
433    now.as_second() - task.updated_at.as_second() > MANUAL_STALE_AFTER.as_secs() as i64
434}
435
436/// The marker [`apply_answer`] writes into [`Task::hold_reason`] and
437/// [`already_applied`] reads back - see this module's own doc on why.
438fn marker_for(q: &Question) -> String {
439    format!("[triage:{}]", q.short())
440}
441
442/// Has `q`'s answer already been applied to `task`? See this module's doc.
443/// Checks [`Task::triage_applied`] first, which survives [`Task::release`].
444fn already_applied(task: &Task, q: &Question) -> bool {
445    if task.triage_applied(&q.id) {
446        return true;
447    }
448    // Records written before `Task::triage_applied` existed carry only the
449    // "keep held" marker in the hold reason.
450    let marker = marker_for(q);
451    task.hold_reason
452        .as_deref()
453        .is_some_and(|r| r.contains(marker.as_str()))
454}
455
456/// The most recent question this module filed for `task_id`, any status -
457/// open (still waiting), answered (may need applying), or abandoned (settled
458/// with nothing decided). Filters on both `node` and `run`, never `run`
459/// alone - see this module's doc on why a bare `run` match is not safe.
460fn latest_triage_question(questions: &Questions, task_id: &str) -> Option<Question> {
461    latest_question(questions, NODE, task_id)
462}
463
464/// [`latest_triage_question`] for any of this module's nodes.
465fn latest_question(questions: &Questions, node: &str, task_id: &str) -> Option<Question> {
466    questions
467        .list()
468        .into_iter()
469        .filter(|q| q.node == node && q.run == task_id)
470        // `asked_at` first: ids carry only whole seconds plus a random
471        // suffix, so two questions filed in the same second order randomly.
472        .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)))
473}
474
475/// What an answered triage question's choice means, independent of which
476/// language it was filed in.
477#[derive(Debug, Clone, Copy, PartialEq, Eq)]
478enum AnswerAction {
479    /// The first choice, always "resume it" / "再開してよい" / "再開する" -
480    /// see [`Wording::choices3`] and [`Wording::choices2`], whose first entry
481    /// is always the resume choice.
482    Resume,
483    /// The third choice, present only in [`Wording::choices3`]: "discard it"
484    /// / "捨ててよい".
485    Discard,
486    /// Anything else: the second choice ("not yet" / "keep it held"), or an
487    /// answer that does not match any offered choice at all (should not
488    /// happen for a multiple-choice question, but the safe default is to
489    /// keep holding rather than guess at "resume").
490    KeepHeld,
491}
492
493/// Read `q`'s answer as an [`AnswerAction`].
494///
495/// Matched by **position in `q.choices`**, never by comparing the answer text
496/// against [`Wording`]'s own strings: [`Wording`] is picked from the task's
497/// *current* repository config, which can differ from whatever language was
498/// in force when the question was filed (a `--config` override on one `magi
499/// task triage` call and not the next, or the repository's config edited in
500/// between). Comparing text would then silently misread an actual "resume"
501/// answer as "keep held" - the choices themselves are fixed at filing time,
502/// in [`file_question`], and never change afterwards, so their position is
503/// the one thing that stays true regardless of which language reads them
504/// back.
505fn interpret_answer(q: &Question) -> AnswerAction {
506    let resolution = q.resolution().unwrap_or_default();
507    match q.choices.iter().position(|c| *c == resolution) {
508        Some(0) => AnswerAction::Resume,
509        Some(2) => AnswerAction::Discard,
510        _ => AnswerAction::KeepHeld,
511    }
512}
513
514/// The note [`already_applied`] looks for, appended to (never replacing)
515/// whatever [`Task::hold_reason`] already said - the original cause is still
516/// worth reading in `magi task show` after the operator answers "not yet",
517/// and [`Task::hold_manual`] would otherwise overwrite it outright.
518fn keep_held_note(task: &Task, q: &Question, resolution: &str) -> String {
519    let marker = format!("{} operator: {resolution}", marker_for(q));
520    match task.hold_reason.as_deref() {
521        Some(existing) if !existing.is_empty() => format!("{existing}\n{marker}"),
522        _ => marker,
523    }
524}
525
526/// File a fresh triage question for `task` and return it. The caller is
527/// responsible for having already established there is no open one - see
528/// [`latest_triage_question`] - so this never checks again.
529fn file_question(
530    questions: &Questions,
531    task: &Task,
532    bucket: Bucket,
533    w: &Wording,
534    now: Timestamp,
535) -> Option<Question> {
536    let (summary, why, choices) = match bucket {
537        Bucket::MachineUnknown => (
538            w.summary_machine_unknown(task),
539            w.why_machine().to_owned(),
540            w.choices3(),
541        ),
542        Bucket::ConductorOverride => (
543            w.summary_conductor_override(task),
544            task.resume_override
545                .as_ref()
546                .map(|o| w.why_conductor_override(o))
547                .unwrap_or_default(),
548            w.choices_conductor_override(),
549        ),
550        Bucket::Legacy => (
551            w.summary_legacy(task),
552            w.why_legacy().to_owned(),
553            w.choices3(),
554        ),
555        Bucket::ManualStale => {
556            let days = (now.as_second() - task.updated_at.as_second()) / (24 * 60 * 60);
557            (
558                w.summary_manual_stale(task, days),
559                w.why_manual().to_owned(),
560                w.choices2(),
561            )
562        }
563    };
564    let mut q = Question::new(
565        task.id.clone(),
566        NODE.to_owned(),
567        SEAT.to_owned(),
568        summary,
569        w.detail(task, &why),
570        choices,
571    );
572    q.triage_generation = Some(task.resumption.as_ref().map_or(0, |r| r.generation));
573    questions.put(&mut q).ok()?;
574    Some(q)
575}
576
577/// What a deputy is told about a triage question: the task, why it is held and
578/// what each position does, in the words [`interpret_answer`] /
579/// [`interpret_deps_answer`] apply them. Written from the stored record; a task
580/// that no longer exists is said to be missing, never reconstructed.
581pub(crate) fn deputy_brief(q: &Question, queue: &Queue) -> String {
582    let task = queue.get(&q.run).ok();
583    let mut s = match &task {
584        Some(t) => format!(
585            "Task {} (`magi task show {}`), \"{}\", is {}. Hold source: {}. Reason: {}.",
586            t.id,
587            t.id,
588            t.title,
589            t.status.as_str(),
590            match t.hold_source {
591                Some(HoldSource::Machine) => "machine (an automatic hold)",
592                Some(HoldSource::Manual) => "manual (an operator held it)",
593                None => "unknown (an old record, treated as the operator's)",
594            },
595            t.hold_reason
596                .as_deref()
597                .or(t.last_error.as_deref())
598                .unwrap_or("(none recorded)")
599        ),
600        None => format!("Task {} no longer exists (its record is gone).", q.run),
601    };
602    s.push_str("\n\nWhat each option does, by position (the owner taps a button; you only read their words):");
603    let n = q.choices.len();
604    for (i, c) in q.choices.iter().enumerate() {
605        let effect = if q.node == DEPS_NODE {
606            match i {
607                0 => "the dependency is released so the loop runs it",
608                1 => {
609                    "the dependants are detached and the dependency task is DELETED; this cannot be undone"
610                }
611                2 => "the dependants are detached; the dependency stays as it is",
612                _ => "nothing is applied",
613            }
614        } else {
615            match i {
616                0 => "the task is released and requeued",
617                2 if n > 2 => "the task is DELETED; this cannot be undone",
618                _ => "the task stays held, with the answer noted",
619            }
620        };
621        s.push_str(&format!("\n- `{c}`: {effect}"));
622    }
623    s.push_str(
624        "\n\nThe daemon applies the answer on its next pass; you apply nothing. \
625         `magi ask --settle` is refused while the task is held by the operator (a \
626         manual hold, or an old record): an answer must not release or delete \
627         something a person parked. In that case do not retry it - ask the owner \
628         with `--thread` to tap the button themselves. The destructive option is \
629         accepted only for an unhedged, verbatim instruction.",
630    );
631    s
632}
633
634/// Move every `blocked` task whose `blocked_by` names a task or question id
635/// that no longer exists to a machine hold, before the per-`held` walk
636/// [`run_once`] does gets a look at it.
637///
638/// `crate::daemon::resolve_blockers` already catches the same situation on
639/// every idle poll, and [`Queue::remove`] already catches it the moment a
640/// dependency is deleted through `magi task rm` - both call the same
641/// [`crate::queue::missing_blockers`]/[`crate::queue::missing_blocker_hold_reason`]
642/// this does. This third copy exists because a dependency can also be deleted
643/// by hand (the file just removed from disk, not through either of those
644/// paths), and because a queue can carry a `blocked` task with a
645/// long-since-deleted dependency from *before* either catch above ever
646/// existed - and such a task is `blocked`, never `held`, so it is invisible
647/// to the rest of this module without this pass. Running it here, first, is
648/// also what makes `magi task triage` alone - with no daemon running at all -
649/// enough to fix one: the task lands `held` in this same call, and the
650/// ordinary loop below files its question in the very same pass.
651fn quarantine_orphaned_blocked(queue: &Queue, questions: &Questions) -> Vec<String> {
652    let mut quarantined = Vec::new();
653    for listed in queue.list() {
654        if listed.status != TaskStatus::Blocked || listed.blocked_by.is_empty() {
655            continue;
656        }
657        let Ok(_claim) = queue.claim(&listed.id) else {
658            continue;
659        };
660        let Ok(mut task) = queue.get(&listed.id) else {
661            continue;
662        };
663        if task.status != TaskStatus::Blocked {
664            continue;
665        }
666        let deleted = queue.apply_deleted_blockers(&mut task);
667        if !deleted.is_empty() && queue.put(&mut task).is_ok() {
668            for id in &deleted {
669                queue.note_dependency_deleted(&task, id);
670            }
671        }
672        if task.status != TaskStatus::Blocked {
673            continue;
674        }
675        let missing = crate::queue::missing_blockers(queue, questions, &task.blocked_by);
676        if missing.is_empty() {
677            continue;
678        }
679        let language = crate::lang::of_repo(&repo_for(&task));
680        task.hold_machine(Some(crate::queue::missing_blocker_hold_reason_in(
681            &task.blocked_by,
682            &missing,
683            &language,
684        )));
685        if queue.put(&mut task).is_ok() {
686            quarantined.push(task.id.clone());
687        }
688    }
689    quarantined
690}
691
692/// Choices of a [`DEPS_NODE`] question, by position: release the root, discard
693/// it, or detach the dependants from it.
694#[derive(Debug, Clone, Copy, PartialEq, Eq)]
695enum DepsAction {
696    Release,
697    Discard,
698    Detach,
699    /// An answer that matches no offered choice: nothing is changed.
700    Nothing,
701}
702
703fn interpret_deps_answer(q: &Question) -> DepsAction {
704    let resolution = q.resolution().unwrap_or_default();
705    match q.choices.iter().position(|c| *c == resolution) {
706        Some(0) => DepsAction::Release,
707        Some(1) => DepsAction::Discard,
708        Some(2) => DepsAction::Detach,
709        _ => DepsAction::Nothing,
710    }
711}
712
713/// Summary, body and choices of the question about one stuck root.
714fn deps_texts(w: &Wording, root: &Task, dependants: &[&Task]) -> (String, String, Vec<String>) {
715    let ja = w.lang == "ja";
716    let reason = root
717        .hold_reason
718        .as_deref()
719        .or(root.last_error.as_deref())
720        .unwrap_or(if ja {
721            "(記録なし)"
722        } else {
723            "(none recorded)"
724        });
725    let list: String = dependants
726        .iter()
727        .map(|t| format!("- {} {}\n", t.short(), t.title))
728        .collect();
729    if ja {
730        (
731            format!(
732                "{} ({}) が {} 件のタスクを止めています",
733                root.short(),
734                root.status.as_str(),
735                dependants.len()
736            ),
737            format!(
738                "task: {} ({})\ntitle: {}\n状態: {}\n理由: {reason}\n\n\
739                 このタスクは自動では実行されないため、依存している次のタスクは永遠に待ち続けます:\n{list}",
740                root.id,
741                root.short(),
742                root.title,
743                root.status.as_str()
744            ),
745            vec![
746                "依存先を再開する".to_owned(),
747                "依存先を捨てる(依存タスクは切り離して実行)".to_owned(),
748                "依存タスクを切り離す(依存先はそのまま)".to_owned(),
749            ],
750        )
751    } else {
752        (
753            format!(
754                "{} ({}) is freezing {} blocked task(s)",
755                root.short(),
756                root.status.as_str(),
757                dependants.len()
758            ),
759            format!(
760                "task: {} ({})\ntitle: {}\nstatus: {}\nreason: {reason}\n\n\
761                 Nothing in the loop will ever run this task, so these dependants wait \
762                 forever:\n{list}",
763                root.id,
764                root.short(),
765                root.title,
766                root.status.as_str()
767            ),
768            vec![
769                "release the dependency".to_owned(),
770                "discard the dependency (dependants are detached and run)".to_owned(),
771                "detach the dependants (the dependency stays as it is)".to_owned(),
772            ],
773        )
774    }
775}
776
777/// Detach every `blocked` task that names `root` directly: drop that one id
778/// from its `blocked_by` (`Task::unblock`), so a dependant with another
779/// unresolved blocker keeps waiting on it. Idempotent.
780fn detach_dependants(queue: &Queue, root: &str) {
781    for listed in queue.list() {
782        if listed.status != TaskStatus::Blocked || !listed.blocked_by.iter().any(|b| b == root) {
783            continue;
784        }
785        let Ok(_claim) = queue.claim(&listed.id) else {
786            continue;
787        };
788        let Ok(mut t) = queue.get(&listed.id) else {
789            continue;
790        };
791        if t.status != TaskStatus::Blocked {
792            continue;
793        }
794        t.unblock(root);
795        let _ = queue.put(&mut t);
796    }
797}
798
799/// Apply an answered [`DEPS_NODE`] question. Every step is idempotent, so a
800/// pass that dies half way is finished by the next one. Returns whether the
801/// answer was consumed.
802fn apply_deps_answer(queue: &Queue, questions: &Questions, q: &Question, now: Timestamp) -> bool {
803    let Ok(_claim) = queue.claim(&q.run) else {
804        return false;
805    };
806    let Ok(mut root) = queue.get(&q.run) else {
807        return false;
808    };
809    if root.triage_applied(&q.id) {
810        return false;
811    }
812    if root.operator_decided_at.is_some_and(|at| at > q.asked_at)
813        || q.triage_generation
814            .is_some_and(|g| g != root.resumption.as_ref().map_or(0, |r| r.generation))
815    {
816        root.mark_triage_applied(&q.id);
817        return queue.put(&mut root).is_ok();
818    }
819    match interpret_deps_answer(q) {
820        DepsAction::Release => {
821            if root.status == TaskStatus::Running {
822                return false;
823            }
824            root.answers.push(crate::queue::AnsweredQuestion {
825                question: q.summary.clone(),
826                answer: q.resolution().unwrap_or_default(),
827            });
828            root.release_operator("triage-dependencies", Some(&q.id));
829            root.resume_override = Some(OperatorResume {
830                question_id: q.id.clone(),
831                at: now,
832                conductor_rehold: None,
833                forced: false,
834                pinned_run: None,
835            });
836        }
837        DepsAction::Discard => {
838            detach_dependants(queue, &root.id);
839            return queue.remove(&root.id, false, questions).is_ok();
840        }
841        DepsAction::Detach => detach_dependants(queue, &root.id),
842        // Matches no offered choice, so there is nothing to apply. Left unmarked:
843        // marking it applied would read as "settled", and the next stuck check
844        // would file an identical question at once. Unmarked, it stays an
845        // answered question awaiting application, which suppresses re-asking.
846        DepsAction::Nothing => return false,
847    }
848    root.mark_triage_applied(&q.id);
849    queue.put(&mut root).is_ok()
850}
851
852/// One question per stuck dependency root. Answers are applied by the
853/// pre-scheduling sweep. See [`crate::blockers`] for what "stuck" means.
854///
855/// Not re-asked: a root with an open or answered-unapplied question; one whose
856/// own hold question ([`NODE`]) is still pending; and one whose question was
857/// abandoned unless the root or a task it freezes changed since. An *applied*
858/// answer leaves nothing stuck (released, discarded, or detached), so a root
859/// that is stuck again is a new situation and is asked about afresh.
860fn ask_about_stuck_roots(
861    queue: &Queue,
862    questions: &Questions,
863    config_override: Option<&Path>,
864    report: &mut Report,
865) {
866    let all = questions.list();
867    let inv = crate::blockers::Inventory::new(queue.list(), &all);
868    let mut frozen: std::collections::BTreeMap<String, Vec<String>> = Default::default();
869    for (id, roots) in inv.stuck() {
870        for root in roots {
871            if root != id {
872                frozen.entry(root).or_default().push(id.clone());
873            }
874        }
875    }
876    // A cycle root freezes the others but may have no dependants of its own
877    // listed above when it is alone; a root with nothing to name is not asked.
878
879    for mut q in all
880        .iter()
881        .filter(|q| q.node == DEPS_NODE && q.status.open())
882        .cloned()
883    {
884        if !frozen.contains_key(&q.run) {
885            q.abandon("nothing waits on this task anymore");
886            let _ = questions.put(&mut q);
887        }
888    }
889
890    for (root_id, dependant_ids) in &frozen {
891        let Some(root) = inv.task(root_id) else {
892            continue;
893        };
894        let dependants: Vec<&Task> = dependant_ids.iter().filter_map(|d| inv.task(d)).collect();
895        let latest = all
896            .iter()
897            .filter(|q| q.node == DEPS_NODE && q.run == *root_id)
898            .max_by(|a, b| a.asked_at.cmp(&b.asked_at).then_with(|| a.id.cmp(&b.id)));
899        match latest {
900            Some(q) if q.status.open() => continue,
901            Some(q) if q.status == QuestionStatus::Answered && !root.triage_applied(&q.id) => {
902                continue;
903            }
904            Some(q) if q.status == QuestionStatus::Abandoned => {
905                let changed = root.updated_at > q.asked_at
906                    || dependants.iter().any(|t| t.updated_at > q.asked_at);
907                if !changed {
908                    continue;
909                }
910            }
911            _ => {}
912        }
913        if pending_for(questions, root) {
914            continue;
915        }
916        let cfg = Config::discover(&repo_for(root), config_override)
917            .ok()
918            .map(|(c, _)| c);
919        let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
920        let (summary, detail, choices) = deps_texts(w, root, &dependants);
921        let mut question = Question::new(
922            root.id.clone(),
923            DEPS_NODE.to_owned(),
924            SEAT.to_owned(),
925            summary,
926            detail,
927            choices,
928        );
929        question.triage_generation = Some(root.resumption.as_ref().map_or(0, |r| r.generation));
930        if questions.put(&mut question).is_ok() {
931            report.asked.push(root.id.clone());
932        }
933    }
934}
935
936/// Apply settled built-in answers before scheduling or conductor invocation.
937/// Kept separate from diagnosis so queued tasks can recover legacy answers too.
938pub fn apply_answers(queue: &Queue, questions: &Questions) -> Vec<String> {
939    let mut applied = Vec::new();
940    for q in questions.list() {
941        if q.node == DEPS_NODE
942            && q.status == QuestionStatus::Answered
943            && apply_deps_answer(queue, questions, &q, Timestamp::now())
944        {
945            applied.push(q.run.clone());
946        }
947    }
948    for listed in queue.list() {
949        let Some(q) = latest_triage_question(questions, &listed.id) else {
950            continue;
951        };
952        if q.status != QuestionStatus::Answered || already_applied(&listed, &q) {
953            continue;
954        }
955        let Ok(_claim) = queue.claim(&listed.id) else {
956            continue;
957        };
958        let Ok(mut task) = queue.get(&listed.id) else {
959            continue;
960        };
961        if already_applied(&task, &q)
962            || !matches!(task.status, TaskStatus::Held | TaskStatus::Queued)
963        {
964            continue;
965        }
966        let generation = task.resumption.as_ref().map_or(0, |r| r.generation);
967        let action = interpret_answer(&q);
968        let mut newer_decision = q.triage_generation.is_some_and(|g| g != generation)
969            || task.resumption.as_ref().is_some_and(|r| r.at > q.asked_at)
970            || task.held_at.is_some_and(|at| at > q.asked_at)
971            || task.operator_decided_at.is_some_and(|at| at > q.asked_at);
972        // A later explicit keep-held answer is itself a newer operator
973        // decision, even when the question predates the release. Resume and
974        // discard still require the question's original scope to match.
975        if matches!(action, AnswerAction::KeepHeld)
976            && q.answered_at.is_some_and(|at| {
977                task.operator_decided_at
978                    .is_none_or(|decision| at > decision)
979                    && task.resumption.as_ref().is_none_or(|r| at > r.at)
980            })
981        {
982            newer_decision = false;
983        }
984        // Audit the answer even when a later release or manual hold wins.
985        let resolution = q.resolution().unwrap_or_default();
986        task.answers.push(crate::queue::AnsweredQuestion {
987            question: q.summary.clone(),
988            answer: if newer_decision {
989                format!("{resolution} (superseded by a later operator decision)")
990            } else {
991                resolution
992            },
993        });
994        if !newer_decision {
995            match action {
996                AnswerAction::Resume => {
997                    task.release_operator("triage", Some(&q.id));
998                    task.resume_override = Some(OperatorResume {
999                        question_id: q.id.clone(),
1000                        at: Timestamp::now(),
1001                        conductor_rehold: None,
1002                        forced: true,
1003                        pinned_run: None,
1004                    });
1005                }
1006                AnswerAction::KeepHeld => {
1007                    let note = keep_held_note(&task, &q, &q.resolution().unwrap_or_default());
1008                    task.hold_manual(Some(note));
1009                }
1010                AnswerAction::Discard => {
1011                    if queue.remove(&task.id, false, questions).is_ok() {
1012                        applied.push(task.id);
1013                    }
1014                    continue;
1015                }
1016            }
1017        }
1018        task.mark_triage_applied(&q.id);
1019        if queue.put(&mut task).is_ok() {
1020            applied.push(task.id);
1021        }
1022    }
1023    applied
1024}
1025
1026/// Run one deterministic triage pass over every `held` task in `queue`. No
1027/// model call anywhere in this function - see this module's own doc for what
1028/// each `HoldSource` gets instead.
1029///
1030/// `config_override` is threaded straight to [`Config::discover`], the same
1031/// role `daemon::Opts::config` plays for `daemon::prepare` - an explicit
1032/// `--config` from the caller, or `None` to let each task's own repository
1033/// pick its layers.
1034///
1035/// Safe to call on every daemon idle tick and from `magi task triage` alike:
1036/// a task already answered and applied is left alone (see
1037/// [`already_applied`]), and a task with an open question is left alone too,
1038/// so repeated calls with nothing new to say do nothing.
1039///
1040/// Also runs [`quarantine_orphaned_blocked`], so a `blocked` task whose
1041/// dependency no longer exists is caught and turned into a fresh `held`
1042/// question in this same pass, not left for a later call to notice.
1043pub fn run_once(
1044    queue: &Queue,
1045    questions: &Questions,
1046    config_override: Option<&Path>,
1047    now: Timestamp,
1048) -> Report {
1049    let mut report = Report {
1050        answered: apply_answers(queue, questions),
1051        quarantined: quarantine_orphaned_blocked(queue, questions),
1052        ..Report::default()
1053    };
1054    ask_about_stuck_roots(queue, questions, config_override, &mut report);
1055    for listed in queue.list() {
1056        if listed.status != TaskStatus::Held {
1057            continue;
1058        }
1059        let Ok(_claim) = queue.claim(&listed.id) else {
1060            continue;
1061        };
1062        let Ok(mut task) = queue.get(&listed.id) else {
1063            continue;
1064        };
1065        // Re-read under the claim: a release or a re-hold landed by a human
1066        // between the listing above and the claim just taken must not be
1067        // clobbered by a decision based on the stale copy.
1068        if task.status != TaskStatus::Held {
1069            continue;
1070        }
1071        // A question about what this task freezes is already the one question
1072        // it owes the operator; a second, about the hold itself, would ask two
1073        // things at once.
1074        if deps_pending(questions, &task) {
1075            continue;
1076        }
1077
1078        let cfg = Config::discover(&repo_for(&task), config_override)
1079            .ok()
1080            .map(|(c, _)| c);
1081        let w = wording(cfg.as_ref().map_or("en", |c| c.graph.language.as_str()));
1082
1083        if let Some(q) = latest_triage_question(questions, &task.id) {
1084            if q.status.open() {
1085                // Already asked, still waiting - nothing to do this pass.
1086                continue;
1087            }
1088            // Abandoned, or an already-applied answer: fall through to the
1089            // ordinary per-source handling below, which is how a stale
1090            // `HoldSource::Manual` re-ask - or a fresh machine/legacy
1091            // question, once a prior one settled the task back into a hold -
1092            // gets filed.
1093        }
1094
1095        match task.hold_source {
1096            Some(HoldSource::Machine) => {
1097                let overridden = task
1098                    .resume_override
1099                    .as_ref()
1100                    .is_some_and(|o| o.conductor_rehold.is_some() && !o.forced);
1101                if overridden {
1102                    if file_question(questions, &task, Bucket::ConductorOverride, w, now).is_some()
1103                    {
1104                        report.asked.push(task.id.clone());
1105                    }
1106                } else if cfg.as_ref().and_then(|c| machine_cause_resolved(&task, c)) == Some(true)
1107                {
1108                    task.release();
1109                    if queue.put(&mut task).is_ok() {
1110                        report.resumed.push(task.id.clone());
1111                    }
1112                } else if file_question(questions, &task, Bucket::MachineUnknown, w, now).is_some()
1113                {
1114                    report.asked.push(task.id.clone());
1115                }
1116            }
1117            None => {
1118                if file_question(questions, &task, Bucket::Legacy, w, now).is_some() {
1119                    report.asked.push(task.id.clone());
1120                }
1121            }
1122            Some(HoldSource::Manual) => {
1123                if manual_is_stale(&task, now)
1124                    && file_question(questions, &task, Bucket::ManualStale, w, now).is_some()
1125                {
1126                    report.asked.push(task.id.clone());
1127                }
1128            }
1129        }
1130    }
1131    report
1132}
1133
1134/// The open triage question about `task_id`, if any - what `magi task show`
1135/// prints so a held task's card names the question waiting on it, not only
1136/// its hold reason. `None` once it is answered or abandoned: nothing is
1137/// waiting on it anymore.
1138pub fn open_question_for(questions: &Questions, task_id: &str) -> Option<Question> {
1139    latest_triage_question(questions, task_id).filter(|q| q.status.open())
1140}
1141
1142/// Does this module still have unfinished business with `task`?
1143///
1144/// True while its latest triage question is still open (waiting on an
1145/// answer), and true for a beat longer than [`open_question_for`] alone
1146/// would say: once answered, the question sits [`QuestionStatus::Answered`]
1147/// but unread until the next [`run_once`] pass actually applies it (see
1148/// [`already_applied`]), and [`run_once`] only ever runs on a fully idle
1149/// daemon tick - far less often than `crate::conduct` polls. A caller that
1150/// only checked "is a question open" would walk straight through that gap
1151/// the moment the operator answers, moving the task out of `held` before
1152/// [`run_once`] gets a turn - orphaning the very answer it was about to
1153/// apply, the same failure mode this function exists to keep `crate::conduct`
1154/// out of. `crate::conduct::apply_one` is exactly that caller.
1155pub fn pending_for(questions: &Questions, task: &Task) -> bool {
1156    let own = match latest_triage_question(questions, &task.id) {
1157        Some(q) if q.status.open() => true,
1158        Some(q) if q.status == QuestionStatus::Answered => !already_applied(task, &q),
1159        _ => false,
1160    };
1161    own || deps_pending(questions, task)
1162}
1163
1164/// Is the latest [`DEPS_NODE`] question about `task` still open, or answered
1165/// but not yet applied? Same reasoning as [`pending_for`]: the gap between an
1166/// answer and the next [`run_once`] pass must not be walked through.
1167fn deps_pending(questions: &Questions, task: &Task) -> bool {
1168    match latest_question(questions, DEPS_NODE, &task.id) {
1169        Some(q) if q.status.open() => true,
1170        Some(q) if q.status == QuestionStatus::Answered => !task.triage_applied(&q.id),
1171        _ => false,
1172    }
1173}
1174
1175/// Every task id with an open triage question right now - what `magi task
1176/// list` uses to mark a held task that is already waiting on an operator
1177/// decision, rather than have it read identically to one nobody has looked
1178/// at yet.
1179pub fn open_task_ids(questions: &Questions) -> std::collections::BTreeSet<String> {
1180    questions
1181        .list()
1182        .into_iter()
1183        .filter(|q| (q.node == NODE || q.node == DEPS_NODE) && q.status.open())
1184        .map(|q| q.run)
1185        .collect()
1186}
1187
1188#[cfg(test)]
1189mod tests {
1190    use super::*;
1191    use crate::ask::Answer;
1192    use crate::queue::Source;
1193    use jiff::SignedDuration;
1194
1195    fn store() -> (tempfile::TempDir, Queue, Questions) {
1196        let dir = tempfile::tempdir().unwrap();
1197        let q = Queue::at(dir.path().join("queue"));
1198        let s = Questions::at(dir.path().join("questions"));
1199        (dir, q, s)
1200    }
1201
1202    fn task(title: &str, repo: PathBuf) -> Task {
1203        Task::new(title.to_owned(), format!("do {title}"), repo, Source::Human)
1204    }
1205
1206    /// `[disk] min_free_bytes = 0` written next to a fictional repo, so
1207    /// `machine_cause_resolved` never has to ask the real disk anything - the
1208    /// same fixture pattern `daemon`'s own idle-loop tests use.
1209    fn gate_disabled_config(dir: &std::path::Path) -> PathBuf {
1210        let config = dir.join("magi.toml");
1211        std::fs::write(&config, "[disk]\nmin_free_bytes = 0\n").unwrap();
1212        config
1213    }
1214
1215    #[test]
1216    fn resumption_later_keep_held_answer_wins_but_an_older_answer_cannot_undo_release() {
1217        for source in ["cli", "web"] {
1218            for answer_after_release in [true, false] {
1219                let (dir, queue, questions) = store();
1220                let mut t = task("recovery", dir.path().join("repo"));
1221                t.hold_machine(Some("inspect remote first".into()));
1222                queue.put(&mut t).unwrap();
1223                let mut q = file_question(
1224                    &questions,
1225                    &t,
1226                    Bucket::MachineUnknown,
1227                    &JA,
1228                    Timestamp::now(),
1229                )
1230                .unwrap();
1231                if !answer_after_release {
1232                    q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
1233                    questions.put(&mut q).unwrap();
1234                }
1235                t.release_operator(source, None);
1236                queue.put(&mut t).unwrap();
1237                if answer_after_release {
1238                    q.answer(Answer::Choice(q.choices[1].clone())).unwrap();
1239                    questions.put(&mut q).unwrap();
1240                }
1241                apply_answers(&queue, &questions);
1242                let after = queue.get(&t.id).unwrap();
1243                assert!(after.triage_applied(&q.id));
1244                assert_eq!(after.operator_held(), answer_after_release);
1245                assert_eq!(
1246                    after.status,
1247                    if answer_after_release {
1248                        TaskStatus::Held
1249                    } else {
1250                        TaskStatus::Queued
1251                    }
1252                );
1253                assert!(apply_answers(&queue, &questions).is_empty());
1254            }
1255        }
1256    }
1257
1258    #[test]
1259    fn explicit_resumption_applies_legacy_queued_triage_once_and_preserves_later_holds() {
1260        let (dir, queue, questions) = store();
1261        let mut t = task("recover", dir.path().join("repo"));
1262        t.hold_machine(Some("inspect first".into()));
1263        queue.put(&mut t).unwrap();
1264        let mut q = file_question(
1265            &questions,
1266            &t,
1267            Bucket::MachineUnknown,
1268            &JA,
1269            Timestamp::now(),
1270        )
1271        .unwrap();
1272        assert!(q.actions.is_empty());
1273        q.answer(Answer::Choice(q.choices[0].clone())).unwrap();
1274        questions.put(&mut q).unwrap();
1275        // Older release paths queued the task without recording approval.
1276        t.release();
1277        t.instruction = "Reuse approved PR head".into();
1278        queue.put(&mut t).unwrap();
1279        assert_eq!(apply_answers(&queue, &questions), [t.id.clone()]);
1280        let mut after = queue.get(&t.id).unwrap();
1281        assert_eq!(
1282            after.resumption.as_ref().unwrap().question_id.as_deref(),
1283            Some(q.id.as_str())
1284        );
1285        assert_eq!(
1286            after.resumption.as_ref().unwrap().instruction,
1287            t.instruction
1288        );
1289        assert_eq!(after.answers[0].answer, JA.resume);
1290        assert!(after.triage_applied(&q.id));
1291        assert!(apply_answers(&Queue::at(dir.path().join("queue")), &questions).is_empty());
1292        after.hold_machine(Some("new blocker".into()));
1293        queue.put(&mut after).unwrap();
1294        let mut late = file_question(
1295            &questions,
1296            &after,
1297            Bucket::MachineUnknown,
1298            &EN,
1299            Timestamp::now(),
1300        )
1301        .unwrap();
1302        after.hold_manual(Some("keep held now".into()));
1303        queue.put(&mut after).unwrap();
1304        late.answer(Answer::Choice(late.choices[0].clone()))
1305            .unwrap();
1306        questions.put(&mut late).unwrap();
1307        apply_answers(&queue, &questions);
1308        let held = queue.get(&t.id).unwrap();
1309        assert!(held.operator_held());
1310        assert_eq!(held.hold_reason.as_deref(), Some("keep held now"));
1311        assert_eq!(held.resumption.as_ref().unwrap().generation, 1);
1312    }
1313
1314    #[test]
1315    fn a_resolved_machine_hold_is_requeued_automatically() {
1316        let (dir, q, questions) = store();
1317        let config = gate_disabled_config(dir.path());
1318        let mut t = task("disk pressure", dir.path().join("repo"));
1319        t.hold_machine(Some(
1320            "not enough free space to start a run: 10 bytes free, 100 required by \
1321             `[disk] min_free_bytes`"
1322                .to_owned(),
1323        ));
1324        q.put(&mut t).unwrap();
1325
1326        let report = run_once(&q, &questions, Some(&config), Timestamp::now());
1327        assert_eq!(report.resumed, [t.id.clone()]);
1328        assert!(report.asked.is_empty());
1329
1330        let back = q.get(&t.id).unwrap();
1331        assert_eq!(back.status, TaskStatus::Queued);
1332        assert!(back.hold_source.is_none());
1333        assert!(questions.list().is_empty(), "nothing needed asking");
1334    }
1335
1336    #[test]
1337    fn a_machine_hold_with_no_recognised_cause_gets_one_question_not_two() {
1338        let (dir, q, questions) = store();
1339        let mut t = task("gate went red", dir.path().join("repo"));
1340        t.hold_machine(Some("gate red".to_owned()));
1341        q.put(&mut t).unwrap();
1342
1343        let first = run_once(&q, &questions, None, Timestamp::now());
1344        assert_eq!(first.asked, [t.id.clone()]);
1345        assert!(first.resumed.is_empty());
1346
1347        let open: Vec<_> = questions
1348            .list()
1349            .into_iter()
1350            .filter(|q| q.status.open())
1351            .collect();
1352        assert_eq!(open.len(), 1);
1353        assert_eq!(open[0].run, t.id);
1354        assert_eq!(open[0].node, NODE);
1355        assert_eq!(open[0].choices.len(), 3);
1356
1357        // A second pass with nothing new must not file a second question.
1358        let second = run_once(&q, &questions, None, Timestamp::now());
1359        assert!(second.asked.is_empty());
1360        assert_eq!(
1361            questions
1362                .list()
1363                .into_iter()
1364                .filter(|q| q.status.open())
1365                .count(),
1366            1
1367        );
1368    }
1369
1370    #[test]
1371    fn a_legacy_hold_with_no_recorded_source_gets_exactly_one_question() {
1372        let (dir, q, questions) = store();
1373        let mut t = task("schema 1 record", dir.path().join("repo"));
1374        t.status = TaskStatus::Held;
1375        assert!(t.hold_source.is_none(), "the case this test is about");
1376        q.put(&mut t).unwrap();
1377
1378        let first = run_once(&q, &questions, None, Timestamp::now());
1379        assert_eq!(first.asked, [t.id.clone()]);
1380
1381        let second = run_once(&q, &questions, None, Timestamp::now());
1382        assert!(
1383            second.asked.is_empty(),
1384            "the same legacy hold must not be asked about twice"
1385        );
1386        assert_eq!(
1387            questions
1388                .list()
1389                .into_iter()
1390                .filter(|q| q.status.open())
1391                .count(),
1392            1
1393        );
1394    }
1395
1396    #[test]
1397    fn a_manual_hold_is_never_auto_resumed() {
1398        let (dir, q, questions) = store();
1399        let mut t = task("operator stopped this", dir.path().join("repo"));
1400        t.hold_manual(Some("waiting on a decision".to_owned()));
1401        q.put(&mut t).unwrap();
1402
1403        let report = run_once(&q, &questions, None, Timestamp::now());
1404        assert!(report.resumed.is_empty());
1405        // Fresh, not stale yet - no question either.
1406        assert!(report.asked.is_empty());
1407
1408        let back = q.get(&t.id).unwrap();
1409        assert_eq!(back.status, TaskStatus::Held);
1410        assert_eq!(back.hold_source, Some(HoldSource::Manual));
1411        assert!(questions.list().is_empty());
1412    }
1413
1414    #[test]
1415    fn a_blocked_task_on_a_deleted_dependency_is_held_and_asked_about_in_one_pass() {
1416        // The five real tasks this whole change exists for are `blocked`, not
1417        // `held`, and no daemon has to be running for `magi task triage` alone
1418        // to reach them - `run_once` must both quarantine and ask in the same
1419        // call.
1420        let (dir, q, questions) = store();
1421        let mut still_going = task("still valid", dir.path().join("repo"));
1422        q.put(&mut still_going).unwrap();
1423
1424        let mut t = task("orphaned", dir.path().join("repo"));
1425        t.block(
1426            vec!["20260101-000000-gone".to_owned(), still_going.id.clone()],
1427            Some("waits on both".to_owned()),
1428        );
1429        q.put(&mut t).unwrap();
1430
1431        let report = run_once(&q, &questions, None, Timestamp::now());
1432        assert_eq!(report.quarantined, [t.id.clone()]);
1433        assert_eq!(
1434            report.asked,
1435            [t.id.clone()],
1436            "the fresh machine hold must earn a question in the same pass"
1437        );
1438
1439        let after = q.get(&t.id).unwrap();
1440        assert_eq!(after.status, TaskStatus::Held);
1441        assert_eq!(after.hold_source, Some(HoldSource::Machine));
1442        assert!(after.blocked_by.is_empty());
1443
1444        // The reason is not disk-pressure wording, so this must not be read
1445        // as a disk hold and silently auto-resumed.
1446        assert!(!is_disk_hold(&after));
1447
1448        let open: Vec<_> = questions
1449            .list()
1450            .into_iter()
1451            .filter(|q| q.status.open())
1452            .collect();
1453        assert_eq!(open.len(), 1);
1454        assert_eq!(open[0].run, t.id);
1455
1456        // A second pass with nothing new files no second question.
1457        let second = run_once(&q, &questions, None, Timestamp::now());
1458        assert!(second.quarantined.is_empty());
1459        assert!(second.asked.is_empty());
1460    }
1461
1462    /// A held root with a chain of dependants: 9db7 <- 4135 <- 6081, and a
1463    /// second direct dependant that also waits on a queued task.
1464    fn stuck_chain(q: &Queue, dir: &std::path::Path) -> (Task, Task, Task) {
1465        let mut root = task("root", dir.join("repo"));
1466        root.hold_manual(Some("waiting".to_owned()));
1467        q.put(&mut root).unwrap();
1468        let mut mid = task("mid", dir.join("repo"));
1469        mid.block(vec![root.id.clone()], None);
1470        q.put(&mut mid).unwrap();
1471        let mut leaf = task("leaf", dir.join("repo"));
1472        leaf.block(vec![mid.id.clone()], None);
1473        q.put(&mut leaf).unwrap();
1474        (root, mid, leaf)
1475    }
1476
1477    fn deps_questions(questions: &Questions) -> Vec<Question> {
1478        questions
1479            .list()
1480            .into_iter()
1481            .filter(|q| q.node == DEPS_NODE)
1482            .collect()
1483    }
1484
1485    fn answer_deps(questions: &Questions, choice: usize) {
1486        let mut asked = deps_questions(questions).remove(0);
1487        let c = asked.choices[choice].clone();
1488        asked.answer(Answer::Choice(c)).unwrap();
1489        questions.put(&mut asked).unwrap();
1490    }
1491
1492    #[test]
1493    fn a_stuck_chain_earns_one_question_naming_every_dependant_and_is_not_reasked() {
1494        let (dir, q, questions) = store();
1495        let (root, mid, leaf) = stuck_chain(&q, dir.path());
1496
1497        let first = run_once(&q, &questions, None, Timestamp::now());
1498        assert_eq!(first.asked, std::slice::from_ref(&root.id));
1499        let asked = deps_questions(&questions);
1500        assert_eq!(asked.len(), 1, "one question per root, not per dependant");
1501        assert_eq!(asked[0].run, root.id);
1502        assert_eq!(asked[0].choices.len(), 3);
1503        assert!(asked[0].detail.contains(mid.short()), "{}", asked[0].detail);
1504        assert!(
1505            asked[0].detail.contains(leaf.short()),
1506            "{}",
1507            asked[0].detail
1508        );
1509
1510        let second = run_once(&q, &questions, None, Timestamp::now());
1511        assert!(second.asked.is_empty());
1512        assert_eq!(deps_questions(&questions).len(), 1);
1513        assert!(pending_for(&questions, &q.get(&root.id).unwrap()));
1514    }
1515
1516    #[test]
1517    fn a_stuck_root_with_a_machine_hold_gets_only_the_dependency_question() {
1518        let (dir, q, questions) = store();
1519        let mut root = task("root", dir.path().join("repo"));
1520        root.hold_machine(Some("gate red".to_owned()));
1521        q.put(&mut root).unwrap();
1522        let mut dep = task("dep", dir.path().join("repo"));
1523        dep.block(vec![root.id.clone()], None);
1524        q.put(&mut dep).unwrap();
1525
1526        run_once(&q, &questions, None, Timestamp::now());
1527        run_once(&q, &questions, None, Timestamp::now());
1528        assert_eq!(deps_questions(&questions).len(), 1);
1529        assert_eq!(
1530            questions.list().len(),
1531            1,
1532            "no second question about the hold"
1533        );
1534    }
1535
1536    #[test]
1537    fn a_dependency_that_can_still_run_asks_nothing() {
1538        let (dir, q, questions) = store();
1539        let mut live = task("live", dir.path().join("repo"));
1540        q.put(&mut live).unwrap();
1541        let mut dep = task("dep", dir.path().join("repo"));
1542        dep.block(vec![live.id.clone()], None);
1543        q.put(&mut dep).unwrap();
1544        let report = run_once(&q, &questions, None, Timestamp::now());
1545        assert!(report.asked.is_empty());
1546        assert!(questions.list().is_empty());
1547    }
1548
1549    #[test]
1550    fn answering_release_requeues_the_root_and_is_not_reasked() {
1551        let (dir, q, questions) = store();
1552        let (root, _mid, _leaf) = stuck_chain(&q, dir.path());
1553        run_once(&q, &questions, None, Timestamp::now());
1554        answer_deps(&questions, 0);
1555
1556        let report = run_once(&q, &questions, None, Timestamp::now());
1557        assert_eq!(report.answered, std::slice::from_ref(&root.id));
1558        assert!(report.asked.is_empty(), "applying must not re-ask");
1559        assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Queued);
1560        let again = run_once(&q, &questions, None, Timestamp::now());
1561        assert!(again.asked.is_empty() && again.answered.is_empty());
1562        assert_eq!(deps_questions(&questions).len(), 1);
1563    }
1564
1565    #[test]
1566    fn answering_detach_frees_the_direct_dependant_and_keeps_the_root() {
1567        let (dir, q, questions) = store();
1568        let (root, mid, leaf) = stuck_chain(&q, dir.path());
1569        run_once(&q, &questions, None, Timestamp::now());
1570        answer_deps(&questions, 2);
1571
1572        let report = run_once(&q, &questions, None, Timestamp::now());
1573        assert!(report.asked.is_empty());
1574        assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
1575        assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
1576        let leaf = q.get(&leaf.id).unwrap();
1577        assert_eq!(leaf.status, TaskStatus::Blocked, "still waits on mid");
1578        assert_eq!(leaf.blocked_by, std::slice::from_ref(&mid.id));
1579    }
1580
1581    #[test]
1582    fn a_dependant_that_can_progress_through_another_blocker_is_not_stuck() {
1583        let (dir, q, questions) = store();
1584        let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1585        let mut live = task("live", dir.path().join("repo"));
1586        q.put(&mut live).unwrap();
1587        let mut both = q.get(&mid.id).unwrap();
1588        both.block(vec![root.id.clone(), live.id.clone()], None);
1589        q.put(&mut both).unwrap();
1590        // `mid` can still progress through `live`, so nothing is stuck yet.
1591        assert!(
1592            run_once(&q, &questions, None, Timestamp::now())
1593                .asked
1594                .is_empty()
1595        );
1596    }
1597
1598    #[test]
1599    fn answering_discard_detaches_then_removes_the_root() {
1600        let (dir, q, questions) = store();
1601        let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1602        run_once(&q, &questions, None, Timestamp::now());
1603        answer_deps(&questions, 1);
1604
1605        let report = run_once(&q, &questions, None, Timestamp::now());
1606        assert!(q.get(&root.id).is_err());
1607        assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Queued);
1608        assert!(
1609            report.asked.is_empty(),
1610            "no per-dependant quarantine question"
1611        );
1612        assert!(report.quarantined.is_empty());
1613    }
1614
1615    #[test]
1616    fn an_unmatched_deps_answer_changes_nothing_and_is_not_reasked() {
1617        let (dir, q, questions) = store();
1618        let (root, mid, _leaf) = stuck_chain(&q, dir.path());
1619        run_once(&q, &questions, None, Timestamp::now());
1620        let mut asked = deps_questions(&questions).remove(0);
1621        asked.choices.clear();
1622        asked.answer(Answer::Text("dunno".to_owned())).unwrap();
1623        questions.put(&mut asked).unwrap();
1624
1625        for _ in 0..2 {
1626            let report = run_once(&q, &questions, None, Timestamp::now());
1627            assert!(report.asked.is_empty() && report.answered.is_empty());
1628        }
1629        assert_eq!(deps_questions(&questions).len(), 1);
1630        assert_eq!(q.get(&root.id).unwrap().status, TaskStatus::Held);
1631        assert_eq!(q.get(&mid.id).unwrap().status, TaskStatus::Blocked);
1632    }
1633
1634    #[test]
1635    fn a_dependency_cycle_terminates_and_is_asked_about_once() {
1636        let (dir, q, questions) = store();
1637        let mut a = task("a", dir.path().join("repo"));
1638        let mut b = task("b", dir.path().join("repo"));
1639        a.block(vec![b.id.clone()], None);
1640        b.block(vec![a.id.clone()], None);
1641        q.put(&mut a).unwrap();
1642        q.put(&mut b).unwrap();
1643
1644        let first = run_once(&q, &questions, None, Timestamp::now());
1645        assert_eq!(first.asked.len(), 1);
1646        let second = run_once(&q, &questions, None, Timestamp::now());
1647        assert!(second.asked.is_empty());
1648        assert_eq!(deps_questions(&questions).len(), 1);
1649    }
1650
1651    #[test]
1652    fn a_missing_dependency_is_still_quarantined_not_asked_about_as_stuck() {
1653        let (dir, q, questions) = store();
1654        let mut t = task("orphan", dir.path().join("repo"));
1655        t.block(vec!["20260101-000000-gone".to_owned()], None);
1656        q.put(&mut t).unwrap();
1657        let report = run_once(&q, &questions, None, Timestamp::now());
1658        assert_eq!(report.quarantined, [t.id.clone()]);
1659        assert!(deps_questions(&questions).is_empty());
1660    }
1661
1662    #[test]
1663    fn a_stale_manual_hold_earns_a_two_choice_question() {
1664        let (dir, q, questions) = store();
1665        let mut t = task("been sitting a while", dir.path().join("repo"));
1666        t.hold_manual(Some("waiting on a decision".to_owned()));
1667        q.put(&mut t).unwrap();
1668        // Back-date the hold past MANUAL_STALE_AFTER without waiting a week.
1669        let mut back = q.get(&t.id).unwrap();
1670        back.updated_at = Timestamp::now() - SignedDuration::new(8 * 24 * 60 * 60, 0);
1671        std::fs::write(
1672            q.path_of(&back.id),
1673            serde_json::to_string_pretty(&back).unwrap(),
1674        )
1675        .unwrap();
1676
1677        let report = run_once(&q, &questions, None, Timestamp::now());
1678        assert_eq!(report.asked, [t.id.clone()]);
1679        let open: Vec<_> = questions
1680            .list()
1681            .into_iter()
1682            .filter(|q| q.status.open())
1683            .collect();
1684        assert_eq!(open.len(), 1);
1685        assert_eq!(open[0].choices.len(), 2);
1686    }
1687
1688    #[test]
1689    fn answering_resume_releases_the_task() {
1690        let (dir, q, questions) = store();
1691        let mut t = task("gate went red", dir.path().join("repo"));
1692        t.hold_machine(Some("gate red".to_owned()));
1693        q.put(&mut t).unwrap();
1694        run_once(&q, &questions, None, Timestamp::now());
1695
1696        let mut asked = questions
1697            .list()
1698            .into_iter()
1699            .find(|q| q.run == t.id)
1700            .unwrap();
1701        asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
1702        questions.put(&mut asked).unwrap();
1703
1704        let report = run_once(&q, &questions, None, Timestamp::now());
1705        assert_eq!(report.answered, [t.id.clone()]);
1706        let back = q.get(&t.id).unwrap();
1707        assert_eq!(back.status, TaskStatus::Queued);
1708        assert!(back.hold_source.is_none());
1709    }
1710
1711    /// A task released by a "resume" answer, run, and failed back to `held`.
1712    fn resumed_then_failed(q: &Queue, questions: &Questions, dir: &std::path::Path) -> Task {
1713        let mut t = task("gate went red", dir.join("repo"));
1714        t.hold_machine(Some("gate red".to_owned()));
1715        q.put(&mut t).unwrap();
1716        run_once(q, questions, None, Timestamp::now());
1717        let mut asked = questions
1718            .list()
1719            .into_iter()
1720            .find(|q| q.run == t.id)
1721            .unwrap();
1722        asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
1723        questions.put(&mut asked).unwrap();
1724
1725        let report = run_once(q, questions, None, Timestamp::now());
1726        assert_eq!(report.answered, [t.id.clone()]);
1727        let mut back = q.get(&t.id).unwrap();
1728        assert_eq!(back.status, TaskStatus::Queued);
1729        assert_eq!(back.attempts, 0);
1730
1731        back.start("run-1".to_owned());
1732        back.fail("rebase conflict", 1);
1733        assert_eq!(back.status, TaskStatus::Held);
1734        q.put(&mut back).unwrap();
1735        back
1736    }
1737
1738    #[test]
1739    fn a_resume_answer_is_applied_once_and_a_new_machine_hold_is_asked_about() {
1740        let (dir, q, questions) = store();
1741        let t = resumed_then_failed(&q, &questions, dir.path());
1742
1743        let report = run_once(&q, &questions, None, Timestamp::now());
1744        assert!(report.answered.is_empty(), "the old answer must not replay");
1745        assert_eq!(report.asked, std::slice::from_ref(&t.id));
1746        let back = q.get(&t.id).unwrap();
1747        assert_eq!(back.status, TaskStatus::Held);
1748        assert_eq!(
1749            questions
1750                .list()
1751                .into_iter()
1752                .filter(|q| q.status.open())
1753                .count(),
1754            1
1755        );
1756    }
1757
1758    #[test]
1759    fn a_manual_hold_placed_after_a_resume_is_not_undone_by_the_old_answer() {
1760        let (dir, q, questions) = store();
1761        let mut t = resumed_then_failed(&q, &questions, dir.path());
1762        t.hold_manual(Some("operator stopped this".to_owned()));
1763        q.put(&mut t).unwrap();
1764        let before = questions.list().len();
1765
1766        let report = run_once(&q, &questions, None, Timestamp::now());
1767        assert!(report.answered.is_empty());
1768        assert!(report.asked.is_empty());
1769        let back = q.get(&t.id).unwrap();
1770        assert_eq!(back.status, TaskStatus::Held);
1771        assert_eq!(back.hold_source, Some(HoldSource::Manual));
1772        assert_eq!(questions.list().len(), before);
1773    }
1774
1775    #[test]
1776    fn answering_not_yet_keeps_it_held_as_a_manual_hold_and_does_not_reapply() {
1777        let (dir, q, questions) = store();
1778        let mut t = task("gate went red", dir.path().join("repo"));
1779        t.hold_machine(Some("gate red".to_owned()));
1780        q.put(&mut t).unwrap();
1781        run_once(&q, &questions, None, Timestamp::now());
1782
1783        let mut asked = questions
1784            .list()
1785            .into_iter()
1786            .find(|q| q.run == t.id)
1787            .unwrap();
1788        asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
1789        questions.put(&mut asked).unwrap();
1790
1791        let report = run_once(&q, &questions, None, Timestamp::now());
1792        assert_eq!(report.answered, [t.id.clone()]);
1793        let back = q.get(&t.id).unwrap();
1794        assert_eq!(back.status, TaskStatus::Held);
1795        assert_eq!(back.hold_source, Some(HoldSource::Manual));
1796        assert!(
1797            back.hold_reason
1798                .as_deref()
1799                .is_some_and(|r| r.contains("gate red")),
1800            "the original cause must survive a \"not yet\" answer, not just the \
1801             triage marker: {:?}",
1802            back.hold_reason
1803        );
1804
1805        // A third pass, same instant: the manual hold is fresh (just
1806        // touched), so nothing more happens - in particular the already
1807        // answered question is not re-applied.
1808        let third = run_once(&q, &questions, None, Timestamp::now());
1809        assert!(third.answered.is_empty());
1810        assert!(third.asked.is_empty());
1811    }
1812
1813    #[test]
1814    fn answering_discard_removes_the_task_entirely() {
1815        let (dir, q, questions) = store();
1816        let mut t = task("gate went red", dir.path().join("repo"));
1817        t.hold_machine(Some("gate red".to_owned()));
1818        q.put(&mut t).unwrap();
1819        run_once(&q, &questions, None, Timestamp::now());
1820
1821        let mut asked = questions
1822            .list()
1823            .into_iter()
1824            .find(|q| q.run == t.id)
1825            .unwrap();
1826        asked.answer(Answer::Choice(EN.discard.to_owned())).unwrap();
1827        questions.put(&mut asked).unwrap();
1828
1829        let report = run_once(&q, &questions, None, Timestamp::now());
1830        assert_eq!(report.answered, [t.id.clone()]);
1831        assert!(
1832            q.get(&t.id).is_err(),
1833            "\"discard it\" (捨ててよい) must actually discard the task, not \
1834             just leave it sitting held forever"
1835        );
1836    }
1837
1838    #[test]
1839    fn an_answer_is_read_by_its_position_in_choices_not_by_the_callers_current_language() {
1840        // Filed while the repo's config reads Japanese...
1841        let (dir, q, questions) = store();
1842        let ja_config = dir.path().join("ja.toml");
1843        std::fs::write(&ja_config, "[graph]\nlanguage = \"ja\"\n").unwrap();
1844        let mut t = task("gate went red", dir.path().join("repo"));
1845        t.hold_machine(Some("gate red".to_owned()));
1846        q.put(&mut t).unwrap();
1847        run_once(&q, &questions, Some(&ja_config), Timestamp::now());
1848
1849        let mut asked = questions
1850            .list()
1851            .into_iter()
1852            .find(|q| q.run == t.id)
1853            .unwrap();
1854        assert_eq!(asked.choices[0], JA.resume, "filed in Japanese");
1855        asked.answer(Answer::Choice(JA.resume.to_owned())).unwrap();
1856        questions.put(&mut asked).unwrap();
1857
1858        // ...but applied against an English config (a later `--config`, or an
1859        // edited repository config). The Japanese "再開してよい" answer must
1860        // still be read as a resume, not silently misread as "keep held"
1861        // because it fails a text comparison against the English wording.
1862        let en_config = dir.path().join("en.toml");
1863        std::fs::write(&en_config, "[graph]\nlanguage = \"en\"\n").unwrap();
1864        let report = run_once(&q, &questions, Some(&en_config), Timestamp::now());
1865        assert_eq!(report.answered, [t.id.clone()]);
1866        let back = q.get(&t.id).unwrap();
1867        assert_eq!(
1868            back.status,
1869            TaskStatus::Queued,
1870            "a resume answer must resume the task regardless of which \
1871             language it is read back in"
1872        );
1873    }
1874
1875    #[test]
1876    fn a_question_falls_back_to_last_error_when_hold_reason_was_never_set() {
1877        // A record written before `Task::fail` started copying `why` into
1878        // `hold_reason` too (or one written by a still older build) carries
1879        // only `last_error`. The question detail must still name a cause
1880        // rather than reading "(none recorded)".
1881        let (dir, q, questions) = store();
1882        let mut t = task("kept failing the gate", dir.path().join("repo"));
1883        t.start("run-1".to_owned());
1884        t.fail("gate red three times running", 1);
1885        assert_eq!(t.status, TaskStatus::Held);
1886        t.hold_reason = None; // simulate a pre-fix or pre-schema record
1887        q.put(&mut t).unwrap();
1888
1889        run_once(&q, &questions, None, Timestamp::now());
1890        let asked = questions
1891            .list()
1892            .into_iter()
1893            .find(|q| q.run == t.id)
1894            .unwrap();
1895        assert!(
1896            asked.detail.contains("gate red three times running"),
1897            "the question must surface `last_error` when there is no \
1898             `hold_reason` to show instead: {}",
1899            asked.detail
1900        );
1901    }
1902
1903    #[test]
1904    fn open_question_for_and_open_task_ids_reflect_only_what_is_still_waiting() {
1905        let (dir, q, questions) = store();
1906        let mut t = task("gate went red", dir.path().join("repo"));
1907        t.hold_machine(Some("gate red".to_owned()));
1908        q.put(&mut t).unwrap();
1909
1910        assert!(open_question_for(&questions, &t.id).is_none());
1911        assert!(!open_task_ids(&questions).contains(&t.id));
1912
1913        run_once(&q, &questions, None, Timestamp::now());
1914        assert!(open_question_for(&questions, &t.id).is_some());
1915        assert!(open_task_ids(&questions).contains(&t.id));
1916
1917        let mut asked = questions
1918            .list()
1919            .into_iter()
1920            .find(|q| q.run == t.id)
1921            .unwrap();
1922        asked.answer(Answer::Choice(EN.resume.to_owned())).unwrap();
1923        questions.put(&mut asked).unwrap();
1924
1925        assert!(
1926            open_question_for(&questions, &t.id).is_none(),
1927            "an answered question is no longer open"
1928        );
1929        assert!(!open_task_ids(&questions).contains(&t.id));
1930    }
1931
1932    #[test]
1933    fn pending_for_stays_true_between_an_answer_and_the_next_run_once_pass() {
1934        // `open_question_for` alone goes `None` the instant the operator
1935        // answers, well before `run_once` - idle-tick only - gets a turn to
1936        // actually apply that answer (see `already_applied`). `pending_for`
1937        // exists so a caller polling far more often than `run_once` does -
1938        // `crate::conduct::apply_one` - does not walk through that gap.
1939        let (dir, q, questions) = store();
1940        let mut t = task("gate went red", dir.path().join("repo"));
1941        t.hold_machine(Some("gate red".to_owned()));
1942        q.put(&mut t).unwrap();
1943
1944        assert!(!pending_for(&questions, &t));
1945
1946        run_once(&q, &questions, None, Timestamp::now());
1947        let held = q.get(&t.id).unwrap();
1948        assert!(pending_for(&questions, &held), "still waiting on an answer");
1949
1950        let mut asked = questions
1951            .list()
1952            .into_iter()
1953            .find(|q| q.run == t.id)
1954            .unwrap();
1955        asked.answer(Answer::Choice(EN.wait.to_owned())).unwrap();
1956        questions.put(&mut asked).unwrap();
1957        assert!(!asked.status.open());
1958
1959        // The race window: answered, but `run_once` has not run again yet.
1960        let still_held = q.get(&t.id).unwrap();
1961        assert!(
1962            pending_for(&questions, &still_held),
1963            "answered but not yet applied is still pending"
1964        );
1965
1966        run_once(&q, &questions, None, Timestamp::now());
1967        let after = q.get(&t.id).unwrap();
1968        assert!(
1969            !pending_for(&questions, &after),
1970            "the answer is applied now, nothing left pending"
1971        );
1972    }
1973}