Skip to main content

magi/
blockers.rs

1//! Dependency inventory for `blocked` tasks.
2//!
3//! [`crate::daemon::resolve_blockers`] frees a task when its dependency is
4//! `done` (or its question answered) and quarantines it when the dependency no
5//! longer exists. It has nothing to say about a dependency that is alive but
6//! *stuck*: a `held` task never becomes `done` on its own, so everything
7//! waiting on it waits forever, and nothing shows why. [`Inventory`] answers
8//! that from one snapshot of the queue and the questions:
9//!
10//! - [`Inventory::waits_on`] - what a blocked task waits on and each
11//!   dependency's state, following a chain of blocked dependencies
12//!   (`4135 (blocked → 9db7 held)`), for `magi task list` and the web UI.
13//! - [`Inventory::stuck_roots`] - the tasks nothing in the loop will ever run
14//!   that a blocked task is frozen behind. [`crate::triage`] asks about each
15//!   such root once, naming everything it freezes.
16//!
17//! A blocked task is *stuck* when it has at least one unresolved dependency
18//! and every one of them is either `held` or itself a stuck blocked task.
19//! Anything that can still make progress - a queued, running or failed
20//! (retried) task, an open question, a dependency that no longer exists (which
21//! `resolve_blockers` quarantines) - makes it not stuck. A dependency cycle
22//! terminates: its members are stuck, and the smallest id in the cycle is its
23//! root.
24
25use std::collections::{BTreeMap, BTreeSet};
26
27use crate::ask::{Question, QuestionStatus};
28use crate::queue::{Task, TaskStatus};
29
30/// How many hops [`Inventory::waits_on`] follows before it stops describing.
31const CHAIN_DEPTH: usize = 4;
32
33/// One snapshot of the tasks and questions a `blocked_by` id can name.
34#[derive(Debug, Clone, Default)]
35pub struct Inventory {
36    tasks: BTreeMap<String, Task>,
37    questions: BTreeMap<String, DecisionRecord>,
38    ids: Vec<String>,
39    complete: bool,
40}
41
42// Keep only routing metadata, rather than duplicating decision transcripts,
43// panels and answer payloads in a dependency inventory.
44#[derive(Debug, Clone)]
45struct DecisionRecord {
46    id: String,
47    status: QuestionStatus,
48    summary: String,
49    routed_task: Option<String>,
50    routed_chat: Option<String>,
51}
52
53impl From<&Question> for DecisionRecord {
54    fn from(q: &Question) -> Self {
55        Self {
56            id: q.id.clone(),
57            status: q.status,
58            summary: q.summary.clone(),
59            routed_task: q.routed_task.clone(),
60            routed_chat: q.routed_chat.clone(),
61        }
62    }
63}
64
65enum Dep<'a> {
66    Task(&'a Task),
67    Question(QuestionStatus),
68    Missing,
69    Unknown,
70}
71
72type Roots = Option<BTreeSet<String>>;
73
74/// Read-only dependency presentation. Decision records are interpreted only
75/// here, alongside the compatibility resolver; clients never infer ownership.
76#[derive(Debug, serde::Serialize)]
77pub struct BlockerView {
78    /// Canonical id when readable, otherwise the stored reference.
79    pub id: String,
80    /// Task, decision, or unavailable record.
81    pub kind: &'static str,
82    /// Recorded status and bounded dependency chain.
83    pub state: String,
84    /// Task title or decision summary, when readable.
85    pub reason: Option<String>,
86    /// Explanation of the supported next step.
87    pub next: String,
88    /// True when progress or scheduler reconciliation needs no operator action.
89    pub resolves_itself: bool,
90    /// Existing read-only page route and record id; never a control endpoint.
91    pub destination: Option<(&'static str, String)>,
92}
93
94/// The last dash-separated part of an id: what `Task::short` shows.
95fn short(id: &str) -> &str {
96    id.split('-').next_back().unwrap_or(id)
97}
98
99fn decision_view(q: &DecisionRecord) -> BlockerView {
100    let mut view = BlockerView {
101        id: q.id.clone(),
102        kind: "decision",
103        state: q.status.as_str().into(),
104        reason: Some(q.summary.clone()),
105        next: String::new(),
106        resolves_itself: q.status == QuestionStatus::Answered,
107        destination: None,
108    };
109    view.next = match q.status {
110        QuestionStatus::Answered => "Decision recorded; waiting for the scheduler to reconcile this dependency.",
111        QuestionStatus::Abandoned => "This record no longer accepts answers. If forwarded, continue in its owning task chat; otherwise inspect magi task triage for recovery. The record does not prove the dependency completed.",
112        QuestionStatus::Open if q.routed_task.is_some() && q.routed_chat.is_none() => "Waiting for delivery to the owning task chat. The scheduler must deliver the decision before it can be handled there.",
113        QuestionStatus::Open if q.routed_task.is_some() => "Open the owning task chat to review and resolve this decision through its existing controls. Availability and approval are checked there.",
114        QuestionStatus::Open => "Open the existing decision to inspect its context and available controls. A historical or unavailable waiter may no longer accept an answer.",
115    }.into();
116    view.destination = if q.routed_task.is_some() {
117        q.routed_chat.clone().map(|id| ("chat", id))
118    } else if q.status == QuestionStatus::Open {
119        Some(("questions", q.id.clone()))
120    } else {
121        None
122    };
123    view
124}
125
126impl Inventory {
127    /// All direct blockers, including settled and unavailable records. Task
128    /// links let the operator follow chains without hiding sibling blockers.
129    pub fn blocker_views(&self, task: &Task) -> Vec<BlockerView> {
130        if task.status != TaskStatus::Blocked {
131            return Vec::new();
132        }
133        task.blocked_by.iter().map(|id| {
134            let mut view = BlockerView {
135                id: id.clone(), kind: "unavailable", state: self.chain(id, &mut vec![task.id.clone()]),
136                reason: None, resolves_itself: false,
137                next: "Inspect the dependency reference with magi task triage; unavailable or ambiguous records cannot safely be treated as resolved.".into(),
138                destination: None,
139            };
140            match self.dep(id) {
141                Dep::Task(t) => {
142                    view.id = t.id.clone();
143                    view.kind = "task";
144                    view.reason = Some(t.title.clone());
145                    view.resolves_itself = matches!(t.status, TaskStatus::Queued | TaskStatus::Running | TaskStatus::Failed | TaskStatus::Parked | TaskStatus::Done);
146                    view.next = if t.status == TaskStatus::Done {
147                        "Completed; waiting for the scheduler to reconcile this dependency."
148                    } else if view.state.contains("cycle") {
149                        "Dependency cycle: inspect the linked task and use task triage or its owning chat to correct the wait. A cycle cannot complete on its own."
150                    } else if view.resolves_itself {
151                        "This dependency is still progressing or awaiting scheduler retry. No operator action is needed for this blocker; wait for it to complete."
152                    } else {
153                        "Open the dependency task to inspect its status, blockers and recovery controls. It must complete before this dependency resolves."
154                    }.into();
155                    view.destination = Some(("tasks", t.id.clone()));
156                }
157                Dep::Question(_) => {
158                    // Compatibility with existing decision outbox records;
159                    // do not create a decision or derive a chat from ancestry.
160                    let full = match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
161                        crate::queue::Reference::Found(full) => full,
162                        _ => id.clone(),
163                    };
164                    if let Some(q) = self.questions.get(&full) {
165                        view = decision_view(q);
166                    }
167                }
168                Dep::Missing => view.state = "missing".into(),
169                Dep::Unknown => {},
170            }
171            view
172        }).collect()
173    }
174
175    /// Pending held-task recovery decisions use the same compatibility
176    /// navigation as dependencies, with triage's exact pending predicate.
177    pub(crate) fn recovery_views(
178        task: &Task,
179        questions: &crate::ask::Questions,
180    ) -> Vec<BlockerView> {
181        crate::triage::pending_recovery_questions(questions, task).iter().map(|q| {
182            let mut view = decision_view(&DecisionRecord::from(q));
183            view.kind = "recovery decision";
184            view.next = if q.status.open() {
185                if q.routed_task.is_some() && q.routed_chat.is_none() {
186                    "Recovery decision pending delivery to the owning task chat. Disk recovery alone will not resume this task; wait for delivery and resolve the decision there."
187                } else {
188                    "Recovery decision pending. Open its existing controls to review and resolve it. Disk recovery alone will not resume this task while the decision remains pending."
189                }
190            } else {
191                "Recovery decision recorded but not yet applied. Its existing task-chat controls or triage must apply it before recovery can proceed; disk recovery alone will not resume this task."
192            }.into();
193            view.resolves_itself = q.status == QuestionStatus::Answered && q.routed_chat.is_none();
194            view
195        }).collect()
196    }
197
198    /// Build the snapshot. Callers take `queue.list()` and `questions.list()`
199    /// once, so a listing over many tasks never rescans the disk per task.
200    pub fn new(tasks: Vec<Task>, questions: &[Question]) -> Self {
201        let ids = tasks
202            .iter()
203            .map(|t| t.id.clone())
204            .chain(questions.iter().map(|q| q.id.clone()))
205            .collect();
206        Self {
207            ids,
208            complete: true,
209            tasks: tasks.into_iter().map(|t| (t.id.clone(), t)).collect(),
210            questions: questions
211                .iter()
212                .map(|q| (q.id.clone(), DecisionRecord::from(q)))
213                .collect(),
214        }
215    }
216
217    /// Include unreadable records and tombstones in id resolution; list()
218    /// alone cannot prove uniqueness or absence.
219    pub fn load(queue: &crate::queue::Queue, questions: &crate::ask::Questions) -> Self {
220        Self::load_with_tasks(queue, questions, queue.list())
221    }
222
223    /// Reuse a listing already read by the caller. Still include tombstones
224    /// and unreadable ids when resolving dependency ambiguity.
225    pub fn load_with_tasks(
226        queue: &crate::queue::Queue,
227        questions: &crate::ask::Questions,
228        tasks: Vec<Task>,
229    ) -> Self {
230        let mut inventory = Self::new(tasks, &questions.list_for_effects());
231        let ids = (|| -> anyhow::Result<Vec<String>> {
232            let mut ids = crate::queue::record_ids(queue.root(), "json")?;
233            ids.extend(crate::queue::record_ids(questions.root(), "json")?);
234            ids.extend(crate::queue::record_ids(queue.root(), "removed")?);
235            ids.sort();
236            ids.dedup();
237            Ok(ids)
238        })();
239        match ids {
240            Ok(ids) => inventory.ids = ids,
241            Err(_) => inventory.complete = false,
242        }
243        inventory
244    }
245
246    /// Read only the dependency closure for a detail view. Names across both
247    /// stores (including tombstones and corrupt records) still establish
248    /// ambiguity, and unreadable records remain unknown rather than resolved.
249    pub fn load_for(
250        queue: &crate::queue::Queue,
251        questions: &crate::ask::Questions,
252        task: &Task,
253    ) -> Self {
254        Self::load_for_tasks(queue, questions, std::slice::from_ref(task))
255    }
256
257    /// Share id enumeration and dependency reads across one list page.
258    pub fn load_for_tasks(
259        queue: &crate::queue::Queue,
260        questions: &crate::ask::Questions,
261        tasks: &[Task],
262    ) -> Self {
263        let mut inventory = Self::new(tasks.to_vec(), &[]);
264        if tasks.iter().all(|task| task.blocked_by.is_empty()) {
265            return inventory;
266        }
267        let ids = (|| -> anyhow::Result<Vec<String>> {
268            let mut ids = crate::queue::record_ids(queue.root(), "json")?;
269            ids.extend(crate::queue::record_ids(questions.root(), "json")?);
270            ids.extend(crate::queue::record_ids(queue.root(), "removed")?);
271            ids.sort();
272            ids.dedup();
273            Ok(ids)
274        })();
275        match ids {
276            Ok(ids) => inventory.ids = ids,
277            Err(_) => inventory.complete = false,
278        }
279        let mut pending: Vec<_> = tasks
280            .iter()
281            .flat_map(|task| task.blocked_by.iter().cloned())
282            .collect();
283        let mut seen = BTreeSet::new();
284        while let Some(reference) = pending.pop() {
285            let full =
286                if queue.path_of(&reference).is_file() || questions.path_of(&reference).is_file() {
287                    reference
288                } else if inventory.complete {
289                    match crate::queue::resolve_reference(
290                        &reference,
291                        inventory.ids.iter().map(String::as_str),
292                    ) {
293                        crate::queue::Reference::Found(full) => full,
294                        _ => continue,
295                    }
296                } else {
297                    continue;
298                };
299            if !seen.insert(full.clone()) {
300                continue;
301            }
302            if queue.path_of(&full).is_file()
303                && let Ok(t) = queue.get(&full)
304            {
305                pending.extend(t.blocked_by.iter().cloned());
306                inventory.tasks.insert(full.clone(), t);
307            }
308            if questions.path_of(&full).is_file()
309                && let Ok(q) = questions.get_for_effects(&full)
310            {
311                inventory.questions.insert(full, DecisionRecord::from(&q));
312            }
313        }
314        inventory
315    }
316
317    fn dep(&self, id: &str) -> Dep<'_> {
318        // A partial scan does not invalidate readable exact records. It does
319        // prevent proving that a prefix/suffix is unique across both stores.
320        if let Some(t) = self.tasks.get(id) {
321            return Dep::Task(t);
322        }
323        if let Some(s) = self.questions.get(id) {
324            return Dep::Question(s.status);
325        }
326        if !self.complete {
327            return Dep::Unknown;
328        }
329        match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
330            crate::queue::Reference::Found(full) => {
331                if let Some(t) = self.tasks.get(&full) {
332                    Dep::Task(t)
333                } else if let Some(s) = self.questions.get(&full) {
334                    Dep::Question(s.status)
335                } else {
336                    Dep::Unknown
337                }
338            }
339            crate::queue::Reference::Missing => Dep::Missing,
340            crate::queue::Reference::Ambiguous => Dep::Unknown,
341        }
342    }
343
344    /// A dependency that has nothing left to wait for.
345    fn resolved(&self, id: &str) -> bool {
346        match self.dep(id) {
347            Dep::Task(t) => t.status == TaskStatus::Done,
348            Dep::Question(s) => s == QuestionStatus::Answered,
349            Dep::Missing | Dep::Unknown => false,
350        }
351    }
352
353    fn walk(
354        &self,
355        id: &str,
356        path: &mut Vec<String>,
357        memo: &mut BTreeMap<String, Roots>,
358    ) -> (Roots, bool) {
359        if let Some(v) = memo.get(id) {
360            return (v.clone(), false);
361        }
362        let Some(task) = self.tasks.get(id) else {
363            return (None, false);
364        };
365        path.push(id.to_owned());
366        let mut roots = BTreeSet::new();
367        let mut moving = false;
368        let mut cyclic = false;
369        for b in &task.blocked_by {
370            match self.dep(b) {
371                Dep::Task(t) => match t.status {
372                    TaskStatus::Done => {}
373                    TaskStatus::Held => {
374                        roots.insert(t.id.clone());
375                    }
376                    TaskStatus::Blocked => {
377                        if let Some(pos) = path.iter().position(|p| p == &t.id) {
378                            // A cycle: its smallest id speaks for all of it, so
379                            // every entry point names the same root.
380                            if let Some(min) = path[pos..].iter().min() {
381                                roots.insert(min.clone());
382                            }
383                            cyclic = true;
384                        } else {
385                            let (sub, c) = self.walk(&t.id, path, memo);
386                            cyclic |= c;
387                            match sub {
388                                Some(r) => roots.extend(r),
389                                None => moving = true,
390                            }
391                        }
392                    }
393                    TaskStatus::Queued
394                    | TaskStatus::Running
395                    | TaskStatus::Failed
396                    | TaskStatus::Parked => {
397                        moving = true;
398                    }
399                },
400                Dep::Question(QuestionStatus::Answered) => {}
401                Dep::Question(_) | Dep::Missing | Dep::Unknown => moving = true,
402            }
403        }
404        path.pop();
405        let verdict = (!moving && !roots.is_empty()).then_some(roots);
406        if !cyclic {
407            memo.insert(id.to_owned(), verdict.clone());
408        }
409        (verdict, cyclic)
410    }
411
412    /// Every stuck `blocked` task, with the root ids it is frozen behind.
413    pub fn stuck(&self) -> BTreeMap<String, BTreeSet<String>> {
414        let mut memo = BTreeMap::new();
415        let mut out = BTreeMap::new();
416        for (id, t) in &self.tasks {
417            if t.status != TaskStatus::Blocked {
418                continue;
419            }
420            let (verdict, _) = self.walk(id, &mut Vec::new(), &mut memo);
421            if let Some(roots) = verdict {
422                out.insert(id.clone(), roots);
423            }
424        }
425        out
426    }
427
428    /// The roots `task` is frozen behind; empty when it is not stuck.
429    pub fn stuck_roots(&self, task: &Task) -> BTreeSet<String> {
430        if task.status != TaskStatus::Blocked {
431            return BTreeSet::new();
432        }
433        self.walk(&task.id, &mut Vec::new(), &mut BTreeMap::new())
434            .0
435            .unwrap_or_default()
436    }
437
438    /// Each dependency of `task` with its state, e.g. `9db7 (held)` or
439    /// `4135 (blocked → 9db7 held)`. Empty unless `task` is `blocked`.
440    pub fn waits_on(&self, task: &Task) -> Vec<String> {
441        if task.status != TaskStatus::Blocked {
442            return Vec::new();
443        }
444        task.blocked_by
445            .iter()
446            .map(|b| {
447                let chain = self.chain(b, &mut vec![task.id.clone()]);
448                format!("{} ({chain})", short(b))
449            })
450            .collect()
451    }
452
453    fn chain(&self, id: &str, seen: &mut Vec<String>) -> String {
454        match self.dep(id) {
455            Dep::Missing => "missing".to_owned(),
456            Dep::Unknown => "unavailable or ambiguous".to_owned(),
457            Dep::Question(s) => format!("question {}", s.as_str()),
458            Dep::Task(t) => {
459                let mut out = t.status.as_str().to_owned();
460                if t.status != TaskStatus::Blocked {
461                    return out;
462                }
463                if seen.iter().any(|s| s == &t.id) {
464                    return format!("{out}, cycle");
465                }
466                if seen.len() > CHAIN_DEPTH {
467                    return format!("{out} → …");
468                }
469                seen.push(t.id.clone());
470                if let Some(next) = t.blocked_by.iter().find(|b| !self.resolved(b)) {
471                    out.push_str(&format!(" → {} {}", short(next), self.chain(next, seen)));
472                }
473                out
474            }
475        }
476    }
477
478    /// The task with this id, if it is one.
479    pub fn task(&self, id: &str) -> Option<&Task> {
480        match self.dep(id) {
481            Dep::Task(t) => Some(t),
482            _ => None,
483        }
484    }
485}
486
487#[cfg(test)]
488mod tests {
489    use super::*;
490    use crate::queue::Source;
491    use std::path::PathBuf;
492
493    fn t(id: &str, status: TaskStatus, blocked_by: &[&str]) -> Task {
494        let mut t = Task::new(
495            id.to_owned(),
496            "x".to_owned(),
497            PathBuf::from("/repo"),
498            Source::Human,
499        );
500        t.id = format!("2026-{id}");
501        t.status = status;
502        t.blocked_by = blocked_by.iter().map(|b| format!("2026-{b}")).collect();
503        t
504    }
505
506    fn inv(tasks: Vec<Task>) -> Inventory {
507        Inventory::new(tasks, &[])
508    }
509
510    #[test]
511    fn blocker_views_preserve_all_dependencies_and_decision_delivery_states() {
512        let held = t("held", TaskStatus::Held, &[]);
513        let done = t("done", TaskStatus::Done, &[]);
514        let mut decision = Question::new(
515            "run".into(),
516            "node".into(),
517            "seat".into(),
518            "Choose recovery".into(),
519            "Context".into(),
520            vec![],
521        );
522        decision.routed_task = Some(held.id.clone());
523        let mut waiting = t("waiting", TaskStatus::Blocked, &["held", "done", "missing"]);
524        waiting.blocked_by.push(decision.id.clone());
525        let inventory = Inventory::new(
526            vec![held.clone(), done, waiting.clone()],
527            std::slice::from_ref(&decision),
528        );
529        let views = inventory.blocker_views(&waiting);
530        assert_eq!(views.len(), 4);
531        assert_eq!(views[0].destination, Some(("tasks", held.id.clone())));
532        assert!(!views[0].resolves_itself);
533        assert!(views[1].resolves_itself);
534        assert!(views[1].next.contains("reconcile"));
535        assert_eq!(views[2].state, "missing");
536        assert!(views[2].destination.is_none());
537        assert!(!views[2].resolves_itself);
538        assert!(!views[3].resolves_itself);
539        assert!(views[3].next.contains("delivery"));
540        assert!(views[3].destination.is_none());
541        assert!(inventory.blocker_views(&held).is_empty());
542        for status in [
543            QuestionStatus::Open,
544            QuestionStatus::Answered,
545            QuestionStatus::Abandoned,
546        ] {
547            decision.status = status;
548            decision.routed_chat = Some("owning-chat".into());
549            let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
550            let views = inventory.blocker_views(&waiting);
551            assert_eq!(views[3].resolves_itself, status == QuestionStatus::Answered);
552            assert_eq!(views[3].id, decision.id);
553            assert_eq!(views[3].destination, Some(("chat", "owning-chat".into())));
554            assert_eq!(views[3].reason.as_deref(), Some("Choose recovery"));
555        }
556        decision.routed_task = None;
557        decision.routed_chat = None;
558        decision.status = QuestionStatus::Open;
559        let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
560        assert_eq!(
561            inventory.blocker_views(&waiting)[3].destination,
562            Some(("questions", decision.id))
563        );
564    }
565
566    #[test]
567    fn blocker_views_distinguish_automatic_progress_from_operator_recovery() {
568        for status in [
569            TaskStatus::Queued,
570            TaskStatus::Running,
571            TaskStatus::Failed,
572            TaskStatus::Parked,
573            TaskStatus::Done,
574            TaskStatus::Held,
575            TaskStatus::Blocked,
576        ] {
577            let dependency = t("dependency", status, &[]);
578            let waiting = t("waiting", TaskStatus::Blocked, &["dependency"]);
579            let inventory = inv(vec![dependency, waiting.clone()]);
580            let views = inventory.blocker_views(&waiting);
581            assert_eq!(
582                views[0].resolves_itself,
583                !matches!(status, TaskStatus::Held | TaskStatus::Blocked),
584                "{status:?}"
585            );
586            if status == TaskStatus::Running {
587                assert!(views[0].next.contains("No operator action"));
588            }
589        }
590        let waiting = t("waiting", TaskStatus::Blocked, &["waiting"]);
591        let inventory = inv(vec![waiting.clone()]);
592        let views = inventory.blocker_views(&waiting);
593        assert!(!views[0].resolves_itself);
594        assert!(views[0].next.contains("cycle"));
595    }
596
597    #[test]
598    fn blocker_views_do_not_link_ambiguous_unreadable_or_removed_records() {
599        let dir = tempfile::tempdir().unwrap();
600        let queue = crate::queue::Queue::at(dir.path().join("queue"));
601        let questions = crate::ask::Questions::at(dir.path().join("questions"));
602        let mut waiting = t("waiting", TaskStatus::Blocked, &[]);
603        waiting.blocked_by = vec!["collision".into(), "broken".into(), "removed".into()];
604        queue.put(&mut waiting).unwrap();
605        for name in [
606            "a-collision.json",
607            "b-collision.removed",
608            "broken.json",
609            "removed.removed",
610        ] {
611            std::fs::write(queue.root().join(name), "unreadable").unwrap();
612        }
613        let inventory = Inventory::load_for(&queue, &questions, &waiting);
614        let views = inventory.blocker_views(&waiting);
615        assert_eq!(views.len(), 3);
616        assert!(
617            views
618                .iter()
619                .all(|view| view.destination.is_none() && view.state == "unavailable or ambiguous")
620        );
621    }
622
623    #[test]
624    fn responsiveness_dependency_closure_matches_the_full_inventory() {
625        let dir = tempfile::tempdir().unwrap();
626        let queue = crate::queue::Queue::at(dir.path().join("queue"));
627        let questions = crate::ask::Questions::at(dir.path().join("questions"));
628        let mut held = t("held", TaskStatus::Held, &[]);
629        let mut middle = t("middle", TaskStatus::Blocked, &["held"]);
630        let mut waiting = t("waiting", TaskStatus::Blocked, &["middle"]);
631        for task in [&mut held, &mut middle, &mut waiting] {
632            queue.put(task).unwrap();
633        }
634        for n in 0..150 {
635            let mut unrelated = t(&format!("noise{n}"), TaskStatus::Done, &[]);
636            unrelated.instruction = "history ".repeat(4096);
637            queue.put(&mut unrelated).unwrap();
638        }
639        for reference in ["2026-middle", "middle", "missing", "collision"] {
640            waiting.blocked_by = vec![reference.into()];
641            queue.put(&mut waiting).unwrap();
642            std::fs::write(queue.root().join("a-collision.json"), "corrupt").unwrap();
643            std::fs::write(queue.root().join("b-collision.removed"), "removed").unwrap();
644            let full = Inventory::load(&queue, &questions);
645            let small = Inventory::load_for(&queue, &questions, &waiting);
646            assert_eq!(small.waits_on(&waiting), full.waits_on(&waiting));
647            assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
648            assert!(small.tasks.len() <= 3);
649        }
650        // A cycle uses the same recursion and root rules as the full inventory.
651        held.status = TaskStatus::Blocked;
652        held.blocked_by = vec![middle.id.clone()];
653        queue.put(&mut held).unwrap();
654        waiting.blocked_by = vec![middle.id.clone()];
655        queue.put(&mut waiting).unwrap();
656        let full = Inventory::load(&queue, &questions);
657        let small = Inventory::load_for(&queue, &questions, &waiting);
658        assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
659    }
660
661    #[test]
662    fn dependency_resolution_partial_scan_keeps_readable_exact_records() {
663        let dir = tempfile::tempdir().unwrap();
664        let queue = crate::queue::Queue::at(dir.path().join("queue"));
665        let questions = crate::ask::Questions::at(dir.path().join("questions"));
666        let mut running = t("feb2", TaskStatus::Running, &[]);
667        let mut middle = t("ca5b", TaskStatus::Blocked, &["feb2"]);
668        let mut waiting = t("ee37", TaskStatus::Blocked, &["ca5b"]);
669        let mut held = t("held", TaskStatus::Held, &[]);
670        let mut short_wait = t("short", TaskStatus::Blocked, &[]);
671        short_wait.blocked_by = vec!["held".into()];
672        for task in [
673            &mut running,
674            &mut middle,
675            &mut waiting,
676            &mut held,
677            &mut short_wait,
678        ] {
679            queue.put(task).unwrap();
680        }
681        // Reading the queue succeeds, while scanning the question store fails.
682        std::fs::write(questions.root(), "not a directory").unwrap();
683        let inventory = Inventory::load(&queue, &questions);
684        assert!(!inventory.complete);
685        assert!(inventory.ids.contains(&running.id));
686        assert_eq!(
687            inventory.task(&running.id).unwrap().status,
688            TaskStatus::Running
689        );
690        assert_eq!(
691            inventory.waits_on(&waiting),
692            ["ca5b (blocked → feb2 running)"]
693        );
694        assert_eq!(
695            inventory.waits_on(&short_wait),
696            ["held (unavailable or ambiguous)"]
697        );
698        assert!(
699            inventory.stuck().is_empty(),
700            "partial scans cannot prove short-id uniqueness"
701        );
702        assert!(matches!(inventory.dep("not-seen"), Dep::Unknown));
703    }
704
705    #[test]
706    fn a_chain_reads_at_a_glance_and_its_root_is_the_held_task() {
707        let i = inv(vec![
708            t("9db7", TaskStatus::Held, &[]),
709            t("4135", TaskStatus::Blocked, &["9db7"]),
710            t("6081", TaskStatus::Blocked, &["4135"]),
711        ]);
712        let six = i.task("2026-6081").unwrap();
713        assert_eq!(i.waits_on(six), ["4135 (blocked → 9db7 held)"]);
714        let four = i.task("2026-4135").unwrap();
715        assert_eq!(i.waits_on(four), ["9db7 (held)"]);
716        let stuck = i.stuck();
717        assert_eq!(stuck.len(), 2);
718        assert!(stuck.values().all(|r| r.iter().eq(["2026-9db7"].iter())));
719    }
720
721    #[test]
722    fn a_dependency_that_can_still_run_is_not_stuck() {
723        let i = inv(vec![
724            t("aaaa", TaskStatus::Queued, &[]),
725            t("bbbb", TaskStatus::Held, &[]),
726            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
727            t("dddd", TaskStatus::Blocked, &["missing1"]),
728            t("eeee", TaskStatus::Blocked, &["cccc"]),
729        ]);
730        assert!(i.stuck().is_empty(), "{:?}", i.stuck());
731    }
732
733    #[test]
734    fn a_done_dependency_does_not_hide_a_held_one() {
735        let i = inv(vec![
736            t("aaaa", TaskStatus::Done, &[]),
737            t("bbbb", TaskStatus::Held, &[]),
738            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
739        ]);
740        assert_eq!(i.stuck().len(), 1);
741    }
742
743    #[test]
744    fn a_cycle_terminates_and_names_its_smallest_id_from_every_entry() {
745        let i = inv(vec![
746            t("bbbb", TaskStatus::Blocked, &["cccc"]),
747            t("cccc", TaskStatus::Blocked, &["aaaa"]),
748            t("aaaa", TaskStatus::Blocked, &["bbbb"]),
749            t("dddd", TaskStatus::Blocked, &["cccc"]),
750        ]);
751        let stuck = i.stuck();
752        assert_eq!(stuck.len(), 4);
753        for roots in stuck.values() {
754            assert!(roots.iter().eq(["2026-aaaa"].iter()), "{roots:?}");
755        }
756        let d = i.task("2026-dddd").unwrap();
757        assert!(i.waits_on(d)[0].contains("cycle"), "{:?}", i.waits_on(d));
758    }
759
760    #[test]
761    fn a_self_dependency_is_a_stuck_cycle_of_one() {
762        let i = inv(vec![t("aaaa", TaskStatus::Blocked, &["aaaa"])]);
763        assert_eq!(i.stuck().len(), 1);
764    }
765
766    #[test]
767    fn an_open_question_keeps_a_task_alive_and_an_answered_one_resolves() {
768        let mut open = Question::new(
769            "r".into(),
770            "n".into(),
771            "s".into(),
772            "?".into(),
773            String::new(),
774            vec![],
775        );
776        open.id = "2026-qqqq".into();
777        let mut answered = open.clone();
778        answered.id = "2026-rrrr".into();
779        answered.status = QuestionStatus::Answered;
780        let tasks = vec![
781            t("bbbb", TaskStatus::Held, &[]),
782            t("cccc", TaskStatus::Blocked, &["bbbb", "qqqq"]),
783            t("dddd", TaskStatus::Blocked, &["bbbb", "rrrr"]),
784        ];
785        let i = Inventory::new(tasks, &[open, answered]);
786        let stuck = i.stuck();
787        assert!(!stuck.contains_key("2026-cccc"));
788        assert!(stuck.contains_key("2026-dddd"));
789        let c = i.task("2026-cccc").unwrap();
790        assert_eq!(i.waits_on(c)[1], "qqqq (question open)");
791    }
792}