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        let ownership = crate::task_chat::InquiryOwnership::default();
285        while let Some(reference) = pending.pop() {
286            let full =
287                if queue.path_of(&reference).is_file() || questions.path_of(&reference).is_file() {
288                    reference
289                } else if inventory.complete {
290                    match crate::queue::resolve_reference(
291                        &reference,
292                        inventory.ids.iter().map(String::as_str),
293                    ) {
294                        crate::queue::Reference::Found(full) => full,
295                        _ => continue,
296                    }
297                } else {
298                    continue;
299                };
300            if !seen.insert(full.clone()) {
301                continue;
302            }
303            if queue.path_of(&full).is_file()
304                && let Ok(t) = queue.get(&full)
305            {
306                pending.extend(t.blocked_by.iter().cloned());
307                inventory.tasks.insert(full.clone(), t);
308            }
309            if questions.path_of(&full).is_file()
310                && let Ok(q) = questions.get_for_effects_in(&full, &ownership)
311            {
312                inventory.questions.insert(full, DecisionRecord::from(&q));
313            }
314        }
315        inventory
316    }
317
318    fn dep(&self, id: &str) -> Dep<'_> {
319        // A partial scan does not invalidate readable exact records. It does
320        // prevent proving that a prefix/suffix is unique across both stores.
321        if let Some(t) = self.tasks.get(id) {
322            return Dep::Task(t);
323        }
324        if let Some(s) = self.questions.get(id) {
325            return Dep::Question(s.status);
326        }
327        if !self.complete {
328            return Dep::Unknown;
329        }
330        match crate::queue::resolve_reference(id, self.ids.iter().map(String::as_str)) {
331            crate::queue::Reference::Found(full) => {
332                if let Some(t) = self.tasks.get(&full) {
333                    Dep::Task(t)
334                } else if let Some(s) = self.questions.get(&full) {
335                    Dep::Question(s.status)
336                } else {
337                    Dep::Unknown
338                }
339            }
340            crate::queue::Reference::Missing => Dep::Missing,
341            crate::queue::Reference::Ambiguous => Dep::Unknown,
342        }
343    }
344
345    /// A dependency that has nothing left to wait for.
346    fn resolved(&self, id: &str) -> bool {
347        match self.dep(id) {
348            Dep::Task(t) => t.status == TaskStatus::Done,
349            Dep::Question(s) => s == QuestionStatus::Answered,
350            Dep::Missing | Dep::Unknown => false,
351        }
352    }
353
354    fn walk(
355        &self,
356        id: &str,
357        path: &mut Vec<String>,
358        memo: &mut BTreeMap<String, Roots>,
359    ) -> (Roots, bool) {
360        if let Some(v) = memo.get(id) {
361            return (v.clone(), false);
362        }
363        let Some(task) = self.tasks.get(id) else {
364            return (None, false);
365        };
366        path.push(id.to_owned());
367        let mut roots = BTreeSet::new();
368        let mut moving = false;
369        let mut cyclic = false;
370        for b in &task.blocked_by {
371            match self.dep(b) {
372                Dep::Task(t) => match t.status {
373                    TaskStatus::Done => {}
374                    TaskStatus::Held => {
375                        roots.insert(t.id.clone());
376                    }
377                    TaskStatus::Blocked => {
378                        if let Some(pos) = path.iter().position(|p| p == &t.id) {
379                            // A cycle: its smallest id speaks for all of it, so
380                            // every entry point names the same root.
381                            if let Some(min) = path[pos..].iter().min() {
382                                roots.insert(min.clone());
383                            }
384                            cyclic = true;
385                        } else {
386                            let (sub, c) = self.walk(&t.id, path, memo);
387                            cyclic |= c;
388                            match sub {
389                                Some(r) => roots.extend(r),
390                                None => moving = true,
391                            }
392                        }
393                    }
394                    TaskStatus::Queued
395                    | TaskStatus::Running
396                    | TaskStatus::Failed
397                    | TaskStatus::Parked => {
398                        moving = true;
399                    }
400                },
401                Dep::Question(QuestionStatus::Answered) => {}
402                Dep::Question(_) | Dep::Missing | Dep::Unknown => moving = true,
403            }
404        }
405        path.pop();
406        let verdict = (!moving && !roots.is_empty()).then_some(roots);
407        if !cyclic {
408            memo.insert(id.to_owned(), verdict.clone());
409        }
410        (verdict, cyclic)
411    }
412
413    /// Every stuck `blocked` task, with the root ids it is frozen behind.
414    pub fn stuck(&self) -> BTreeMap<String, BTreeSet<String>> {
415        let mut memo = BTreeMap::new();
416        let mut out = BTreeMap::new();
417        for (id, t) in &self.tasks {
418            if t.status != TaskStatus::Blocked {
419                continue;
420            }
421            let (verdict, _) = self.walk(id, &mut Vec::new(), &mut memo);
422            if let Some(roots) = verdict {
423                out.insert(id.clone(), roots);
424            }
425        }
426        out
427    }
428
429    /// The roots `task` is frozen behind; empty when it is not stuck.
430    pub fn stuck_roots(&self, task: &Task) -> BTreeSet<String> {
431        if task.status != TaskStatus::Blocked {
432            return BTreeSet::new();
433        }
434        self.walk(&task.id, &mut Vec::new(), &mut BTreeMap::new())
435            .0
436            .unwrap_or_default()
437    }
438
439    /// Each dependency of `task` with its state, e.g. `9db7 (held)` or
440    /// `4135 (blocked → 9db7 held)`. Empty unless `task` is `blocked`.
441    pub fn waits_on(&self, task: &Task) -> Vec<String> {
442        if task.status != TaskStatus::Blocked {
443            return Vec::new();
444        }
445        task.blocked_by
446            .iter()
447            .map(|b| {
448                let chain = self.chain(b, &mut vec![task.id.clone()]);
449                format!("{} ({chain})", short(b))
450            })
451            .collect()
452    }
453
454    fn chain(&self, id: &str, seen: &mut Vec<String>) -> String {
455        match self.dep(id) {
456            Dep::Missing => "missing".to_owned(),
457            Dep::Unknown => "unavailable or ambiguous".to_owned(),
458            Dep::Question(s) => format!("question {}", s.as_str()),
459            Dep::Task(t) => {
460                let mut out = t.status.as_str().to_owned();
461                if t.status != TaskStatus::Blocked {
462                    return out;
463                }
464                if seen.iter().any(|s| s == &t.id) {
465                    return format!("{out}, cycle");
466                }
467                if seen.len() > CHAIN_DEPTH {
468                    return format!("{out} → …");
469                }
470                seen.push(t.id.clone());
471                if let Some(next) = t.blocked_by.iter().find(|b| !self.resolved(b)) {
472                    out.push_str(&format!(" → {} {}", short(next), self.chain(next, seen)));
473                }
474                out
475            }
476        }
477    }
478
479    /// The task with this id, if it is one.
480    pub fn task(&self, id: &str) -> Option<&Task> {
481        match self.dep(id) {
482            Dep::Task(t) => Some(t),
483            _ => None,
484        }
485    }
486}
487
488#[cfg(test)]
489mod tests {
490    use super::*;
491    use crate::queue::Source;
492    use std::path::PathBuf;
493
494    fn t(id: &str, status: TaskStatus, blocked_by: &[&str]) -> Task {
495        let mut t = Task::new(
496            id.to_owned(),
497            "x".to_owned(),
498            PathBuf::from("/repo"),
499            Source::Human,
500        );
501        t.id = format!("2026-{id}");
502        t.status = status;
503        t.blocked_by = blocked_by.iter().map(|b| format!("2026-{b}")).collect();
504        t
505    }
506
507    fn inv(tasks: Vec<Task>) -> Inventory {
508        Inventory::new(tasks, &[])
509    }
510
511    #[test]
512    fn blocker_views_preserve_all_dependencies_and_decision_delivery_states() {
513        let held = t("held", TaskStatus::Held, &[]);
514        let done = t("done", TaskStatus::Done, &[]);
515        let mut decision = Question::new(
516            "run".into(),
517            "node".into(),
518            "seat".into(),
519            "Choose recovery".into(),
520            "Context".into(),
521            vec![],
522        );
523        decision.routed_task = Some(held.id.clone());
524        let mut waiting = t("waiting", TaskStatus::Blocked, &["held", "done", "missing"]);
525        waiting.blocked_by.push(decision.id.clone());
526        let inventory = Inventory::new(
527            vec![held.clone(), done, waiting.clone()],
528            std::slice::from_ref(&decision),
529        );
530        let views = inventory.blocker_views(&waiting);
531        assert_eq!(views.len(), 4);
532        assert_eq!(views[0].destination, Some(("tasks", held.id.clone())));
533        assert!(!views[0].resolves_itself);
534        assert!(views[1].resolves_itself);
535        assert!(views[1].next.contains("reconcile"));
536        assert_eq!(views[2].state, "missing");
537        assert!(views[2].destination.is_none());
538        assert!(!views[2].resolves_itself);
539        assert!(!views[3].resolves_itself);
540        assert!(views[3].next.contains("delivery"));
541        assert!(views[3].destination.is_none());
542        assert!(inventory.blocker_views(&held).is_empty());
543        for status in [
544            QuestionStatus::Open,
545            QuestionStatus::Answered,
546            QuestionStatus::Abandoned,
547        ] {
548            decision.status = status;
549            decision.routed_chat = Some("owning-chat".into());
550            let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
551            let views = inventory.blocker_views(&waiting);
552            assert_eq!(views[3].resolves_itself, status == QuestionStatus::Answered);
553            assert_eq!(views[3].id, decision.id);
554            assert_eq!(views[3].destination, Some(("chat", "owning-chat".into())));
555            assert_eq!(views[3].reason.as_deref(), Some("Choose recovery"));
556        }
557        decision.routed_task = None;
558        decision.routed_chat = None;
559        decision.status = QuestionStatus::Open;
560        let inventory = Inventory::new(vec![waiting.clone()], std::slice::from_ref(&decision));
561        assert_eq!(
562            inventory.blocker_views(&waiting)[3].destination,
563            Some(("questions", decision.id))
564        );
565    }
566
567    #[test]
568    fn blocker_views_distinguish_automatic_progress_from_operator_recovery() {
569        for status in [
570            TaskStatus::Queued,
571            TaskStatus::Running,
572            TaskStatus::Failed,
573            TaskStatus::Parked,
574            TaskStatus::Done,
575            TaskStatus::Held,
576            TaskStatus::Blocked,
577        ] {
578            let dependency = t("dependency", status, &[]);
579            let waiting = t("waiting", TaskStatus::Blocked, &["dependency"]);
580            let inventory = inv(vec![dependency, waiting.clone()]);
581            let views = inventory.blocker_views(&waiting);
582            assert_eq!(
583                views[0].resolves_itself,
584                !matches!(status, TaskStatus::Held | TaskStatus::Blocked),
585                "{status:?}"
586            );
587            if status == TaskStatus::Running {
588                assert!(views[0].next.contains("No operator action"));
589            }
590        }
591        let waiting = t("waiting", TaskStatus::Blocked, &["waiting"]);
592        let inventory = inv(vec![waiting.clone()]);
593        let views = inventory.blocker_views(&waiting);
594        assert!(!views[0].resolves_itself);
595        assert!(views[0].next.contains("cycle"));
596    }
597
598    #[test]
599    fn blocker_views_do_not_link_ambiguous_unreadable_or_removed_records() {
600        let dir = tempfile::tempdir().unwrap();
601        let queue = crate::queue::Queue::at(dir.path().join("queue"));
602        let questions = crate::ask::Questions::at(dir.path().join("questions"));
603        let mut waiting = t("waiting", TaskStatus::Blocked, &[]);
604        waiting.blocked_by = vec!["collision".into(), "broken".into(), "removed".into()];
605        queue.put(&mut waiting).unwrap();
606        for name in [
607            "a-collision.json",
608            "b-collision.removed",
609            "broken.json",
610            "removed.removed",
611        ] {
612            std::fs::write(queue.root().join(name), "unreadable").unwrap();
613        }
614        let inventory = Inventory::load_for(&queue, &questions, &waiting);
615        let views = inventory.blocker_views(&waiting);
616        assert_eq!(views.len(), 3);
617        assert!(
618            views
619                .iter()
620                .all(|view| view.destination.is_none() && view.state == "unavailable or ambiguous")
621        );
622    }
623
624    #[test]
625    fn responsiveness_dependency_closure_matches_the_full_inventory() {
626        let dir = tempfile::tempdir().unwrap();
627        let queue = crate::queue::Queue::at(dir.path().join("queue"));
628        let questions = crate::ask::Questions::at(dir.path().join("questions"));
629        let mut held = t("held", TaskStatus::Held, &[]);
630        let mut middle = t("middle", TaskStatus::Blocked, &["held"]);
631        let mut waiting = t("waiting", TaskStatus::Blocked, &["middle"]);
632        for task in [&mut held, &mut middle, &mut waiting] {
633            queue.put(task).unwrap();
634        }
635        for n in 0..150 {
636            let mut unrelated = t(&format!("noise{n}"), TaskStatus::Done, &[]);
637            unrelated.instruction = "history ".repeat(4096);
638            queue.put(&mut unrelated).unwrap();
639        }
640        for reference in ["2026-middle", "middle", "missing", "collision"] {
641            waiting.blocked_by = vec![reference.into()];
642            queue.put(&mut waiting).unwrap();
643            std::fs::write(queue.root().join("a-collision.json"), "corrupt").unwrap();
644            std::fs::write(queue.root().join("b-collision.removed"), "removed").unwrap();
645            let full = Inventory::load(&queue, &questions);
646            let small = Inventory::load_for(&queue, &questions, &waiting);
647            assert_eq!(small.waits_on(&waiting), full.waits_on(&waiting));
648            assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
649            assert!(small.tasks.len() <= 3);
650        }
651        // A cycle uses the same recursion and root rules as the full inventory.
652        held.status = TaskStatus::Blocked;
653        held.blocked_by = vec![middle.id.clone()];
654        queue.put(&mut held).unwrap();
655        waiting.blocked_by = vec![middle.id.clone()];
656        queue.put(&mut waiting).unwrap();
657        let full = Inventory::load(&queue, &questions);
658        let small = Inventory::load_for(&queue, &questions, &waiting);
659        assert_eq!(small.stuck_roots(&waiting), full.stuck_roots(&waiting));
660    }
661
662    #[test]
663    fn dependency_resolution_partial_scan_keeps_readable_exact_records() {
664        let dir = tempfile::tempdir().unwrap();
665        let queue = crate::queue::Queue::at(dir.path().join("queue"));
666        let questions = crate::ask::Questions::at(dir.path().join("questions"));
667        let mut running = t("feb2", TaskStatus::Running, &[]);
668        let mut middle = t("ca5b", TaskStatus::Blocked, &["feb2"]);
669        let mut waiting = t("ee37", TaskStatus::Blocked, &["ca5b"]);
670        let mut held = t("held", TaskStatus::Held, &[]);
671        let mut short_wait = t("short", TaskStatus::Blocked, &[]);
672        short_wait.blocked_by = vec!["held".into()];
673        for task in [
674            &mut running,
675            &mut middle,
676            &mut waiting,
677            &mut held,
678            &mut short_wait,
679        ] {
680            queue.put(task).unwrap();
681        }
682        // Reading the queue succeeds, while scanning the question store fails.
683        std::fs::write(questions.root(), "not a directory").unwrap();
684        let inventory = Inventory::load(&queue, &questions);
685        assert!(!inventory.complete);
686        assert!(inventory.ids.contains(&running.id));
687        assert_eq!(
688            inventory.task(&running.id).unwrap().status,
689            TaskStatus::Running
690        );
691        assert_eq!(
692            inventory.waits_on(&waiting),
693            ["ca5b (blocked → feb2 running)"]
694        );
695        assert_eq!(
696            inventory.waits_on(&short_wait),
697            ["held (unavailable or ambiguous)"]
698        );
699        assert!(
700            inventory.stuck().is_empty(),
701            "partial scans cannot prove short-id uniqueness"
702        );
703        assert!(matches!(inventory.dep("not-seen"), Dep::Unknown));
704    }
705
706    #[test]
707    fn a_chain_reads_at_a_glance_and_its_root_is_the_held_task() {
708        let i = inv(vec![
709            t("9db7", TaskStatus::Held, &[]),
710            t("4135", TaskStatus::Blocked, &["9db7"]),
711            t("6081", TaskStatus::Blocked, &["4135"]),
712        ]);
713        let six = i.task("2026-6081").unwrap();
714        assert_eq!(i.waits_on(six), ["4135 (blocked → 9db7 held)"]);
715        let four = i.task("2026-4135").unwrap();
716        assert_eq!(i.waits_on(four), ["9db7 (held)"]);
717        let stuck = i.stuck();
718        assert_eq!(stuck.len(), 2);
719        assert!(stuck.values().all(|r| r.iter().eq(["2026-9db7"].iter())));
720    }
721
722    #[test]
723    fn a_dependency_that_can_still_run_is_not_stuck() {
724        let i = inv(vec![
725            t("aaaa", TaskStatus::Queued, &[]),
726            t("bbbb", TaskStatus::Held, &[]),
727            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
728            t("dddd", TaskStatus::Blocked, &["missing1"]),
729            t("eeee", TaskStatus::Blocked, &["cccc"]),
730        ]);
731        assert!(i.stuck().is_empty(), "{:?}", i.stuck());
732    }
733
734    #[test]
735    fn a_done_dependency_does_not_hide_a_held_one() {
736        let i = inv(vec![
737            t("aaaa", TaskStatus::Done, &[]),
738            t("bbbb", TaskStatus::Held, &[]),
739            t("cccc", TaskStatus::Blocked, &["aaaa", "bbbb"]),
740        ]);
741        assert_eq!(i.stuck().len(), 1);
742    }
743
744    #[test]
745    fn a_cycle_terminates_and_names_its_smallest_id_from_every_entry() {
746        let i = inv(vec![
747            t("bbbb", TaskStatus::Blocked, &["cccc"]),
748            t("cccc", TaskStatus::Blocked, &["aaaa"]),
749            t("aaaa", TaskStatus::Blocked, &["bbbb"]),
750            t("dddd", TaskStatus::Blocked, &["cccc"]),
751        ]);
752        let stuck = i.stuck();
753        assert_eq!(stuck.len(), 4);
754        for roots in stuck.values() {
755            assert!(roots.iter().eq(["2026-aaaa"].iter()), "{roots:?}");
756        }
757        let d = i.task("2026-dddd").unwrap();
758        assert!(i.waits_on(d)[0].contains("cycle"), "{:?}", i.waits_on(d));
759    }
760
761    #[test]
762    fn a_self_dependency_is_a_stuck_cycle_of_one() {
763        let i = inv(vec![t("aaaa", TaskStatus::Blocked, &["aaaa"])]);
764        assert_eq!(i.stuck().len(), 1);
765    }
766
767    #[test]
768    fn an_open_question_keeps_a_task_alive_and_an_answered_one_resolves() {
769        let mut open = Question::new(
770            "r".into(),
771            "n".into(),
772            "s".into(),
773            "?".into(),
774            String::new(),
775            vec![],
776        );
777        open.id = "2026-qqqq".into();
778        let mut answered = open.clone();
779        answered.id = "2026-rrrr".into();
780        answered.status = QuestionStatus::Answered;
781        let tasks = vec![
782            t("bbbb", TaskStatus::Held, &[]),
783            t("cccc", TaskStatus::Blocked, &["bbbb", "qqqq"]),
784            t("dddd", TaskStatus::Blocked, &["bbbb", "rrrr"]),
785        ];
786        let i = Inventory::new(tasks, &[open, answered]);
787        let stuck = i.stuck();
788        assert!(!stuck.contains_key("2026-cccc"));
789        assert!(stuck.contains_key("2026-dddd"));
790        let c = i.task("2026-cccc").unwrap();
791        assert_eq!(i.waits_on(c)[1], "qqqq (question open)");
792    }
793}