haz-cli 0.1.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
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
//! Interactive scaffold TUI for `haz init` per
//! `AUX-003`..`AUX-005`.
//!
//! Two layers live here:
//!
//! - [`dispatch`] is a pure function from a crossterm event and a
//!   [`TuiState`] to a [`DispatchResult`]. It mutates the state
//!   in-place and performs no IO; the side effects the driver
//!   needs to perform (loading children from disk, leaving the
//!   tree screen to commit) are returned as enum variants. The
//!   purity makes every key binding exhaustively unit-testable
//!   without a terminal.
//! - [`run_interactive_scaffold`] is the IO-driven loop that owns
//!   the terminal: it sets up raw mode + the alternate screen,
//!   draws each frame, reads events, calls [`dispatch`], and
//!   performs the IO actions the dispatcher requests.
//!
//! The screen layout is a single navigable tree with a synthetic
//! `[ Commit selection ]` button just below it; pressing `Enter`
//! from any focus position commits, while arrow / space cycle
//! state for tree rows.
//!
//! Hidden-directory handling: by default the tree omits
//! dotfile-prefixed entries (`.git`, `.cache`, ...) and entries
//! matched by the cwd's `.gitignore` (and git's global excludes).
//! `H` toggles their visibility; when shown, dotfile rows render
//! dim and gitignored rows render dim with a warning-coloured
//! foreground so the user can still distinguish them from
//! ordinary content. The classification is captured per-row via
//! [`super::model::HiddenKind`].

use std::ffi::OsString;
use std::fs;
use std::io::{self, Stdout, Write};
use std::path::{Path, PathBuf};

use crossterm::{
    event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
    execute,
    terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ignore::gitignore::{Gitignore, GitignoreBuilder};
use miette::{IntoDiagnostic, Result, WrapErr, miette};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::{Constraint, Direction, Layout, Rect};
use ratatui::style::{Color, Modifier, Style, Stylize};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, List, ListItem, ListState, Paragraph, Wrap};
use ratatui::{Frame, TerminalOptions, Viewport};

use super::commit::{CommitPlan, plan_commit};
use super::model::{
    CycleOutcome, ExpandOutcome, HiddenKind, Node, SelectionState, Tree, VisibleNode,
};

/// What the dispatcher's caller (the driver loop) should do next.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DispatchResult {
    /// Stay in the loop: redraw, then read another event.
    Continue,
    /// The driver reads the focused node's children and then
    /// retries the expand in the same keystroke. Used when Right
    /// was pressed on a directory whose children were not yet
    /// loaded: without the retry, the keypress would silently
    /// flip `expanded` (or do nothing for an empty directory)
    /// without giving the user the AUX-004-style refusal signal
    /// the empty case warrants.
    LoadChildrenThenRetryExpand,
    /// The driver reads the focused node's children and then
    /// retries `cycle_focused` in the same keystroke. Used when
    /// Space was pressed on a node whose children were not yet
    /// loaded: without the retry the keypress would only do a
    /// silent `read_dir` and the user would see "nothing happen".
    LoadChildrenThenRetryCycle,
    /// The user toggled `hidden_visible` and the tree's
    /// currently-loaded subtrees must be re-read against the new
    /// filter so the visual state matches the flag. The driver
    /// walks every already-loaded directory, re-reads its
    /// children with the new visibility, preserves
    /// expanded/state by basename, then re-anchors focus.
    ReloadTreeForVisibility,
    /// Leave the tree screen and move to the commit pass.
    ExitCommit,
    /// User declined the scaffold (`q` / `Esc`). Exit cleanly.
    ExitCancel,
    /// User aborted (`Ctrl+C`). Exit with the signal-interrupt
    /// code.
    Abort,
}

/// Final outcome of the scaffold flow as far as the executor is
/// concerned.
#[derive(Debug)]
pub enum ScaffoldOutcome {
    /// User confirmed the plan. Apply it.
    Confirmed(CommitPlan),
    /// User declined either the tree screen (`q`) or the
    /// confirmation prompt (`n`). Exit 0 with no filesystem
    /// changes per `AUX-005` step 4 and `AUX-008`.
    Declined,
    /// User aborted via `Ctrl+C`. Exit 130 per `EXEC-021`.
    Aborted,
}

/// Which on-screen element currently carries the focus highlight.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TuiFocus {
    /// A tree row, identified by the underlying [`Tree`]'s focus
    /// path.
    Tree,
    /// The synthetic `[ Commit selection ]` button below the tree.
    CommitButton,
}

/// Combined gitignore matcher used to classify directories as
/// `HiddenKind::Gitignored` at read time.
///
/// Honours the cwd's local `.gitignore` plus git's global
/// excludes (`core.excludesFile`, typically
/// `~/.config/git/ignore`). Sub-directory `.gitignore` files are
/// NOT cascaded for the v1 of this feature: the common case
/// (excludes declared at the repo root: `node_modules/`,
/// `target/`, etc.) is covered, and deeper cascading would
/// require either a pre-walk of the whole tree or per-directory
/// matcher rebuilds, both of which cost more than this feature
/// pays back.
#[derive(Debug, Clone)]
pub struct GitignoreMatcher {
    local: Gitignore,
    global: Gitignore,
}

impl GitignoreMatcher {
    /// Construct a matcher rooted at `cwd_host`. A missing
    /// `.gitignore` is not an error; the matcher then matches
    /// only entries the global gitignore would also match (if
    /// any).
    #[must_use]
    pub fn new(cwd_host: &Path) -> Self {
        let mut builder = GitignoreBuilder::new(cwd_host);
        // The builder's `add` returns `Option<Error>`; we ignore
        // a missing file (the common case) and any malformed
        // ignore file (would produce a typed error if needed,
        // but for now we degrade gracefully to an empty
        // matcher).
        let _ = builder.add(cwd_host.join(".gitignore"));
        let local = builder.build().unwrap_or_else(|_| Gitignore::empty());
        let (global, _) = Gitignore::global();
        Self { local, global }
    }

    /// Whether the (host-side) `path` is treated as ignored.
    /// `is_dir` mirrors `gitignore`'s directory-vs-file
    /// distinction so `dir/`-style patterns match correctly.
    #[must_use]
    pub fn is_ignored(&self, host_path: &Path, is_dir: bool) -> bool {
        self.local.matched(host_path, is_dir).is_ignore()
            || self.global.matched(host_path, is_dir).is_ignore()
    }
}

/// The full mutable TUI state. Held by the driver, mutated by
/// [`dispatch`].
#[derive(Debug)]
pub struct TuiState {
    /// The interactive tree per [`super::model`].
    pub tree: Tree,
    /// Which on-screen element gets the focus highlight.
    pub focus: TuiFocus,
    /// Host filesystem path of the cwd. Displayed in the header;
    /// used by the commit-pass plumbing when leaving the tree
    /// screen.
    pub cwd_host: PathBuf,
    /// Gitignore matcher consulted at directory-read time to
    /// classify entries as `HiddenKind::Gitignored`.
    pub gitignore: GitignoreMatcher,
    /// Whether dotfile-prefixed and gitignored sibling
    /// directories are visible in the tree. Defaults to `false`.
    /// Toggled by `H`; the toggle returns
    /// [`DispatchResult::ReloadTreeForVisibility`] so the driver
    /// can re-read every already-loaded directory against the new
    /// flag (state and expanded-ness are preserved by basename).
    pub hidden_visible: bool,
    /// Transient status / refusal message rendered above the
    /// keybinding hint. Cleared on every new keystroke before
    /// dispatch.
    pub status: Option<String>,
    /// Whether the help overlay is currently open. Any keystroke
    /// dismisses it.
    pub help_visible: bool,
    /// Whether the driver should ring the terminal bell on the
    /// next render. Cleared after the bell fires.
    pub bell_pending: bool,
}

impl TuiState {
    /// Construct an initial state rooted at `cwd_host`. Loads the
    /// cwd's direct subdirectories (filtered per [`Self::hidden_visible`])
    /// so the user has something to navigate immediately.
    fn new(cwd_host: PathBuf) -> Result<Self> {
        let gitignore = GitignoreMatcher::new(&cwd_host);
        let children = read_dir_children(&cwd_host, Path::new("/"), &gitignore, false)?;
        let mut root = Node::new(OsString::from("/"), PathBuf::from("/"));
        root.children = children;
        root.children_loaded = true;
        root.expanded = true;
        Ok(Self {
            tree: Tree::new(root),
            focus: TuiFocus::Tree,
            cwd_host,
            gitignore,
            hidden_visible: false,
            status: None,
            help_visible: false,
            bell_pending: false,
        })
    }
}

// ---------------------------------------------------------------
// Dispatcher (pure)
// ---------------------------------------------------------------

/// Apply a single crossterm event to the TUI state and report
/// what the driver should do next.
///
/// The function clears the state's transient fields (`status`,
/// `bell_pending`) at the start of every call so each keystroke
/// produces a fresh signal. Set both inside this function when
/// the binding warrants them.
pub fn dispatch(event: &Event, state: &mut TuiState) -> DispatchResult {
    state.status = None;
    state.bell_pending = false;

    let Event::Key(key) = event else {
        return DispatchResult::Continue;
    };
    if key.kind != KeyEventKind::Press {
        return DispatchResult::Continue;
    }

    // Ctrl+C aborts before any other interpretation so the user
    // can always bail out from anywhere, including the help
    // overlay.
    if key.modifiers.contains(KeyModifiers::CONTROL) && matches!(key.code, KeyCode::Char('c' | 'C'))
    {
        return DispatchResult::Abort;
    }

    // Help overlay swallows the next keystroke and closes.
    if state.help_visible {
        state.help_visible = false;
        return DispatchResult::Continue;
    }

    match key.code {
        KeyCode::Up => {
            move_focus(state, FocusDirection::Prev);
            DispatchResult::Continue
        }
        KeyCode::Down => {
            move_focus(state, FocusDirection::Next);
            DispatchResult::Continue
        }
        KeyCode::Right => expand_current(state),
        KeyCode::Left => {
            collapse_current(state);
            DispatchResult::Continue
        }
        KeyCode::Char(' ') => cycle_current(state),
        KeyCode::Enter => DispatchResult::ExitCommit,
        KeyCode::Char('h' | 'H') => {
            state.hidden_visible = !state.hidden_visible;
            state.status = Some(if state.hidden_visible {
                "hidden directories shown".to_string()
            } else {
                "hidden directories hidden".to_string()
            });
            DispatchResult::ReloadTreeForVisibility
        }
        KeyCode::Char('?') => {
            state.help_visible = true;
            DispatchResult::Continue
        }
        KeyCode::Char('q' | 'Q') | KeyCode::Esc => DispatchResult::ExitCancel,
        _ => DispatchResult::Continue,
    }
}

#[derive(Clone, Copy)]
enum FocusDirection {
    Next,
    Prev,
}

fn move_focus(state: &mut TuiState, dir: FocusDirection) {
    let visible = state.tree.visible_nodes().len();
    if visible == 0 {
        // Cannot happen with a well-formed tree (the root is
        // always visible) but stay defensive.
        return;
    }
    let total = visible + 1; // commit button is the (visible)th slot
    let current = match state.focus {
        TuiFocus::Tree => state.tree.focused_visible_index(),
        TuiFocus::CommitButton => visible,
    };
    let next = match dir {
        FocusDirection::Next => (current + 1) % total,
        FocusDirection::Prev => {
            if current == 0 {
                total - 1
            } else {
                current - 1
            }
        }
    };
    if next == visible {
        state.focus = TuiFocus::CommitButton;
    } else {
        state.focus = TuiFocus::Tree;
        state.tree.focus_at_visible_index(next);
    }
}

fn expand_current(state: &mut TuiState) -> DispatchResult {
    if state.focus != TuiFocus::Tree {
        return DispatchResult::Continue;
    }
    let outcome = state.tree.try_expand_focused();
    if matches!(outcome, ExpandOutcome::NeedsChildrenLoaded) {
        // The driver does the read and retries the expand in
        // the same keystroke so the user sees a single decisive
        // outcome per Right-arrow press.
        return DispatchResult::LoadChildrenThenRetryExpand;
    }
    apply_expand_outcome_signal(state, outcome);
    DispatchResult::Continue
}

/// Translate an `ExpandOutcome` into the user-visible signal.
/// `Expanded` and `AlreadyExpanded` are silent (success or
/// no-op); `RefusedNoSubdirs` rings the bell and shows a status
/// message; `NeedsChildrenLoaded` is treated as a no-op here
/// because the driver only calls this helper after a load.
fn apply_expand_outcome_signal(state: &mut TuiState, outcome: ExpandOutcome) {
    match outcome {
        ExpandOutcome::Expanded
        | ExpandOutcome::AlreadyExpanded
        | ExpandOutcome::NeedsChildrenLoaded => {}
        ExpandOutcome::RefusedNoSubdirs => {
            let path_display = display_workspace_path(&state.tree.focused().path);
            state.bell_pending = true;
            state.status = Some(format!("cannot expand `{path_display}`: no subdirectories"));
        }
    }
}

fn collapse_current(state: &mut TuiState) {
    if state.focus != TuiFocus::Tree {
        return;
    }
    state.tree.collapse_focused();
}

fn cycle_current(state: &mut TuiState) -> DispatchResult {
    if state.focus != TuiFocus::Tree {
        return DispatchResult::Continue;
    }
    let outcome = state.tree.cycle_focused();
    if matches!(outcome, CycleOutcome::NeedsChildrenLoaded) {
        // The driver does the disk read and retries the cycle in
        // the same keystroke so the user sees a single, decisive
        // transition per Space press.
        return DispatchResult::LoadChildrenThenRetryCycle;
    }
    apply_cycle_outcome_signal(state, outcome);
    DispatchResult::Continue
}

/// Translate a `CycleOutcome` into the user-visible signal:
/// terminal bell and status message for the two refusal cases,
/// no-op for `Advanced`. `NeedsChildrenLoaded` is treated as a
/// no-op here because the driver only calls this helper after a
/// load (where the outcome cannot be `NeedsChildrenLoaded`
/// again).
fn apply_cycle_outcome_signal(state: &mut TuiState, outcome: CycleOutcome) {
    match outcome {
        CycleOutcome::Advanced(_) | CycleOutcome::NeedsChildrenLoaded => {}
        CycleOutcome::RefusedEmptyGlob => {
            let path_display = display_workspace_path(&state.tree.focused().path);
            state.bell_pending = true;
            state.status = Some(format!(
                "skipped projects-parent for `{path_display}`: no subdirectories",
            ));
        }
        CycleOutcome::RefusedSubtreeLock => {
            let path_display = display_workspace_path(&state.tree.focused().path);
            state.bell_pending = true;
            state.status = Some(format!(
                "cannot cycle `{path_display}`: under a projects-parent directory",
            ));
        }
    }
}

fn display_workspace_path(p: &Path) -> String {
    p.to_string_lossy().into_owned()
}

// ---------------------------------------------------------------
// Driver (terminal IO)
// ---------------------------------------------------------------

/// Run the full interactive scaffold flow against `cwd_host`.
///
/// Sets up a ratatui terminal on stdout, drives the tree screen
/// to end-of-selection, builds a [`CommitPlan`], and then drives
/// the confirmation screen. The terminal is unconditionally
/// restored on return via the [`TerminalGuard`] RAII helper.
///
/// # Errors
///
/// Propagates the dispatcher's IO errors (`read_dir` failures,
/// raw mode setup) plus any [`super::commit::CommitPlanError`]
/// surfaced during the commit pass.
pub fn run_interactive_scaffold(cwd_host: &Path) -> Result<ScaffoldOutcome> {
    let mut state = TuiState::new(cwd_host.to_path_buf())?;

    let mut terminal = enter_terminal()?;
    let mut guard = TerminalGuard::armed();

    let outcome = drive_tree_screen(&mut terminal, &mut state);

    // Whichever outcome we got, we leave the tree screen with the
    // terminal still in raw mode. The confirmation pass reuses
    // the same terminal; the guard restores on the way out.
    let outcome = match outcome {
        Ok(DriverExit::Commit) => {
            let plan = plan_commit(&state.tree, cwd_host)
                .map_err(|err| miette!("{err}"))
                .wrap_err("haz init: AUX-005 commit-plan construction failed")?;
            drive_confirmation_screen(&mut terminal, &plan)?
        }
        Ok(DriverExit::Cancel) => ScaffoldOutcome::Declined,
        Ok(DriverExit::Abort) => ScaffoldOutcome::Aborted,
        Err(e) => {
            guard.disarm();
            restore_terminal();
            return Err(e);
        }
    };

    guard.disarm();
    restore_terminal();
    Ok(outcome)
}

#[derive(Debug)]
enum DriverExit {
    Commit,
    Cancel,
    Abort,
}

fn drive_tree_screen(
    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
    state: &mut TuiState,
) -> Result<DriverExit> {
    loop {
        terminal
            .draw(|frame| render_tree_screen(frame, state))
            .into_diagnostic()
            .wrap_err("haz init: failed to draw tree screen")?;

        if state.bell_pending {
            ring_bell();
            state.bell_pending = false;
        }

        let event = read_event_blocking()?;
        match dispatch(&event, state) {
            DispatchResult::Continue => {}
            DispatchResult::LoadChildrenThenRetryExpand => {
                load_children_for_focused(state)?;
                let outcome = state.tree.try_expand_focused();
                apply_expand_outcome_signal(state, outcome);
            }
            DispatchResult::LoadChildrenThenRetryCycle => {
                load_children_for_focused(state)?;
                let outcome = state.tree.cycle_focused();
                apply_cycle_outcome_signal(state, outcome);
            }
            DispatchResult::ReloadTreeForVisibility => {
                reload_tree_for_visibility(state)?;
            }
            DispatchResult::ExitCommit => return Ok(DriverExit::Commit),
            DispatchResult::ExitCancel => return Ok(DriverExit::Cancel),
            DispatchResult::Abort => return Ok(DriverExit::Abort),
        }
    }
}

fn drive_confirmation_screen(
    terminal: &mut Terminal<CrosstermBackend<Stdout>>,
    plan: &CommitPlan,
) -> Result<ScaffoldOutcome> {
    loop {
        terminal
            .draw(|frame| render_confirmation_screen(frame, plan))
            .into_diagnostic()
            .wrap_err("haz init: failed to draw confirmation screen")?;

        let event = read_event_blocking()?;
        let Event::Key(key) = event else {
            continue;
        };
        if key.kind != KeyEventKind::Press {
            continue;
        }
        if key.modifiers.contains(KeyModifiers::CONTROL)
            && matches!(key.code, KeyCode::Char('c' | 'C'))
        {
            return Ok(ScaffoldOutcome::Aborted);
        }
        match key.code {
            KeyCode::Char('y' | 'Y') => {
                return Ok(ScaffoldOutcome::Confirmed(plan.clone()));
            }
            KeyCode::Char('n' | 'N' | 'q' | 'Q') | KeyCode::Esc => {
                return Ok(ScaffoldOutcome::Declined);
            }
            _ => {}
        }
    }
}

fn read_event_blocking() -> Result<Event> {
    // crossterm::event::read() blocks; the poll-with-timeout
    // pattern is for non-blocking redraws driven by external
    // state. Our redraws are entirely event-driven, so a plain
    // blocking read keeps the loop simple.
    event::read()
        .into_diagnostic()
        .wrap_err("haz init: failed to read terminal event")
}

fn ring_bell() {
    let _ = io::stderr().write_all(b"\x07");
    let _ = io::stderr().flush();
}

// ---------------------------------------------------------------
// Filesystem
// ---------------------------------------------------------------

fn load_children_for_focused(state: &mut TuiState) -> Result<()> {
    let focused_path = state.tree.focused().path.clone();
    let host_path = host_join(&state.cwd_host, &focused_path);
    let children = read_dir_children(
        &host_path,
        &focused_path,
        &state.gitignore,
        state.hidden_visible,
    )?;
    state.tree.populate_focused_children(children);
    Ok(())
}

/// Re-read every currently-loaded directory in the tree against
/// the new `hidden_visible` value. New entries appear with
/// default state; entries previously present retain their
/// `state`, `expanded`, `children_loaded`, and `children`
/// (matched by basename). Entries no longer in the new read are
/// dropped. After reloading, focus is restored to the
/// previously-focused workspace path when that node is still
/// visible, otherwise it falls back to the root.
fn reload_tree_for_visibility(state: &mut TuiState) -> Result<()> {
    let focused_workspace_path = state.tree.focused().path.clone();
    let cwd_host = state.cwd_host.clone();
    let show_hidden = state.hidden_visible;
    reload_loaded_subtree(
        state.tree.root_mut(),
        &cwd_host,
        &state.gitignore,
        show_hidden,
    )?;
    let new_path =
        locate_visible_path(state.tree.root(), &focused_workspace_path).unwrap_or_default();
    state.tree.set_focus_path(new_path);
    Ok(())
}

/// Recursive reload helper. Only descends into directories
/// previously loaded (`children_loaded == true`); never reads a
/// directory the user has not yet expanded.
fn reload_loaded_subtree(
    node: &mut Node,
    cwd_host: &Path,
    gitignore: &GitignoreMatcher,
    show_hidden: bool,
) -> Result<()> {
    if !node.children_loaded {
        return Ok(());
    }
    let host_path = host_join(cwd_host, &node.path);
    let mut new_children = read_dir_children(&host_path, &node.path, gitignore, show_hidden)?;

    let mut old_by_name: std::collections::HashMap<std::ffi::OsString, Node> =
        std::collections::HashMap::new();
    for child in std::mem::take(&mut node.children) {
        old_by_name.insert(child.name.clone(), child);
    }

    for new_child in &mut new_children {
        if let Some(old) = old_by_name.remove(&new_child.name) {
            new_child.state = old.state;
            new_child.expanded = old.expanded;
            new_child.children_loaded = old.children_loaded;
            new_child.children = old.children;
            reload_loaded_subtree(new_child, cwd_host, gitignore, show_hidden)?;
        }
    }
    node.children = new_children;
    Ok(())
}

/// Locate the focus path (list of child indices) leading to the
/// node whose workspace-absolute path equals `target`. Returns
/// `None` if no such node is visible (collapsed ancestor or
/// removed by the reload).
fn locate_visible_path(root: &Node, target: &Path) -> Option<Vec<usize>> {
    let mut path: Vec<usize> = Vec::new();
    if locate_visible_path_rec(root, target, &mut path) {
        Some(path)
    } else {
        None
    }
}

fn locate_visible_path_rec(node: &Node, target: &Path, path: &mut Vec<usize>) -> bool {
    if node.path == target {
        return true;
    }
    if !node.expanded {
        return false;
    }
    for (i, child) in node.children.iter().enumerate() {
        path.push(i);
        if locate_visible_path_rec(child, target, path) {
            return true;
        }
        path.pop();
    }
    false
}

fn read_dir_children(
    host_dir: &Path,
    workspace_dir: &Path,
    gitignore: &GitignoreMatcher,
    show_hidden: bool,
) -> Result<Vec<Node>> {
    let mut entries: Vec<Node> = Vec::new();
    let read = fs::read_dir(host_dir)
        .into_diagnostic()
        .wrap_err_with(|| format!("failed to read directory `{}`", host_dir.display()))?;
    for entry in read {
        let entry = entry
            .into_diagnostic()
            .wrap_err_with(|| format!("failed to read entry under `{}`", host_dir.display()))?;
        let file_type = entry
            .file_type()
            .into_diagnostic()
            .wrap_err_with(|| format!("failed to stat `{}`", entry.path().display()))?;
        if !file_type.is_dir() {
            continue;
        }
        let name = entry.file_name();
        let kind = classify_hidden(&name, &entry.path(), gitignore);
        if kind != HiddenKind::Visible && !show_hidden {
            continue;
        }
        let mut child_workspace = workspace_dir.to_path_buf();
        child_workspace.push(&name);
        let mut node = Node::new(name, child_workspace);
        node.hidden_kind = kind;
        entries.push(node);
    }
    entries.sort_by(|a, b| a.name.cmp(&b.name));
    Ok(entries)
}

/// Classify a directory entry by how it would be hidden.
///
/// `Gitignored` wins over `Dotfile` when both apply, so the
/// warning-colour styling reaches the user. Pure helper; the
/// caller decides whether the entry is suppressed or shown.
fn classify_hidden(name: &OsString, host_path: &Path, gitignore: &GitignoreMatcher) -> HiddenKind {
    if gitignore.is_ignored(host_path, true) {
        return HiddenKind::Gitignored;
    }
    if is_hidden_name(name) {
        return HiddenKind::Dotfile;
    }
    HiddenKind::Visible
}

fn is_hidden_name(name: &OsString) -> bool {
    let bytes = name.as_encoded_bytes();
    bytes.first().copied() == Some(b'.')
}

fn host_join(cwd_host_root: &Path, workspace_absolute: &Path) -> PathBuf {
    let stripped = workspace_absolute
        .strip_prefix("/")
        .unwrap_or(workspace_absolute);
    if stripped.as_os_str().is_empty() {
        cwd_host_root.to_path_buf()
    } else {
        cwd_host_root.join(stripped)
    }
}

// ---------------------------------------------------------------
// Terminal setup / teardown
// ---------------------------------------------------------------

fn enter_terminal() -> Result<Terminal<CrosstermBackend<Stdout>>> {
    enable_raw_mode()
        .into_diagnostic()
        .wrap_err("haz init: failed to enable terminal raw mode")?;
    let mut stdout = io::stdout();
    execute!(stdout, EnterAlternateScreen)
        .into_diagnostic()
        .wrap_err("haz init: failed to enter the alternate screen")?;
    let backend = CrosstermBackend::new(stdout);
    let terminal = Terminal::with_options(
        backend,
        TerminalOptions {
            viewport: Viewport::Fullscreen,
        },
    )
    .into_diagnostic()
    .wrap_err("haz init: failed to initialise the ratatui terminal")?;
    Ok(terminal)
}

fn restore_terminal() {
    let _ = disable_raw_mode();
    let _ = execute!(io::stdout(), LeaveAlternateScreen);
}

struct TerminalGuard {
    armed: bool,
}

impl TerminalGuard {
    fn armed() -> Self {
        Self { armed: true }
    }

    fn disarm(&mut self) {
        self.armed = false;
    }
}

impl Drop for TerminalGuard {
    fn drop(&mut self) {
        if self.armed {
            restore_terminal();
        }
    }
}

// ---------------------------------------------------------------
// Rendering
// ---------------------------------------------------------------

const COLOR_PROJECT: Color = Color::Green;
const COLOR_PROJECTS_PARENT: Color = Color::Cyan;

/// Lines occupied by chrome ABOVE the tree (title + cwd).
const CHROME_ABOVE_TREE: u16 = 2;
/// Lines occupied by chrome BELOW the tree (spacer + commit
/// button + status + keys). The tree is sized to fit its
/// visible rows up to the height that leaves room for this
/// chrome; remaining vertical space falls into the trailing
/// `Min(0)` chunk so the chrome sits close to the tree on
/// tall terminals instead of being pushed to the screen bottom.
const CHROME_BELOW_TREE: u16 = 4;

fn render_tree_screen(frame: &mut Frame<'_>, state: &TuiState) {
    let area = frame.area();

    let visible_count = u16::try_from(state.tree.visible_nodes().len()).unwrap_or(u16::MAX);
    let available_for_tree = area
        .height
        .saturating_sub(CHROME_ABOVE_TREE + CHROME_BELOW_TREE);
    let tree_height = visible_count.min(available_for_tree).max(1);

    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1),           // 0: title
            Constraint::Length(1),           // 1: cwd
            Constraint::Length(tree_height), // 2: tree
            Constraint::Length(1),           // 3: spacer
            Constraint::Length(1),           // 4: commit button
            Constraint::Length(1),           // 5: status
            Constraint::Length(1),           // 6: keybindings
            Constraint::Min(0),              // 7: empty trailer
        ])
        .split(area);

    render_title(frame, chunks[0]);
    render_cwd(frame, chunks[1], &state.cwd_host);
    render_tree(frame, chunks[2], state);
    render_commit_button(frame, chunks[4], state);
    render_status(frame, chunks[5], state.status.as_deref());
    render_keys(frame, chunks[6]);

    if state.help_visible {
        render_help_overlay(frame, area);
    }
}

fn render_title(frame: &mut Frame<'_>, area: Rect) {
    let para = Paragraph::new(Line::from(Span::styled(
        " haz init \u{2014} select directories to register as projects ",
        Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD),
    )));
    frame.render_widget(para, area);
}

fn render_cwd(frame: &mut Frame<'_>, area: Rect, cwd: &Path) {
    let text = format!(" cwd: {}", cwd.display());
    let para = Paragraph::new(Line::from(Span::raw(text)));
    frame.render_widget(para, area);
}

fn render_tree(frame: &mut Frame<'_>, area: Rect, state: &TuiState) {
    let visible = state.tree.visible_nodes();
    let width = area.width as usize;
    let items: Vec<ListItem<'static>> = visible
        .iter()
        .map(|vn| ListItem::new(build_row_line(vn, width)))
        .collect();

    let list = List::new(items).highlight_style(
        Style::default()
            .add_modifier(Modifier::REVERSED)
            .add_modifier(Modifier::BOLD),
    );

    let mut list_state = ListState::default();
    if state.focus == TuiFocus::Tree {
        list_state.select(Some(state.tree.focused_visible_index()));
    }
    frame.render_stateful_widget(list, area, &mut list_state);
}

/// Fixed column gap between the row's content and its italic
/// state label. The label sits this many columns to the right of
/// the name, regardless of terminal width, so it does not
/// migrate across the screen on resize and stays close to the
/// row it describes.
const GAP_TO_RIGHT_LABEL: usize = 4;

fn build_row_line(vn: &VisibleNode<'_>, area_width: usize) -> Line<'static> {
    let (state_glyph, state_glyph_style, state_text, state_text_style) = state_decor(vn.node.state);

    // Every Node in the model is a directory (the read_dir
    // filter drops non-directories), so every row is
    // expandable: the triangle just reflects expanded vs
    // collapsed, never "leaf".
    let expand_glyph = if vn.node.expanded {
        "\u{25BC}" // â–¼
    } else {
        "\u{25B6}" // â–¶
    };

    let indent: String = " ".repeat(vn.depth * 2);
    let name = vn.node.name.to_string_lossy().into_owned();

    // Left-hand block: state glyph, depth indent, expand glyph, name.
    let left_text = format!(" {state_glyph} {indent}{expand_glyph} {name}");
    let left_len = left_text.chars().count();

    // Italic state label sits at a fixed gap after the row's
    // name. When even that minimum-gap layout overflows the
    // terminal, drop the label rather than let ratatui clip it
    // mid-glyph.
    let right_text = state_text.to_string();
    let right_len = right_text.chars().count();
    let has_room_for_right_label =
        !right_text.is_empty() && left_len + GAP_TO_RIGHT_LABEL + right_len <= area_width;
    let pad_width = GAP_TO_RIGHT_LABEL;

    let mut row_modifier = Modifier::empty();
    if vn.locked {
        row_modifier |= Modifier::DIM;
    }
    let hidden_fg = match vn.node.hidden_kind {
        HiddenKind::Visible => None,
        HiddenKind::Dotfile => {
            // Dotfile rows dim only; no foreground recolour, so
            // they read as "background" content.
            row_modifier |= Modifier::DIM;
            None
        }
        HiddenKind::Gitignored => {
            // Gitignored rows dim AND recolour to a warning
            // orange (RGB 204/102/0), per the design's
            // "obviously here but you probably don't want it"
            // intent.
            row_modifier |= Modifier::DIM;
            Some(Color::Rgb(204, 102, 0))
        }
    };

    let glyph_style = state_glyph_style.add_modifier(row_modifier);
    let plain_style = match hidden_fg {
        Some(fg) => Style::default().fg(fg).add_modifier(row_modifier),
        None => Style::default().add_modifier(row_modifier),
    };
    let italic_style = state_text_style.add_modifier(row_modifier);

    let mut spans = vec![
        Span::styled(" ", plain_style),
        Span::styled(state_glyph.to_string(), glyph_style),
        Span::styled(format!(" {indent}{expand_glyph} {name}"), plain_style),
    ];
    if has_room_for_right_label {
        spans.push(Span::styled(" ".repeat(pad_width), plain_style));
        spans.push(Span::styled(right_text, italic_style));
    }
    Line::from(spans)
}

fn state_decor(state: SelectionState) -> (&'static str, Style, &'static str, Style) {
    match state {
        SelectionState::None => (
            "\u{25A1}", // â–¡
            Style::default(),
            "",
            Style::default(),
        ),
        SelectionState::Project => (
            "\u{25A0}", // â– 
            Style::default()
                .fg(COLOR_PROJECT)
                .add_modifier(Modifier::BOLD),
            "(project)",
            Style::default()
                .fg(COLOR_PROJECT)
                .add_modifier(Modifier::ITALIC),
        ),
        SelectionState::ProjectsParent => (
            "\u{25A3}", // â–£
            Style::default()
                .fg(COLOR_PROJECTS_PARENT)
                .add_modifier(Modifier::BOLD),
            "(projects parent)",
            Style::default()
                .fg(COLOR_PROJECTS_PARENT)
                .add_modifier(Modifier::ITALIC),
        ),
    }
}

fn render_commit_button(frame: &mut Frame<'_>, area: Rect, state: &TuiState) {
    let count = state.tree.project_root_set().len();
    let label = format!(
        "  [ Commit selection ({count} project{plural}) ]",
        count = count,
        plural = if count == 1 { "" } else { "s" },
    );
    let style = if state.focus == TuiFocus::CommitButton {
        Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD)
    } else {
        Style::default().add_modifier(Modifier::BOLD)
    };
    let para = Paragraph::new(Line::from(Span::styled(label, style)));
    frame.render_widget(para, area);
}

fn render_status(frame: &mut Frame<'_>, area: Rect, status: Option<&str>) {
    let text = status.unwrap_or("");
    let para = Paragraph::new(Line::from(Span::styled(
        format!(" {text}"),
        Style::default().fg(Color::Yellow),
    )));
    frame.render_widget(para, area);
}

fn render_keys(frame: &mut Frame<'_>, area: Rect) {
    let line = Line::from(vec![
        Span::raw(" \u{2191}\u{2193} move  "),
        Span::raw("\u{2192} expand  "),
        Span::raw("\u{2190} collapse  "),
        Span::raw("Space cycle selection  "),
        Span::raw("Enter commit  "),
        Span::raw("H hidden  "),
        Span::raw("q cancel  "),
        Span::raw("? help"),
    ])
    .style(Style::default().add_modifier(Modifier::DIM));
    let para = Paragraph::new(line);
    frame.render_widget(para, area);
}

fn render_help_overlay(frame: &mut Frame<'_>, area: Rect) {
    let inner = centred_rect(area, 60, 18);
    let block = Block::bordered().title(" help ").bold();
    let body = vec![
        Line::from("Navigation"),
        Line::from("  \u{2191} / \u{2193}        move focus through visible rows"),
        Line::from("  \u{2192}            expand focused directory"),
        Line::from("  \u{2190}            collapse focused directory"),
        Line::from(""),
        Line::from("Selection (AUX-003 / AUX-004)"),
        Line::from("  Space        cycle: none -> project -> projects-parent"),
        Line::from(""),
        Line::from("Commit"),
        Line::from("  Enter        leave selection, show confirmation"),
        Line::from(""),
        Line::from("Other"),
        Line::from("  H            toggle hidden directories"),
        Line::from("  ?            toggle this overlay"),
        Line::from("  q / Esc      cancel (exit with no changes)"),
        Line::from("  Ctrl+C       abort"),
    ];
    let para = Paragraph::new(body).block(block).wrap(Wrap { trim: false });
    frame.render_widget(Clear, inner);
    frame.render_widget(para, inner);
}

fn centred_rect(area: Rect, width: u16, height: u16) -> Rect {
    let w = width.min(area.width.saturating_sub(4));
    let h = height.min(area.height.saturating_sub(2));
    let x = area.x + area.width.saturating_sub(w) / 2;
    let y = area.y + area.height.saturating_sub(h) / 2;
    Rect {
        x,
        y,
        width: w,
        height: h,
    }
}

fn render_confirmation_screen(frame: &mut Frame<'_>, plan: &CommitPlan) {
    let area = frame.area();
    let chunks = Layout::default()
        .direction(Direction::Vertical)
        .constraints([
            Constraint::Length(1), // title
            Constraint::Min(0),    // body
            Constraint::Length(1), // keys
        ])
        .split(area);

    let title = Paragraph::new(Line::from(Span::styled(
        " haz init \u{2014} confirm scaffold ",
        Style::default().add_modifier(Modifier::REVERSED | Modifier::BOLD),
    )));
    frame.render_widget(title, chunks[0]);

    let mut lines: Vec<Line<'static>> = Vec::new();
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        " will write .haz/workspace.yml:",
        Style::default().add_modifier(Modifier::BOLD),
    )));
    for line in plan.workspace_yml_body.lines() {
        lines.push(Line::from(format!("   {line}")));
    }
    lines.push(Line::from(""));
    if plan.project_ymls.is_empty() {
        lines.push(Line::from(Span::styled(
            " will scaffold no haz.yml files (empty projects: list).",
            Style::default().add_modifier(Modifier::ITALIC),
        )));
    } else {
        lines.push(Line::from(Span::styled(
            " will scaffold haz.yml:",
            Style::default().add_modifier(Modifier::BOLD),
        )));
        for scaffold in &plan.project_ymls {
            lines.push(Line::from(format!(
                "   {root}        name: {name}",
                root = scaffold.project_root.display(),
                name = scaffold.sanitised_name,
            )));
        }
    }
    lines.push(Line::from(""));
    lines.push(Line::from(Span::styled(
        " Proceed?  y = write, n / q = decline",
        Style::default().add_modifier(Modifier::BOLD),
    )));

    let para = Paragraph::new(lines).wrap(Wrap { trim: false });
    frame.render_widget(para, chunks[1]);

    let keys = Paragraph::new(Line::from(vec![
        Span::raw(" y proceed  "),
        Span::raw("n decline  "),
        Span::raw("q / Esc cancel  "),
        Span::raw("Ctrl+C abort"),
    ]))
    .style(Style::default().add_modifier(Modifier::DIM));
    frame.render_widget(keys, chunks[2]);
}

// ---------------------------------------------------------------
// Tests (dispatcher only, render functions are exercised by
// hand against a real terminal)
// ---------------------------------------------------------------

#[cfg(test)]
mod tests {
    use std::ffi::OsString;
    use std::fs;
    use std::path::{Path, PathBuf};

    use crossterm::event::{Event, KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers};
    use tempfile::TempDir;

    use super::super::model::{HiddenKind, Node, SelectionState, Tree};
    use super::{
        DispatchResult, GitignoreMatcher, TuiFocus, TuiState, dispatch, read_dir_children,
    };

    fn press(code: KeyCode) -> Event {
        press_with(code, KeyModifiers::NONE)
    }

    fn press_with(code: KeyCode, mods: KeyModifiers) -> Event {
        Event::Key(KeyEvent {
            code,
            modifiers: mods,
            kind: KeyEventKind::Press,
            state: KeyEventState::NONE,
        })
    }

    fn release(code: KeyCode) -> Event {
        Event::Key(KeyEvent {
            code,
            modifiers: KeyModifiers::NONE,
            kind: KeyEventKind::Release,
            state: KeyEventState::NONE,
        })
    }

    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 build_state(root: Node) -> TuiState {
        let mut state = TuiState {
            tree: Tree::new(root),
            focus: TuiFocus::Tree,
            cwd_host: PathBuf::from("/host"),
            gitignore: GitignoreMatcher::new(Path::new("/host")),
            hidden_visible: false,
            status: None,
            help_visible: false,
            bell_pending: false,
        };
        // Make sure we are starting in a known clean state.
        let _ = dispatch(&release(KeyCode::Esc), &mut state);
        state.status = None;
        state.bell_pending = false;
        state
    }

    // --- key release events are no-ops -------------------------

    #[test]
    fn release_events_do_not_mutate_state() {
        let mut root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        root.expanded = true;
        let mut state = build_state(root);
        let before_focus = state.focus;
        let result = dispatch(&release(KeyCode::Down), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.focus, before_focus);
    }

    // --- Ctrl+C aborts regardless of overlay state -------------

    #[test]
    fn ctrl_c_returns_abort() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(
            &press_with(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut state,
        );
        assert_eq!(result, DispatchResult::Abort);
    }

    #[test]
    fn ctrl_c_aborts_even_when_help_overlay_is_open() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char('?')), &mut state);
        assert!(state.help_visible);
        let result = dispatch(
            &press_with(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut state,
        );
        assert_eq!(result, DispatchResult::Abort);
    }

    // --- help overlay swallows the next keystroke --------------

    #[test]
    fn help_overlay_closes_on_next_keystroke() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char('?')), &mut state);
        assert!(state.help_visible);
        let result = dispatch(&press(KeyCode::Char('q')), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(!state.help_visible);
    }

    // --- navigation wraps via the commit button ----------------

    #[test]
    fn down_at_last_visible_tree_row_moves_to_commit_button() {
        let mut root = loaded_dir(
            "root",
            "/",
            vec![loaded_empty("a", "/a"), loaded_empty("b", "/b")],
        );
        root.expanded = true;
        let mut state = build_state(root);
        // root -> a
        dispatch(&press(KeyCode::Down), &mut state);
        // a -> b
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::Tree);
        // b -> commit button
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::CommitButton);
        // commit button -> root (wrap)
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::Tree);
        assert_eq!(state.tree.focused().path, PathBuf::from("/"));
    }

    #[test]
    fn up_from_root_wraps_to_commit_button() {
        let mut state = build_state(loaded_empty("root", "/"));
        // Root only, one visible row -> Up wraps to commit button.
        let result = dispatch(&press(KeyCode::Up), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.focus, TuiFocus::CommitButton);
    }

    // --- Space cycle (AUX-003) ---------------------------------

    #[test]
    fn space_advances_state_when_focused_on_tree_row() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(state.tree.focused().state, SelectionState::Project);
    }

    #[test]
    fn space_on_commit_button_is_noop() {
        let mut state = build_state(loaded_empty("root", "/"));
        // Move focus to commit button.
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::CommitButton);
        dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(state.tree.focused().state, SelectionState::None);
    }

    // --- Space on an unloaded directory requests the load and retry ---

    #[test]
    fn space_on_unloaded_directory_at_project_state_requests_load_then_retry() {
        // children_loaded=false. From Project state the next
        // cycle step is ProjectsParent, which the model cannot
        // evaluate without knowing whether subdirs exist. The
        // dispatcher signals the driver to load and re-issue
        // the cycle so the user sees a single decisive
        // transition per Space press.
        let mut root = Node::new(OsString::from("root"), PathBuf::from("/"));
        root.state = SelectionState::Project;
        let mut state = build_state(root);
        let result = dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(result, DispatchResult::LoadChildrenThenRetryCycle);
        // State unchanged at this point; the driver does the
        // load + retry, which the dispatcher unit test cannot
        // exercise.
        assert_eq!(state.tree.focused().state, SelectionState::Project);
    }

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

    #[test]
    fn space_refusal_when_no_subdirs_skips_to_none_and_signals() {
        // On a leaf, ProjectsParent is unreachable: the cycle
        // moves past it to None, AND the refusal channels (bell
        // + status message) still fire so the user perceives
        // why ProjectsParent didn't take.
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Char(' ')), &mut state); // -> Project
        let result = dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.tree.focused().state, SelectionState::None);
        assert!(state.bell_pending, "AUX-004 refusal must ring the bell");
        let status = state.status.as_deref().unwrap_or("");
        assert!(
            status.contains("no subdirectories"),
            "status message should explain the refusal: {status}",
        );
    }

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

    #[test]
    fn space_refusal_under_locked_subtree_sets_status_and_bell() {
        let mut src = loaded_empty("src", "/lib/src");
        let mut lib = loaded_dir("lib", "/lib", vec![src.clone()]);
        lib.state = SelectionState::ProjectsParent;
        lib.expanded = true;
        let mut root = loaded_dir("root", "/", vec![lib]);
        root.expanded = true;
        // Tweak src state to verify it stays put under lockout.
        src.state = SelectionState::None;
        let mut state = build_state(root);
        // Move focus down to lib/src (root -> lib -> lib/src).
        dispatch(&press(KeyCode::Down), &mut state);
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.tree.focused().path, PathBuf::from("/lib/src"));
        let result = dispatch(&press(KeyCode::Char(' ')), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(state.bell_pending, "lockout refusal must ring the bell");
        let status = state.status.as_deref().unwrap_or("");
        assert!(
            status.contains("projects-parent"),
            "lockout status should explain the cause: {status}",
        );
        assert_eq!(state.tree.focused().state, SelectionState::None);
    }

    // --- right-arrow expansion ---------------------------------

    #[test]
    fn right_arrow_expands_focused_directory_with_subdirectories() {
        let root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        let mut state = build_state(root);
        assert!(!state.tree.focused().expanded);
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(state.tree.focused().expanded);
    }

    #[test]
    fn right_arrow_on_loaded_leaf_refuses_with_bell_and_status() {
        // No subdirectories: expansion would reveal nothing, so
        // it is refused. `expanded` MUST stay false; the user
        // gets the bell + status message.
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(!state.tree.focused().expanded);
        assert!(state.bell_pending);
        let status = state.status.as_deref().unwrap_or("");
        assert!(
            status.contains("no subdirectories"),
            "refusal status should explain the reason: {status}",
        );
    }

    #[test]
    fn right_arrow_on_unloaded_directory_requests_load_then_retry() {
        let root = Node::new(OsString::from("root"), PathBuf::from("/"));
        // children_loaded is false by default.
        let mut state = build_state(root);
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::LoadChildrenThenRetryExpand);
        // expanded MUST stay false until the driver loads and
        // retries: the empty-vs-non-empty decision is not made
        // until after the load.
        assert!(!state.tree.focused().expanded);
    }

    #[test]
    fn right_arrow_on_commit_button_is_noop() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Down), &mut state); // focus button
        let result = dispatch(&press(KeyCode::Right), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert_eq!(state.focus, TuiFocus::CommitButton);
    }

    // --- left-arrow collapse -----------------------------------

    #[test]
    fn left_arrow_collapses_focused_directory() {
        let mut root = loaded_dir("root", "/", vec![loaded_empty("a", "/a")]);
        root.expanded = true;
        let mut state = build_state(root);
        assert!(state.tree.focused().expanded);
        let result = dispatch(&press(KeyCode::Left), &mut state);
        assert_eq!(result, DispatchResult::Continue);
        assert!(!state.tree.focused().expanded);
    }

    // --- Enter always commits ----------------------------------

    #[test]
    fn enter_on_tree_row_returns_exit_commit() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Enter), &mut state);
        assert_eq!(result, DispatchResult::ExitCommit);
    }

    #[test]
    fn enter_on_commit_button_returns_exit_commit() {
        let mut state = build_state(loaded_empty("root", "/"));
        dispatch(&press(KeyCode::Down), &mut state);
        assert_eq!(state.focus, TuiFocus::CommitButton);
        let result = dispatch(&press(KeyCode::Enter), &mut state);
        assert_eq!(result, DispatchResult::ExitCommit);
    }

    // --- H toggle ----------------------------------------------

    #[test]
    fn h_toggles_hidden_visibility_and_requests_reload() {
        let mut state = build_state(loaded_empty("root", "/"));
        assert!(!state.hidden_visible);
        let result = dispatch(&press(KeyCode::Char('h')), &mut state);
        assert!(state.hidden_visible);
        assert_eq!(result, DispatchResult::ReloadTreeForVisibility);
        assert!(state.status.as_deref().unwrap_or("").contains("shown"));
        let result = dispatch(&press(KeyCode::Char('h')), &mut state);
        assert!(!state.hidden_visible);
        assert_eq!(result, DispatchResult::ReloadTreeForVisibility);
        assert!(state.status.as_deref().unwrap_or("").contains("hidden"));
    }

    #[test]
    fn capital_h_also_toggles_hidden() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Char('H')), &mut state);
        assert!(state.hidden_visible);
        assert_eq!(result, DispatchResult::ReloadTreeForVisibility);
    }

    // --- q / Esc cancel ----------------------------------------

    #[test]
    fn q_returns_exit_cancel() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Char('q')), &mut state);
        assert_eq!(result, DispatchResult::ExitCancel);
    }

    #[test]
    fn esc_returns_exit_cancel() {
        let mut state = build_state(loaded_empty("root", "/"));
        let result = dispatch(&press(KeyCode::Esc), &mut state);
        assert_eq!(result, DispatchResult::ExitCancel);
    }

    // --- transient state cleared on every dispatch -------------

    #[test]
    fn status_cleared_on_each_dispatch_unless_set_by_handler() {
        let mut state = build_state(loaded_empty("root", "/"));
        // Set status via H toggle.
        dispatch(&press(KeyCode::Char('h')), &mut state);
        assert!(state.status.is_some());
        // An unrelated keystroke (Up) clears it.
        dispatch(&press(KeyCode::Up), &mut state);
        assert!(state.status.is_none());
    }

    // --- HiddenKind classification at read_dir time ------------

    fn names_of(nodes: &[Node]) -> Vec<String> {
        nodes
            .iter()
            .map(|n| n.name.to_string_lossy().into_owned())
            .collect()
    }

    fn kind_of(nodes: &[Node], name: &str) -> Option<HiddenKind> {
        nodes
            .iter()
            .find(|n| n.name.as_os_str() == std::ffi::OsStr::new(name))
            .map(|n| n.hidden_kind)
    }

    fn write_gitignore(dir: &Path, body: &str) {
        fs::write(dir.join(".gitignore"), body).unwrap();
    }

    #[test]
    fn read_dir_children_skips_dotfile_and_gitignored_when_show_hidden_false() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir(tmp.path().join("src")).unwrap();
        fs::create_dir(tmp.path().join(".git")).unwrap();
        fs::create_dir(tmp.path().join("node_modules")).unwrap();
        write_gitignore(tmp.path(), "node_modules/\n");
        let matcher = GitignoreMatcher::new(tmp.path());
        let children = read_dir_children(tmp.path(), Path::new("/"), &matcher, false).unwrap();
        assert_eq!(names_of(&children), vec!["src".to_owned()]);
    }

    #[test]
    fn read_dir_children_includes_hidden_with_kinds_when_show_hidden_true() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir(tmp.path().join("src")).unwrap();
        fs::create_dir(tmp.path().join(".git")).unwrap();
        fs::create_dir(tmp.path().join("node_modules")).unwrap();
        write_gitignore(tmp.path(), "node_modules/\n");
        let matcher = GitignoreMatcher::new(tmp.path());
        let children = read_dir_children(tmp.path(), Path::new("/"), &matcher, true).unwrap();
        // All three present, alphabetically sorted by basename.
        assert_eq!(
            names_of(&children),
            vec![
                ".git".to_owned(),
                "node_modules".to_owned(),
                "src".to_owned()
            ],
        );
        assert_eq!(kind_of(&children, ".git"), Some(HiddenKind::Dotfile));
        assert_eq!(
            kind_of(&children, "node_modules"),
            Some(HiddenKind::Gitignored),
        );
        assert_eq!(kind_of(&children, "src"), Some(HiddenKind::Visible));
    }

    #[test]
    fn read_dir_children_classifies_dotfile_dir_that_is_also_gitignored_as_gitignored() {
        // Gitignored wins when both apply, so the warning channel
        // reaches the user.
        let tmp = TempDir::new().unwrap();
        fs::create_dir(tmp.path().join(".cache")).unwrap();
        write_gitignore(tmp.path(), ".cache/\n");
        let matcher = GitignoreMatcher::new(tmp.path());
        let children = read_dir_children(tmp.path(), Path::new("/"), &matcher, true).unwrap();
        assert_eq!(kind_of(&children, ".cache"), Some(HiddenKind::Gitignored));
    }

    #[test]
    fn read_dir_children_with_no_gitignore_file_still_skips_dotfiles() {
        let tmp = TempDir::new().unwrap();
        fs::create_dir(tmp.path().join("lib")).unwrap();
        fs::create_dir(tmp.path().join(".hidden")).unwrap();
        // No .gitignore on disk; the matcher degrades to "match
        // nothing" via Gitignore::empty.
        let matcher = GitignoreMatcher::new(tmp.path());
        let children = read_dir_children(tmp.path(), Path::new("/"), &matcher, false).unwrap();
        assert_eq!(names_of(&children), vec!["lib".to_owned()]);
    }

    #[test]
    fn read_dir_children_ignores_regular_files() {
        // Files are never offered to the user: only directories
        // carry selection state.
        let tmp = TempDir::new().unwrap();
        fs::create_dir(tmp.path().join("lib")).unwrap();
        fs::write(tmp.path().join("README.md"), "").unwrap();
        let matcher = GitignoreMatcher::new(tmp.path());
        let children = read_dir_children(tmp.path(), Path::new("/"), &matcher, true).unwrap();
        assert_eq!(names_of(&children), vec!["lib".to_owned()]);
    }
}