haz-cli 0.2.0

Command-line task runner: tracks task DAGs across a workspace of projects, executes them with caching.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
//! Interactive-tree state machine for `haz init` per
//! `AUX-003`..`AUX-005`.
//!
//! This module owns the pure data structures and state transitions
//! the interactive scaffold flow needs; the TUI runtime lives in a
//! sibling module and drives this model in response to keystrokes.
//! Keeping the model pure (no terminal IO, no filesystem reads)
//! makes the `AUX-004` rules exhaustively unit-testable.
//!
//! The model represents the cwd-rooted directory subtree as a
//! [`Node`] tree with per-node [`SelectionState`] and a single
//! focused position. Navigation, expansion, and state cycling are
//! all expressed as tree mutations; the driver re-renders the
//! [`Tree::visible_nodes`] list after each mutation.

use std::collections::BTreeSet;
use std::ffi::OsString;
use std::path::PathBuf;

/// Why a directory was treated as hidden by the TUI driver.
///
/// The model carries the classification per-node so the renderer
/// can style hidden rows distinctly when the user has toggled
/// "show hidden" on. Dotfile-prefixed entries dim normally;
/// gitignored entries dim with a warning-coloured foreground.
/// When both apply, `Gitignored` wins so the warning channel is
/// preserved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum HiddenKind {
    /// Default: not hidden, rendered normally.
    #[default]
    Visible,
    /// Basename starts with `.` (e.g. `.git`, `.cache`).
    Dotfile,
    /// Matched by the workspace's `.gitignore` (or the global
    /// gitignore) at the moment the directory was loaded.
    Gitignored,
}

/// One of the three selection states `AUX-003` defines for a
/// directory node. Cycling goes
/// `None` -> `Project` -> `ProjectsParent` -> `None`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SelectionState {
    /// Not referenced by `projects:` (default).
    #[default]
    None,
    /// Referenced as a literal `/<dir>` entry in `projects:`.
    Project,
    /// Referenced as a glob `/<dir>/*` entry in `projects:` per
    /// the `AUX-003` `projects-parent` arm.
    ProjectsParent,
}

impl SelectionState {
    /// The next state in the `AUX-003` cycle. Cycling out of
    /// `ProjectsParent` returns to `None`.
    #[must_use]
    pub fn next(self) -> Self {
        match self {
            Self::None => Self::Project,
            Self::Project => Self::ProjectsParent,
            Self::ProjectsParent => Self::None,
        }
    }
}

/// A single visible filesystem directory inside the interactive
/// tree.
///
/// The model does not represent regular files: per `AUX-003`,
/// only directories carry a selection state. File-system reads
/// happen in the TUI driver; the model is fed `Node` trees and
/// has no IO of its own.
#[derive(Debug, Clone)]
pub struct Node {
    /// Display label (the directory's basename).
    pub name: OsString,
    /// Workspace-absolute path of this directory (host filesystem
    /// path is computed by the driver before display).
    pub path: PathBuf,
    /// Current selection state per `AUX-003`.
    pub state: SelectionState,
    /// Whether the node is currently expanded (its children are
    /// part of the visible list).
    pub expanded: bool,
    /// Whether [`Self::children`] has been populated from disk.
    /// `false` for a directory whose contents have never been
    /// loaded; cycling into [`SelectionState::ProjectsParent`]
    /// requires this to be `true` (the empty-glob check needs to
    /// know whether subdirectories exist).
    pub children_loaded: bool,
    /// Sub-directory nodes in the order the driver loaded them.
    pub children: Vec<Node>,
    /// How this directory was classified at read time. Defaults
    /// to [`HiddenKind::Visible`]; the TUI driver overwrites it
    /// for entries it loaded while "show hidden" was on.
    pub hidden_kind: HiddenKind,
}

impl Node {
    /// Construct a directory node with no children loaded yet.
    #[must_use]
    pub fn new(name: OsString, path: PathBuf) -> Self {
        Self {
            name,
            path,
            state: SelectionState::default(),
            expanded: false,
            children_loaded: false,
            children: Vec::new(),
            hidden_kind: HiddenKind::default(),
        }
    }

    /// Whether this node has at least one direct subdirectory.
    ///
    /// Used by [`Tree::cycle_focused`] to evaluate `AUX-004`
    /// rule 1 (empty-glob refusal). The caller MUST have loaded
    /// children first (`children_loaded == true`); calling on an
    /// unloaded node returns `false` conservatively, which lets
    /// the driver decide whether to trigger a load.
    #[must_use]
    pub fn has_subdirectories(&self) -> bool {
        self.children_loaded && !self.children.is_empty()
    }
}

/// Outcome of an attempted [`Tree::cycle_focused`] call.
///
/// `AUX-004` defines two refusal cases; cycling outside those
/// constraints succeeds and returns the new state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CycleOutcome {
    /// The cycle succeeded; the focused node's new state is the
    /// carried value.
    Advanced(SelectionState),
    /// `AUX-004` rule 1: the focused node has no subdirectories,
    /// so cycling *into* [`SelectionState::ProjectsParent`] is
    /// refused. The previous state is preserved.
    RefusedEmptyGlob,
    /// `AUX-004` rule 2: the focused node lies under an ancestor
    /// in [`SelectionState::ProjectsParent`], so cycling is
    /// refused while the lock holds. The focused node's state
    /// is left unchanged; under the rule 2 invariant the locked
    /// descendant is always [`SelectionState::None`].
    RefusedSubtreeLock,
    /// The focused node's children have not been loaded yet, so
    /// the rule 1 check cannot be evaluated. The driver MUST
    /// load children and re-issue the cycle. The previous state
    /// is preserved.
    NeedsChildrenLoaded,
}

/// Outcome of an attempted [`Tree::try_expand_focused`] call.
///
/// Expanding a directory whose `children` list (after loading)
/// is empty is refused, mirroring the AUX-004 rule 1 refusal on
/// the selection cycle: the user expects "expand" to do
/// something visible, and silently changing `expanded` on an
/// empty directory does not.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ExpandOutcome {
    /// The focused node has subdirectories and is now expanded.
    Expanded,
    /// The focused node was already expanded. No-op.
    AlreadyExpanded,
    /// The focused node has zero subdirectories. The expansion
    /// is refused; `expanded` stays at its previous value
    /// (false), and the driver fires the perceptible refusal
    /// signal.
    RefusedNoSubdirs,
    /// The focused node's children have not been loaded yet.
    /// The driver MUST load them and re-issue the expand
    /// request.
    NeedsChildrenLoaded,
}

/// The interactive-tree state.
///
/// Carries the root [`Node`] plus the focus path (a sequence of
/// indices from the root to the currently-focused node).
#[derive(Debug, Clone)]
pub struct Tree {
    root: Node,
    focus_path: Vec<usize>,
}

impl Tree {
    /// Build a tree from a pre-populated root.
    #[must_use]
    pub fn new(root: Node) -> Self {
        Self {
            root,
            focus_path: Vec::new(),
        }
    }

    /// Borrow the root node.
    #[must_use]
    pub fn root(&self) -> &Node {
        &self.root
    }

    /// Borrow the focused node.
    #[must_use]
    pub fn focused(&self) -> &Node {
        let mut node = &self.root;
        for &idx in &self.focus_path {
            node = &node.children[idx];
        }
        node
    }

    /// Cycle the focused node's [`SelectionState`] per `AUX-003`,
    /// subject to the `AUX-004` refusal rules.
    ///
    /// On a directory with zero sub-directories, `ProjectsParent`
    /// is unreachable per `AUX-004` rule 1. The cycle continues
    /// to the state that would come after it (`None`) so the
    /// user can always escape `Project`; the return value
    /// [`CycleOutcome::RefusedEmptyGlob`] tells the driver to
    /// fire the perceptible refusal channel the rule mandates.
    ///
    /// Cycling INTO `ProjectsParent` clears every descendant's
    /// selection state to `None` per `AUX-004` rule 2. Without
    /// the clear, the commit pass could emit a `projects:` list
    /// that mixes the glob with a literal entry the glob already
    /// shadows. The clearing is one-way: cycling back out of
    /// `ProjectsParent` does NOT restore prior descendant states.
    pub fn cycle_focused(&mut self) -> CycleOutcome {
        if self.focused_under_projects_parent_ancestor() {
            return CycleOutcome::RefusedSubtreeLock;
        }
        let current = self.focused().state;
        let next = current.next();
        if next == SelectionState::ProjectsParent {
            if !self.focused().children_loaded {
                return CycleOutcome::NeedsChildrenLoaded;
            }
            if !self.focused().has_subdirectories() {
                let after = next.next();
                self.focused_mut().state = after;
                return CycleOutcome::RefusedEmptyGlob;
            }
        }
        let focused = self.focused_mut();
        focused.state = next;
        if next == SelectionState::ProjectsParent {
            clear_descendant_states(focused);
        }
        CycleOutcome::Advanced(next)
    }

    /// Move focus to the next visible node (down arrow).
    ///
    /// "Next" walks the visible-nodes list in depth-first order;
    /// at the tail it wraps to the head, which makes long lists
    /// navigable without explicit "back to top" UI.
    pub fn focus_next(&mut self) {
        let total = self.visible_count();
        if total == 0 {
            return;
        }
        let current = self.focused_index();
        let next = (current + 1) % total;
        self.set_focused_index(next);
    }

    /// Move focus to the previous visible node (up arrow). Wraps
    /// at the head per the symmetric rule of [`Self::focus_next`].
    pub fn focus_prev(&mut self) {
        let total = self.visible_count();
        if total == 0 {
            return;
        }
        let current = self.focused_index();
        let prev = if current == 0 { total - 1 } else { current - 1 };
        self.set_focused_index(prev);
    }

    /// Try to expand the focused node, reporting why the
    /// expansion did or did not take effect. The TUI driver uses
    /// the outcome to decide whether to ring the bell, set a
    /// refusal status message, or trigger a disk read.
    pub fn try_expand_focused(&mut self) -> ExpandOutcome {
        let node = self.focused();
        if node.expanded {
            return ExpandOutcome::AlreadyExpanded;
        }
        if !node.children_loaded {
            return ExpandOutcome::NeedsChildrenLoaded;
        }
        if node.children.is_empty() {
            return ExpandOutcome::RefusedNoSubdirs;
        }
        self.focused_mut().expanded = true;
        ExpandOutcome::Expanded
    }

    /// Collapse the focused node. No-op when not currently
    /// expanded. The node's state and the states of its
    /// descendants are preserved across collapse / expand cycles.
    pub fn collapse_focused(&mut self) {
        self.focused_mut().expanded = false;
    }

    /// Whether the focused node's children need to be loaded
    /// before the next [`Self::cycle_focused`] call can evaluate
    /// the `AUX-004` rule 1 empty-glob refusal.
    #[must_use]
    pub fn focused_needs_children_loaded(&self) -> bool {
        !self.focused().children_loaded
    }

    /// Replace the focused node's children with the supplied list
    /// and mark its `children_loaded` flag. Called by the TUI
    /// driver after a `read_dir` populates the directory contents
    /// the model needs.
    pub fn populate_focused_children(&mut self, children: Vec<Node>) {
        let node = self.focused_mut();
        node.children = children;
        node.children_loaded = true;
    }

    /// Iterate every currently-visible node in depth-first order
    /// (root, then expanded children recursively). Each entry
    /// carries the node's depth (root = 0), a focus marker, and a
    /// lock flag indicating whether the node is currently
    /// subject to the `AUX-004` rule 2 sub-tree lockout.
    #[must_use]
    pub fn visible_nodes(&self) -> Vec<VisibleNode<'_>> {
        let mut out: Vec<VisibleNode<'_>> = Vec::new();
        walk_visible(
            &self.root,
            &mut Vec::new(),
            &self.focus_path,
            false,
            0,
            &mut out,
        );
        out
    }

    /// Compute the `AUX-005` step 1 project-root set: every
    /// directory currently in [`SelectionState::Project`], plus
    /// every direct subdirectory of every directory currently in
    /// [`SelectionState::ProjectsParent`].
    ///
    /// The result is ordered (`BTreeSet`) so the
    /// `AUX-005` step 3 summary and the `workspace.yml`
    /// emission are byte-stable across runs.
    #[must_use]
    pub fn project_root_set(&self) -> BTreeSet<PathBuf> {
        let mut out: BTreeSet<PathBuf> = BTreeSet::new();
        collect_roots(&self.root, &mut out);
        out
    }

    /// Index of the focused node in the visible list (the result
    /// of [`Self::visible_nodes`]). The TUI driver uses this to
    /// reason about navigation positions across the synthetic
    /// commit-button row that lives outside the model.
    #[must_use]
    pub fn focused_visible_index(&self) -> usize {
        self.focused_index()
    }

    /// Move focus to the node at position `target` in the visible
    /// list. Panics when `target` is out of range; the TUI driver
    /// always clamps to `[0, visible_nodes().len())` before
    /// calling.
    pub fn focus_at_visible_index(&mut self, target: usize) {
        self.set_focused_index(target);
    }

    /// Mutable borrow of the root node. The TUI driver uses this
    /// to walk the tree and re-read directory children when the
    /// visibility filter (`H` toggle) changes.
    pub fn root_mut(&mut self) -> &mut Node {
        &mut self.root
    }

    /// Replace the focus path with `path`, defaulting to root
    /// (`[]`) when `path` does not identify a visible node
    /// (out-of-range child index, or any ancestor along the path
    /// is collapsed). Used by the TUI driver after a reload that
    /// may have shifted or removed the previously-focused node.
    pub fn set_focus_path(&mut self, path: Vec<usize>) {
        if Self::is_valid_visible_path(&self.root, &path) {
            self.focus_path = path;
        } else {
            self.focus_path = Vec::new();
        }
    }

    fn is_valid_visible_path(root: &Node, path: &[usize]) -> bool {
        let mut node = root;
        for &idx in path {
            if !node.expanded || idx >= node.children.len() {
                return false;
            }
            node = &node.children[idx];
        }
        true
    }

    // --- internals ---

    fn focused_mut(&mut self) -> &mut Node {
        let mut node = &mut self.root;
        for &idx in &self.focus_path {
            node = &mut node.children[idx];
        }
        node
    }

    fn focused_under_projects_parent_ancestor(&self) -> bool {
        let mut node = &self.root;
        for &idx in &self.focus_path {
            // The check inspects strict ancestors; the focused
            // node itself does NOT count.
            if node.state == SelectionState::ProjectsParent {
                return true;
            }
            node = &node.children[idx];
        }
        false
    }

    fn visible_count(&self) -> usize {
        self.visible_nodes().len()
    }

    fn focused_index(&self) -> usize {
        // The visible-nodes list always starts at the root, so
        // the focused index equals the position the same focus
        // path produces during the visible walk. We compute it
        // by re-walking the tree and counting nodes until we
        // encounter the focused one.
        let mut count = 0usize;
        find_index(&self.root, &mut Vec::new(), &self.focus_path, &mut count)
            .expect("focus path must always identify a visible node")
    }

    fn set_focused_index(&mut self, target: usize) {
        let mut count = 0usize;
        let mut path: Vec<usize> = Vec::new();
        find_path_at_index(&self.root, &mut path, target, &mut count)
            .expect("target index in [0, visible_count) is always reachable");
        self.focus_path = path;
    }
}

/// A node currently visible in the tree view, paired with its
/// depth and `AUX-004`-rule-2 lockout flag.
#[derive(Debug, Clone, Copy)]
pub struct VisibleNode<'a> {
    /// The node itself.
    pub node: &'a Node,
    /// Depth from the root (0 for the root).
    pub depth: usize,
    /// Whether this node is the currently-focused one.
    pub focused: bool,
    /// Whether this node is subject to the `AUX-004` rule 2
    /// sub-tree lockout because some strict ancestor is in
    /// [`SelectionState::ProjectsParent`].
    pub locked: bool,
}

// --- free helpers --------------------------------------------

fn walk_visible<'a>(
    node: &'a Node,
    here: &mut Vec<usize>,
    focus: &[usize],
    inherited_lock: bool,
    depth: usize,
    out: &mut Vec<VisibleNode<'a>>,
) {
    let focused = here.as_slice() == focus;
    out.push(VisibleNode {
        node,
        depth,
        focused,
        locked: inherited_lock,
    });
    if !node.expanded {
        return;
    }
    let child_lock = inherited_lock || node.state == SelectionState::ProjectsParent;
    for (i, child) in node.children.iter().enumerate() {
        here.push(i);
        walk_visible(child, here, focus, child_lock, depth + 1, out);
        here.pop();
    }
}

fn clear_descendant_states(node: &mut Node) {
    for child in &mut node.children {
        child.state = SelectionState::None;
        clear_descendant_states(child);
    }
}

fn collect_roots(node: &Node, out: &mut BTreeSet<PathBuf>) {
    match node.state {
        SelectionState::None => {}
        SelectionState::Project => {
            out.insert(node.path.clone());
        }
        SelectionState::ProjectsParent => {
            for child in &node.children {
                out.insert(child.path.clone());
            }
        }
    }
    for child in &node.children {
        collect_roots(child, out);
    }
}

fn find_index(
    node: &Node,
    here: &mut Vec<usize>,
    focus: &[usize],
    count: &mut usize,
) -> Option<usize> {
    if here.as_slice() == focus {
        return Some(*count);
    }
    *count += 1;
    if !node.expanded {
        return None;
    }
    for (i, child) in node.children.iter().enumerate() {
        here.push(i);
        if let Some(found) = find_index(child, here, focus, count) {
            return Some(found);
        }
        here.pop();
    }
    None
}

fn find_path_at_index(
    node: &Node,
    path: &mut Vec<usize>,
    target: usize,
    count: &mut usize,
) -> Option<()> {
    if *count == target {
        return Some(());
    }
    *count += 1;
    if !node.expanded {
        return None;
    }
    for (i, child) in node.children.iter().enumerate() {
        path.push(i);
        if find_path_at_index(child, path, target, count).is_some() {
            return Some(());
        }
        path.pop();
    }
    None
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeSet;
    use std::ffi::OsString;
    use std::path::PathBuf;

    use super::{CycleOutcome, ExpandOutcome, Node, SelectionState, Tree, VisibleNode};

    fn dir(name: &str, path: &str) -> Node {
        Node::new(OsString::from(name), PathBuf::from(path))
    }

    fn loaded_dir(name: &str, path: &str, children: Vec<Node>) -> Node {
        let mut node = dir(name, path);
        node.children = children;
        node.children_loaded = true;
        node
    }

    fn loaded_empty(name: &str, path: &str) -> Node {
        loaded_dir(name, path, Vec::new())
    }

    fn visible_paths(vn: &[VisibleNode<'_>]) -> Vec<PathBuf> {
        vn.iter().map(|v| v.node.path.clone()).collect()
    }

    fn pb(s: &str) -> PathBuf {
        PathBuf::from(s)
    }

    fn pbs(paths: &[&str]) -> BTreeSet<PathBuf> {
        paths.iter().map(|s| pb(s)).collect()
    }

    // --- SelectionState::next cycles in the documented order ---

    #[test]
    fn selection_state_cycles_none_project_projects_parent_none() {
        assert_eq!(SelectionState::None.next(), SelectionState::Project);
        assert_eq!(
            SelectionState::Project.next(),
            SelectionState::ProjectsParent,
        );
        assert_eq!(SelectionState::ProjectsParent.next(), SelectionState::None);
    }

    // --- visible_nodes lists the root, then expanded children ---

    #[test]
    fn visible_nodes_lists_only_root_when_unexpanded() {
        let tree = Tree::new(dir("root", "/"));
        let vis = tree.visible_nodes();
        assert_eq!(vis.len(), 1);
        assert_eq!(vis[0].node.name, OsString::from("root"));
        assert_eq!(vis[0].depth, 0);
        assert!(vis[0].focused);
    }

    #[test]
    fn visible_nodes_includes_children_when_root_expanded() {
        let mut root = loaded_dir(
            "root",
            "/",
            vec![loaded_empty("lib", "/lib"), loaded_empty("web", "/web")],
        );
        root.expanded = true;
        let tree = Tree::new(root);
        let vis = tree.visible_nodes();
        assert_eq!(visible_paths(&vis), vec![pb("/"), pb("/lib"), pb("/web")]);
        assert_eq!(
            vis.iter().map(|v| v.depth).collect::<Vec<_>>(),
            vec![0, 1, 1]
        );
    }

    #[test]
    fn collapse_hides_descendants_without_dropping_their_state() {
        let mut root = loaded_dir("root", "/", vec![loaded_empty("lib", "/lib")]);
        root.expanded = true;
        root.children[0].state = SelectionState::Project;
        let mut tree = Tree::new(root);
        tree.focus_next(); // focus lib (depth 1)
        tree.set_focused_to_root_for_test();
        tree.collapse_focused();
        let vis = tree.visible_nodes();
        assert_eq!(visible_paths(&vis), vec![pb("/")]);
        // Re-expand: descendant state preserved.
        assert_eq!(tree.try_expand_focused(), ExpandOutcome::Expanded);
        let vis = tree.visible_nodes();
        assert_eq!(vis[1].node.state, SelectionState::Project);
    }

    // --- focus navigation ---

    #[test]
    fn focus_next_walks_visible_list_then_wraps_to_root() {
        let mut root = loaded_dir(
            "root",
            "/",
            vec![loaded_empty("a", "/a"), loaded_empty("b", "/b")],
        );
        root.expanded = true;
        let mut tree = Tree::new(root);
        assert_eq!(tree.focused().path, pb("/"));
        tree.focus_next();
        assert_eq!(tree.focused().path, pb("/a"));
        tree.focus_next();
        assert_eq!(tree.focused().path, pb("/b"));
        tree.focus_next(); // wraps
        assert_eq!(tree.focused().path, pb("/"));
    }

    #[test]
    fn focus_prev_wraps_from_root_to_last_visible_node() {
        let mut root = loaded_dir(
            "root",
            "/",
            vec![loaded_empty("a", "/a"), loaded_empty("b", "/b")],
        );
        root.expanded = true;
        let mut tree = Tree::new(root);
        tree.focus_prev();
        assert_eq!(tree.focused().path, pb("/b"));
    }

    // --- AUX-003 cycle on the focused node ---

    #[test]
    fn aux_003_cycle_focused_advances_none_to_project() {
        let tree_root = loaded_empty("root", "/");
        let mut tree = Tree::new(tree_root);
        let outcome = tree.cycle_focused();
        assert_eq!(outcome, CycleOutcome::Advanced(SelectionState::Project));
        assert_eq!(tree.focused().state, SelectionState::Project);
    }

    #[test]
    fn aux_003_cycle_focused_advances_project_to_projects_parent_when_subdirs_exist() {
        let root = loaded_dir(
            "root",
            "/",
            vec![loaded_empty("a", "/a"), loaded_empty("b", "/b")],
        );
        let mut tree = Tree::new(root);
        tree.cycle_focused(); // -> Project
        let outcome = tree.cycle_focused();
        assert_eq!(
            outcome,
            CycleOutcome::Advanced(SelectionState::ProjectsParent),
        );
    }

    #[test]
    fn aux_003_cycle_focused_advances_projects_parent_back_to_none() {
        let root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        let mut tree = Tree::new(root);
        tree.cycle_focused(); // -> Project
        tree.cycle_focused(); // -> ProjectsParent
        let outcome = tree.cycle_focused();
        assert_eq!(outcome, CycleOutcome::Advanced(SelectionState::None));
    }

    // --- try_expand_focused outcomes -----------------------------

    #[test]
    fn try_expand_succeeds_on_directory_with_subdirectories() {
        let root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        let mut tree = Tree::new(root);
        assert!(!tree.focused().expanded);
        assert_eq!(tree.try_expand_focused(), ExpandOutcome::Expanded);
        assert!(tree.focused().expanded);
    }

    #[test]
    fn try_expand_returns_already_expanded_when_open() {
        let mut root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        root.expanded = true;
        let mut tree = Tree::new(root);
        assert_eq!(tree.try_expand_focused(), ExpandOutcome::AlreadyExpanded);
    }

    #[test]
    fn try_expand_refuses_when_no_subdirectories() {
        // A loaded leaf MUST NOT expand: there is nothing to
        // reveal. The expansion is refused and `expanded` stays
        // false; the TUI driver fires the refusal signal.
        let tree_root = loaded_empty("root", "/");
        let mut tree = Tree::new(tree_root);
        assert!(!tree.focused().expanded);
        assert_eq!(tree.try_expand_focused(), ExpandOutcome::RefusedNoSubdirs);
        assert!(!tree.focused().expanded);
    }

    #[test]
    fn try_expand_signals_needs_load_when_children_unknown() {
        let root = dir("root", "/");
        let mut tree = Tree::new(root);
        assert!(!tree.focused().children_loaded);
        assert_eq!(
            tree.try_expand_focused(),
            ExpandOutcome::NeedsChildrenLoaded
        );
        assert!(!tree.focused().expanded);
    }

    // --- AUX-004 rule 1: empty-glob refusal ---

    #[test]
    fn aux_004_rule_1_skips_projects_parent_when_no_subdirectories() {
        // On a leaf, ProjectsParent is unreachable; the cycle
        // continues past it to None so the user can always
        // escape Project. The RefusedEmptyGlob outcome tells the
        // driver to fire the AUX-004 rule 1 refusal signal.
        let tree_root = loaded_empty("root", "/");
        let mut tree = Tree::new(tree_root);
        tree.cycle_focused(); // -> Project
        let outcome = tree.cycle_focused();
        assert_eq!(outcome, CycleOutcome::RefusedEmptyGlob);
        assert_eq!(tree.focused().state, SelectionState::None);
    }

    #[test]
    fn aux_004_rule_1_request_signals_needs_load_when_children_unknown() {
        let mut root = dir("root", "/");
        // not loaded: children_loaded = false.
        root.state = SelectionState::Project;
        let mut tree = Tree::new(root);
        let outcome = tree.cycle_focused();
        assert_eq!(outcome, CycleOutcome::NeedsChildrenLoaded);
        // The state was NOT changed.
        assert_eq!(tree.focused().state, SelectionState::Project);
    }

    #[test]
    fn populate_focused_children_marks_children_loaded() {
        let root = dir("root", "/");
        let mut tree = Tree::new(root);
        assert!(tree.focused_needs_children_loaded());
        tree.populate_focused_children(vec![loaded_empty("a", "/a")]);
        assert!(!tree.focused_needs_children_loaded());
        assert_eq!(tree.focused().children.len(), 1);
    }

    // --- AUX-004 rule 2: sub-tree lockout ---

    #[test]
    fn aux_004_rule_2_lockout_refuses_cycle_when_ancestor_is_projects_parent() {
        let mut root = loaded_dir(
            "root",
            "/",
            vec![loaded_dir(
                "lib",
                "/lib",
                vec![loaded_empty("src", "/lib/src")],
            )],
        );
        root.expanded = true;
        root.children[0].expanded = true;
        root.children[0].state = SelectionState::ProjectsParent;
        let mut tree = Tree::new(root);
        // Move focus to lib/src.
        tree.focus_next(); // lib
        tree.focus_next(); // lib/src
        let outcome = tree.cycle_focused();
        assert_eq!(outcome, CycleOutcome::RefusedSubtreeLock);
        assert_eq!(tree.focused().state, SelectionState::None);
    }

    #[test]
    fn aux_004_rule_2_cycling_into_projects_parent_clears_direct_child_state() {
        // /lib/src holds Project when /lib cycles from Project
        // into ProjectsParent. Without the clear, /lib/* would
        // appear in workspace.yml alongside the shadowed literal
        // /lib/src. After the cycle, /lib/src MUST be None.
        let mut src = loaded_empty("src", "/lib/src");
        src.state = SelectionState::Project;
        let lib = loaded_dir("lib", "/lib", vec![src]);
        let mut root = loaded_dir("root", "/", vec![lib]);
        root.expanded = true;
        let mut tree = Tree::new(root);
        tree.focus_next(); // lib
        assert_eq!(
            tree.cycle_focused(),
            CycleOutcome::Advanced(SelectionState::Project),
        );
        // At this point /lib is Project; /lib/src is still Project.
        assert_eq!(tree.focused().children[0].state, SelectionState::Project);
        // The second cycle moves /lib into ProjectsParent and
        // clears /lib/src.
        assert_eq!(
            tree.cycle_focused(),
            CycleOutcome::Advanced(SelectionState::ProjectsParent),
        );
        assert_eq!(tree.focused().state, SelectionState::ProjectsParent);
        assert_eq!(tree.focused().children[0].state, SelectionState::None);
    }

    #[test]
    fn aux_004_rule_2_clearing_recurses_through_subtree() {
        // /a/b/c holds Project when /a cycles into ProjectsParent.
        // The clear MUST cover transitive descendants, not just
        // direct children: nested literals inside the glob's
        // implicit project roots are as bad as redundant direct
        // ones.
        let mut c = loaded_empty("c", "/a/b/c");
        c.state = SelectionState::Project;
        let mut b = loaded_dir("b", "/a/b", vec![c]);
        b.state = SelectionState::Project;
        let a = loaded_dir("a", "/a", vec![b]);
        let mut root = loaded_dir("root", "/", vec![a]);
        root.expanded = true;
        let mut tree = Tree::new(root);
        tree.focus_next(); // /a
        tree.cycle_focused(); // -> Project
        tree.cycle_focused(); // -> ProjectsParent
        assert_eq!(tree.focused().state, SelectionState::ProjectsParent);
        assert_eq!(tree.focused().children[0].state, SelectionState::None);
        assert_eq!(
            tree.focused().children[0].children[0].state,
            SelectionState::None,
        );
    }

    #[test]
    fn aux_004_rule_2_clearing_is_one_way_on_cycle_out() {
        // After the parent cycles back out of ProjectsParent, the
        // descendants stay None: the clear is destructive by
        // design. The user re-selects from scratch.
        let mut child = loaded_empty("child", "/parent/child");
        child.state = SelectionState::Project;
        let parent = loaded_dir("parent", "/parent", vec![child]);
        let mut root = loaded_dir("root", "/", vec![parent]);
        root.expanded = true;
        let mut tree = Tree::new(root);
        tree.focus_next(); // /parent
        tree.cycle_focused(); // -> Project
        tree.cycle_focused(); // -> ProjectsParent (clears child)
        tree.cycle_focused(); // -> None (no restore)
        assert_eq!(tree.focused().state, SelectionState::None);
        assert_eq!(tree.focused().children[0].state, SelectionState::None);
    }

    #[test]
    fn aux_004_rule_2_descendants_marked_locked_in_visible_nodes() {
        let mut lib = loaded_dir("lib", "/lib", vec![loaded_empty("src", "/lib/src")]);
        lib.state = SelectionState::ProjectsParent;
        lib.expanded = true;
        let mut root = loaded_dir("root", "/", vec![lib]);
        root.expanded = true;
        let tree = Tree::new(root);
        let vis = tree.visible_nodes();
        // root is not locked; lib is not locked (it IS the
        // projects-parent itself); lib/src IS locked.
        assert!(!vis[0].locked, "root not locked");
        assert!(!vis[1].locked, "lib itself is not locked");
        assert!(vis[2].locked, "lib/src locked under lib");
    }

    // --- AUX-005 step 1: project-root set ---

    #[test]
    fn aux_005_project_root_set_collects_project_nodes() {
        let mut a = loaded_empty("a", "/a");
        a.state = SelectionState::Project;
        let mut b = loaded_empty("b", "/b");
        b.state = SelectionState::Project;
        let mut root = loaded_dir("root", "/", vec![a, b]);
        root.expanded = true;
        let tree = Tree::new(root);
        assert_eq!(tree.project_root_set(), pbs(&["/a", "/b"]));
    }

    #[test]
    fn aux_005_project_root_set_expands_projects_parent_to_direct_subdirs() {
        let mut apps = loaded_dir(
            "apps",
            "/apps",
            vec![
                loaded_empty("api", "/apps/api"),
                loaded_empty("web", "/apps/web"),
            ],
        );
        apps.state = SelectionState::ProjectsParent;
        apps.expanded = true;
        let mut root = loaded_dir("root", "/", vec![apps]);
        root.expanded = true;
        let tree = Tree::new(root);
        assert_eq!(tree.project_root_set(), pbs(&["/apps/api", "/apps/web"]),);
    }

    #[test]
    fn aux_005_project_root_set_mixes_project_and_projects_parent() {
        let mut lib = loaded_empty("lib", "/lib");
        lib.state = SelectionState::Project;
        let mut apps = loaded_dir("apps", "/apps", vec![loaded_empty("api", "/apps/api")]);
        apps.state = SelectionState::ProjectsParent;
        let mut root = loaded_dir("root", "/", vec![lib, apps]);
        root.expanded = true;
        let tree = Tree::new(root);
        assert_eq!(tree.project_root_set(), pbs(&["/apps/api", "/lib"]),);
    }

    #[test]
    fn aux_005_project_root_set_is_empty_when_nothing_selected() {
        let tree = Tree::new(loaded_empty("root", "/"));
        assert!(tree.project_root_set().is_empty());
    }

    // ---- helpers used only in tests ------------------------------

    impl Tree {
        fn set_focused_to_root_for_test(&mut self) {
            self.focus_path.clear();
        }
    }
}