baraddur 0.1.6

Project-agnostic file watcher that surfaces issues before CI
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
#![forbid(unsafe_code)]

pub mod config;
pub mod git;
mod loop_guard;
pub mod output;
pub mod pipeline;
pub mod watcher;

use anyhow::Result;
use std::fmt::Write as _;
use std::future::Future;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
use tokio::task::JoinHandle;

use crate::loop_guard::LoopGuard;
use crate::output::style::{Theme, should_color};
use crate::output::{
    BrowseAction, Display, DisplayConfig, JsonDisplay, OutputFormat, PlainDisplay, TtyDisplay,
};
use crate::pipeline::StepResult;

/// Emits a timestamped `[debug]` line to stderr, but only at `Debug`
/// verbosity. Centralizing the timestamp is the whole point: a restart loop is
/// obvious in the scrollback when each line is stamped, where bare `[debug]`
/// lines are not.
macro_rules! debug_log {
    ($dc:expr, $($arg:tt)*) => {
        if $dc.verbosity == $crate::output::Verbosity::Debug {
            eprintln!(
                "[debug {}] {}",
                ::chrono::Local::now().format("%H:%M:%S%.3f"),
                format_args!($($arg)*)
            );
        }
    };
}

/// Loop-guard tuning. A genuine human rarely produces 5 distinct debounced
/// file-change batches inside 10s; a self-inflicted loop does so easily.
const LOOP_WINDOW: Duration = Duration::from_secs(10);
const LOOP_THRESHOLD: usize = 5;
const LOOP_COOLDOWN: Duration = Duration::from_secs(5);

/// Result of the spawned on_failure hook task. Outer Result is the join
/// result; inner is `run_hook`'s return — `Some(text)` if the hook produced
/// output, `None` if it was suppressed (timeout, non-zero exit, empty stdout).
type HookHandle = JoinHandle<Result<Option<String>>>;

pub struct App {
    pub config: config::Config,
    pub config_path: PathBuf,
    pub root: PathBuf,
    pub display_config: DisplayConfig,
    /// Active profile name, set by `--profile <name>`. Purely informational
    /// at runtime — step filtering already happened via `apply_profile` before
    /// `App` was constructed. Shown in the watch banner when present.
    pub profile: Option<String>,
}

/// Filters `cfg.steps` to the named profile's members, preserving declaration
/// order. Errors if the profile name isn't defined in `cfg.profiles` or if a
/// member name references a step that no longer exists (the latter should be
/// caught by `validate`, but we check defensively).
///
/// Composes with `--staged` / `--since` / `if_changed`: this narrows the step
/// list first, then later path filtering narrows further.
pub fn apply_profile(cfg: &mut config::Config, profile_name: &str) -> Result<()> {
    let members = cfg.profiles.get(profile_name).ok_or_else(|| {
        let mut available: Vec<&String> = cfg.profiles.keys().collect();
        available.sort();
        if available.is_empty() {
            anyhow::anyhow!("profile `{profile_name}` not found (no profiles defined in config)")
        } else {
            let list = available
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ");
            anyhow::anyhow!("profile `{profile_name}` not found (defined: {list})")
        }
    })?;

    let wanted: std::collections::HashSet<&str> = members.iter().map(String::as_str).collect();
    cfg.steps.retain(|s| wanted.contains(s.name.as_str()));

    if cfg.steps.is_empty() {
        anyhow::bail!("profile `{profile_name}` resolved to zero steps");
    }

    Ok(())
}

/// Options for a one-shot `App::run_once` invocation.
#[derive(Debug, Default, Clone)]
pub struct RunOnceOptions {
    /// Skip the configured `[on_failure]` hook even if enabled.
    pub no_hook: bool,

    /// Initial trigger paths (relative to `App.root`). When `Some`, the
    /// pipeline filters steps by `if_changed` and substitutes `{files}`
    /// exactly as watch-mode does on a file-change. `None` runs every step.
    pub initial_trigger: Option<Vec<PathBuf>>,
}

impl App {
    /// Convenience wrapper that uses Ctrl+C as the shutdown signal.
    /// Production entry point.
    pub async fn run(self) -> Result<()> {
        let stop = async {
            let _ = tokio::signal::ctrl_c().await;
        };
        self.run_until(stop).await
    }

    /// Constructs the display the watch loop uses based on `display_config`.
    /// `JsonDisplay` when format is Json; otherwise `TtyDisplay` when attached
    /// to a terminal, `PlainDisplay` for non-TTY contexts.
    fn build_display(&self) -> Box<dyn Display> {
        let dc = &self.display_config;
        if dc.format == OutputFormat::Json {
            return Box::new(JsonDisplay::new());
        }
        let color = should_color(dc.is_tty);
        if dc.is_tty {
            Box::new(TtyDisplay::new(
                Theme::new(color),
                dc.verbosity,
                dc.no_clear,
            ))
        } else {
            Box::new(PlainDisplay::new(Theme::new(color), dc.verbosity))
        }
    }

    /// Runs the configured pipeline exactly once and returns whether every
    /// step passed. Uses `PlainDisplay` unconditionally (no spinner, no browse
    /// mode) so output is scriptable. Writes `.baraddur/last-run.log` and,
    /// unless `opts.no_hook`, runs the configured `[on_failure]` hook
    /// synchronously when the run fails.
    pub async fn run_once(self, opts: RunOnceOptions) -> Result<bool> {
        let dc = &self.display_config;
        let mut display: Box<dyn Display> = if dc.format == OutputFormat::Json {
            Box::new(JsonDisplay::new())
        } else {
            let color = should_color(dc.is_tty);
            Box::new(PlainDisplay::new(Theme::new(color), dc.verbosity))
        };

        display.banner(
            &self.root,
            &self.config_path,
            self.config.steps.len(),
            self.profile.as_deref(),
        );

        if let Some(paths) = opts.initial_trigger.as_deref() {
            display.set_trigger(paths);
        }

        let results = pipeline::run_pipeline(
            &self.config,
            &self.root,
            display.as_mut(),
            None,
            opts.initial_trigger.as_deref(),
            None,
        )
        .await?;

        log_run_outcome(write_run_log(&self.root, &results), dc);

        let success = results.iter().all(|r| r.success);

        if !success && !opts.no_hook && self.config.on_failure.enabled {
            display.hook_started();
            let combined = pipeline::combine_failed_output(&results);
            match pipeline::run_hook(&self.config.on_failure, &self.root, &combined).await {
                Ok(Some(text)) => display.hook_output(&text),
                _ => display.hook_finished(),
            }
        }

        Ok(success)
    }

    /// Runs the pipeline once; if it passes, executes `wrapped` (replacing
    /// the current process on Unix, spawn+wait on Windows). Returns the exit
    /// code to surface from `baraddur gate`.
    ///
    /// Empty trigger (e.g. `--staged` with nothing staged) skips the pipeline
    /// and execs immediately — there's nothing to verify.
    ///
    /// The configured `[on_failure]` hook timeout is clamped to 15s for gate
    /// so the gate fails fast (vs the watch-mode default of 30s).
    pub async fn gate(mut self, wrapped: Vec<String>, opts: RunOnceOptions) -> Result<i32> {
        if wrapped.is_empty() {
            anyhow::bail!("gate: no command provided");
        }

        let skip_pipeline = matches!(&opts.initial_trigger, Some(paths) if paths.is_empty());

        if !skip_pipeline {
            self.config.on_failure.timeout_secs = self.config.on_failure.timeout_secs.min(15);
            let success = self.run_once(opts).await?;
            if !success {
                return Ok(1);
            }
        }

        exec_wrapped(&wrapped)
    }

    /// Runs the watch loop until either `stop` resolves or the watcher dies.
    /// Exposed so tests can drive the loop without sending SIGINT to the test runner.
    // `last_failed_steps` is initialized to None as a placeholder; the first
    // read only happens after at least one Completed has overwritten it, so
    // the initial None is correctly diagnosed as unused. The placeholder is
    // required for control-flow init.
    #[allow(unused_assignments)]
    pub async fn run_until<F>(self, stop: F) -> Result<()>
    where
        F: Future<Output = ()>,
    {
        tokio::pin!(stop);
        let dc = &self.display_config;

        let spinner_interval = if dc.is_tty {
            Some(Duration::from_millis(80))
        } else {
            None
        };

        let mut display: Box<dyn Display> = self.build_display();

        // Show startup banner once before the first run.
        display.banner(
            &self.root,
            &self.config_path,
            self.config.steps.len(),
            self.profile.as_deref(),
        );

        let wcfg = watcher::WatchConfig {
            root: self.root.clone(),
            debounce: Duration::from_millis(self.config.watch.debounce_ms),
            extensions: self.config.watch.extensions.clone(),
            ignore: self.config.watch.ignore.clone(),
        };
        let mut rx = watcher::start(wcfg)?;

        // Single long-lived OS thread drains crossterm events into a channel.
        // Per-iteration spawn_blocking readers leaked: their JoinHandles were
        // dropped on file-change cancellation but the threads kept blocking
        // inside event::read(), then stole the next keystroke and exited.
        let mut key_rx = if dc.is_tty {
            Some(spawn_key_reader())
        } else {
            None
        };

        debug_log!(dc, "watcher started, running initial pipeline");

        // In-flight on_failure hook task, set after a failing run and cleared
        // when it completes, the user saves a file, or shutdown begins.
        let mut hook_handle: Option<HookHandle> = None;

        // Relative paths of files that triggered the current pipeline run.
        // `None` on the initial run; set on each `FileChange` and consumed by
        // the next `run_pipeline` invocation for path-based step filtering.
        let mut trigger_paths: Option<Vec<PathBuf>> = None;

        // Names of steps that failed in the most recent completed run.
        // Captured on `Completed`; consumed by the browse-mode `f` key, which
        // narrows the next run to just these steps via `rerun_filter`. `None`
        // until at least one run has completed.
        let mut last_failed_steps: Option<Vec<String>> = None;

        // Name filter for the next pipeline run. `Some(names)` runs only
        // matching steps (browse-mode `f`); `None` runs everything that
        // path-filtering left. Reset to `None` after each run completes.
        let mut rerun_filter: Option<Vec<String>> = None;

        // Self-inflicted-loop detection. `file_triggered` is set by every
        // file-change arm (all of which route back to the top of 'main) and
        // consumed here, giving the guard a single chokepoint regardless of
        // which arm fired. User-initiated reruns (browse `r`/`f`/`c`) leave it
        // false, so they never count toward the loop budget.
        let mut guard = LoopGuard::new(LOOP_WINDOW, LOOP_THRESHOLD);
        let mut file_triggered = false;

        'main: loop {
            if file_triggered {
                file_triggered = false;
                if guard.record(Instant::now()) {
                    guard.reset();
                    warn_loop(trigger_paths.as_deref().unwrap_or(&[]));
                    match cooldown(&mut stop, &mut rx, LOOP_COOLDOWN).await {
                        Flow::Resume => {}
                        Flow::Shutdown => {
                            cancel_hook(&mut hook_handle, display.as_mut());
                            return self.shutdown();
                        }
                        Flow::WatcherDied => {
                            eprintln!("baraddur: file watcher stopped unexpectedly. exiting.");
                            return Ok(());
                        }
                    }
                }
            }

            let outcome = tokio::select! {
                biased;

                _ = &mut stop => RunOutcome::Shutdown,

                maybe = rx.recv() => {
                    match maybe {
                        Some(paths) => RunOutcome::FileChange(paths),
                        None => RunOutcome::WatcherDied,
                    }
                }

                result = pipeline::run_pipeline(
                    &self.config,
                    &self.root,
                    display.as_mut(),
                    spinner_interval,
                    trigger_paths.as_deref(),
                    rerun_filter.as_deref(),
                ) => RunOutcome::Completed(result),
            };

            // Pipeline future is dropped here — all child processes killed,
            // all borrows released. `display` is available again.
            match outcome {
                RunOutcome::Completed(result) => {
                    let results = result?;
                    log_run_outcome(write_run_log(&self.root, &results), dc);

                    // Remember which steps failed so the browse-mode `f` key
                    // can rerun them; reset the filter so the next iteration
                    // doesn't accidentally re-apply it.
                    last_failed_steps = Some(
                        results
                            .iter()
                            .filter(|r| !r.success)
                            .map(|r| r.name.clone())
                            .collect(),
                    );
                    rerun_filter = None;

                    // Cancel any leftover hook from a prior run; spawn a new
                    // one if this run failed and the user has on_failure enabled.
                    cancel_hook(&mut hook_handle, display.as_mut());
                    if self.config.on_failure.enabled && results.iter().any(|r| !r.success) {
                        let cfg = self.config.on_failure.clone();
                        let cwd = self.root.clone();
                        let combined = pipeline::combine_failed_output(&results);
                        hook_handle = Some(tokio::spawn(async move {
                            pipeline::run_hook(&cfg, &cwd, &combined).await
                        }));
                        display.hook_started();
                    }
                }
                RunOutcome::FileChange(paths) => {
                    cancel_hook(&mut hook_handle, display.as_mut());
                    display.run_cancelled();
                    trigger_paths = Some(self.on_file_change(&paths, &mut rx, display.as_mut()));
                    file_triggered = true;
                    continue;
                }
                RunOutcome::Shutdown => {
                    cancel_hook(&mut hook_handle, display.as_mut());
                    return self.shutdown();
                }
                RunOutcome::WatcherDied => {
                    eprintln!("baraddur: file watcher stopped unexpectedly. exiting.");
                    return Ok(());
                }
            }

            // ── Idle: wait for the next file change or Ctrl+C ───────────────
            debug_log!(dc, "idle — waiting for file change");

            // In TTY mode, enter interactive browse mode so the user can
            // navigate steps and expand output with vim-style keybindings.
            if dc.is_tty {
                let key_rx = key_rx
                    .as_mut()
                    .expect("key_rx initialized when dc.is_tty is true");

                // Discard any keystrokes that queued up during the pipeline run.
                while key_rx.try_recv().is_ok() {}

                display.enter_browse_mode();

                loop {
                    tokio::select! {
                        biased;

                        _ = &mut stop => {
                            cancel_hook(&mut hook_handle, display.as_mut());
                            display.exit_browse_mode();
                            return self.shutdown();
                        }

                        maybe = rx.recv() => {
                            cancel_hook(&mut hook_handle, display.as_mut());
                            display.exit_browse_mode();
                            match maybe {
                                Some(paths) => {
                                    trigger_paths = Some(self.on_file_change(&paths, &mut rx, display.as_mut()));
                                    file_triggered = true;
                                    continue 'main;
                                }
                                None => {
                                    eprintln!("baraddur: file watcher stopped unexpectedly. exiting.");
                                    return Ok(());
                                }
                            }
                        }

                        maybe_key = key_rx.recv() => {
                            match maybe_key {
                                Some(key) => match display.handle_key(key) {
                                    BrowseAction::Noop => {}
                                    BrowseAction::Redraw => display.browse_redraw_if_active(),
                                    BrowseAction::Quit => {
                                        cancel_hook(&mut hook_handle, display.as_mut());
                                        display.exit_browse_mode();
                                        return self.shutdown();
                                    }
                                    action @ (BrowseAction::Rerun
                                    | BrowseAction::RerunFailed
                                    | BrowseAction::RerunCursor(_)) => {
                                        cancel_hook(&mut hook_handle, display.as_mut());
                                        display.exit_browse_mode();
                                        let (tp, rf) =
                                            Self::rerun_params(&action, &last_failed_steps);
                                        trigger_paths = tp;
                                        rerun_filter = rf;
                                        continue 'main;
                                    }
                                },
                                None => {
                                    display.exit_browse_mode();
                                    eprintln!("baraddur: keyboard reader stopped unexpectedly. exiting.");
                                    return Ok(());
                                }
                            }
                        }

                        // Hook task completed: forward its output (if any) into
                        // the browse-mode footer. Never breaks the loop — user
                        // stays in browse until a file change or `q`.
                        res = await_hook(&mut hook_handle), if hook_handle.is_some() => {
                            hook_handle = None;
                            apply_hook_result(res, display.as_mut());
                        }
                    }
                }
            }

            // Plain idle wait: non-TTY mode only (TTY mode loops inside browse above).
            // Loops so that an in-flight hook completion doesn't fall through —
            // we keep waiting for the next file-change or shutdown after it fires.
            'idle: loop {
                tokio::select! {
                    biased;

                    _ = &mut stop => {
                        cancel_hook(&mut hook_handle, display.as_mut());
                        return self.shutdown();
                    }

                    maybe = rx.recv() => {
                        cancel_hook(&mut hook_handle, display.as_mut());
                        match maybe {
                            Some(paths) => {
                                trigger_paths = Some(self.on_file_change(&paths, &mut rx, display.as_mut()));
                                file_triggered = true;
                                break 'idle; // fall through to loop top → rerun pipeline
                            }
                            None => {
                                eprintln!("baraddur: file watcher stopped unexpectedly. exiting.");
                                return Ok(());
                            }
                        }
                    }

                    res = await_hook(&mut hook_handle), if hook_handle.is_some() => {
                        hook_handle = None;
                        apply_hook_result(res, display.as_mut());
                        // continue idle loop — wait for next event
                    }
                }
            }
        }
    }

    /// Handles a file-change event shared by all three `run_until` sites (the
    /// running-pipeline arm, the browse-idle arm, and the non-TTY idle arm):
    /// drains any further queued events, logs the change, records the
    /// triggering paths on the display, and returns the relative paths for the
    /// caller to stash into `trigger_paths`. Hook cancellation and browse-mode
    /// exit stay at the call sites since they differ per arm.
    fn on_file_change(
        &self,
        paths: &[PathBuf],
        rx: &mut tokio::sync::mpsc::Receiver<watcher::WatchEvent>,
        display: &mut dyn Display,
    ) -> Vec<PathBuf> {
        while rx.try_recv().is_ok() {}
        let dc = &self.display_config;
        debug_log!(dc, "file change — triggering pipeline");
        for p in paths {
            debug_log!(dc, "  triggered by: {}", p.display());
        }
        let rel = rel_paths(paths, &self.root);
        display.set_trigger(&rel);
        rel
    }

    /// Maps a rerun browse action to the `(trigger_paths, rerun_filter)` the
    /// next pipeline run should use. Every rerun clears `trigger_paths` (reruns
    /// span the full file set, not the last trigger); they differ only in the
    /// step-name filter: full rerun → none, failed → last failed set, cursor →
    /// the single named step. Pure and unit-tested. Non-rerun actions map to
    /// `(None, None)` but are never passed here.
    fn rerun_params(
        action: &BrowseAction,
        last_failed: &Option<Vec<String>>,
    ) -> (Option<Vec<PathBuf>>, Option<Vec<String>>) {
        let rerun_filter = match action {
            BrowseAction::RerunFailed => last_failed.clone(),
            BrowseAction::RerunCursor(name) => Some(vec![name.clone()]),
            _ => None,
        };
        (None, rerun_filter)
    }

    fn shutdown(&self) -> Result<()> {
        eprintln!("\nbaraddur: exiting...");

        // Double-tap handler: a second Ctrl+C force-exits immediately.
        tokio::spawn(async {
            tokio::signal::ctrl_c().await.ok();
            eprintln!("baraddur: force exit.");
            std::process::exit(130);
        });

        Ok(())
    }
}

/// Awaits the on_failure hook task if one is in flight; otherwise pends
/// forever. Used as a select! arm so the main loop can react to hook
/// completion without blocking when no hook is active.
async fn await_hook(
    handle: &mut Option<HookHandle>,
) -> std::result::Result<Result<Option<String>>, tokio::task::JoinError> {
    match handle.as_mut() {
        Some(h) => h.await,
        None => std::future::pending().await,
    }
}

/// Aborts an in-flight `on_failure` hook task and notifies the display.
/// No-op when no hook is running. The display hook is a no-op on
/// `PlainDisplay`, so this is safe to call from non-TTY paths too.
fn cancel_hook(hook_handle: &mut Option<HookHandle>, display: &mut dyn Display) {
    if let Some(h) = hook_handle.take() {
        h.abort();
        display.hook_finished();
    }
}

/// Routes a settled hook's result to the display: forwards captured output
/// when present, otherwise clears the "running…" footer slot.
fn apply_hook_result(
    res: std::result::Result<Result<Option<String>>, tokio::task::JoinError>,
    display: &mut dyn Display,
) {
    match res {
        Ok(Ok(Some(text))) => display.hook_output(&text),
        _ => display.hook_finished(),
    }
}

/// Spawns a dedicated OS thread that loops on `crossterm::event::read()` and
/// forwards key events onto a channel. One reader per process — the channel
/// outlives any single browse-mode session, so file-change cancellation no
/// longer leaks blocked readers that steal subsequent keystrokes.
///
/// The thread exits when the receiver is dropped or `event::read()` errors.
fn spawn_key_reader() -> tokio::sync::mpsc::Receiver<crossterm::event::KeyEvent> {
    let (tx, rx) = tokio::sync::mpsc::channel(16);
    let _ = std::thread::Builder::new()
        .name("baraddur-keys".into())
        .spawn(move || {
            loop {
                match crossterm::event::read() {
                    Ok(crossterm::event::Event::Key(k)) => {
                        if tx.blocking_send(k).is_err() {
                            return;
                        }
                    }
                    Ok(_) => {}
                    Err(_) => return,
                }
            }
        });
    rx
}

/// Writes all step output for the last run to `.baraddur/last-run.log` and
/// returns the path written. Errors are surfaced to the caller (see
/// `log_run_outcome`) rather than silently swallowed, so "the log isn't being
/// created" is diagnosable instead of invisible.
fn write_run_log(root: &Path, results: &[StepResult]) -> std::io::Result<PathBuf> {
    let log_dir = root.join(".baraddur");
    std::fs::create_dir_all(&log_dir)?;

    let mut content = String::new();
    for r in results {
        let _ = writeln!(
            content,
            "═══ {} ({}) ═══",
            r.name,
            if r.success { "pass" } else { "FAIL" }
        );
        if !r.stdout.is_empty() {
            content.push_str(&r.stdout);
            if !r.stdout.ends_with('\n') {
                content.push('\n');
            }
        }
        if !r.stderr.is_empty() {
            content.push_str("--- stderr ---\n");
            content.push_str(&r.stderr);
            if !r.stderr.ends_with('\n') {
                content.push('\n');
            }
        }
        content.push('\n');
    }

    let path = log_dir.join("last-run.log");
    std::fs::write(&path, &content)?;
    Ok(path)
}

/// Reports the result of `write_run_log`. Success is debug-only noise; failure
/// is always surfaced because a run log that silently never appears is exactly
/// the kind of thing the user can't otherwise diagnose.
fn log_run_outcome(outcome: std::io::Result<PathBuf>, dc: &DisplayConfig) {
    match outcome {
        Ok(path) => debug_log!(dc, "wrote run log: {}", path.display()),
        Err(e) => eprintln!("baraddur: failed to write .baraddur/last-run.log: {e}"),
    }
}

/// Builds the always-on warning lines emitted when the loop guard trips,
/// naming the paths behind the latest restart so the user can fix the offending
/// step or add the paths to `[watch].ignore`. Pure (returns the lines) so the
/// path-count branches are unit-testable; `warn_loop` just prints them.
fn warn_loop_lines(paths: &[PathBuf]) -> Vec<String> {
    let mut lines = vec![
        format!(
            "baraddur: restart loop detected — the pipeline restarted {LOOP_THRESHOLD} times within {}s.",
            LOOP_WINDOW.as_secs()
        ),
        "baraddur: a step is likely modifying watched files (e.g. a formatter), which the watcher re-detects.".to_string(),
    ];
    if paths.is_empty() {
        lines.push("baraddur: (no triggering paths recorded for the latest restart)".to_string());
    } else {
        lines.push("baraddur: latest restart triggered by:".to_string());
        for p in paths.iter().take(10) {
            lines.push(format!("baraddur:   {}", p.display()));
        }
        if paths.len() > 10 {
            lines.push(format!("baraddur:   … and {} more", paths.len() - 10));
        }
    }
    lines.push(format!(
        "baraddur: pausing {}s to let changes settle. add these paths to [watch].ignore or fix the step to stop this.",
        LOOP_COOLDOWN.as_secs()
    ));
    lines
}

/// Prints the loop-guard warning. See `warn_loop_lines` for the content.
fn warn_loop(paths: &[PathBuf]) {
    for line in warn_loop_lines(paths) {
        eprintln!("{line}");
    }
}

/// Outcome of a loop-guard `cooldown`.
enum Flow {
    /// Cooldown elapsed; resume normal operation.
    Resume,
    /// Stop signal fired during the cooldown.
    Shutdown,
    /// Watcher channel closed during the cooldown.
    WatcherDied,
}

/// Waits out a loop-guard cooldown: drains and ignores file-change events for
/// `dur` so self-inflicted churn settles, then resumes. Returns early if the
/// stop signal fires or the watcher dies. Draining (rather than buffering)
/// means the post-cooldown run uses the current file state, not a backlog.
async fn cooldown<F>(
    stop: &mut std::pin::Pin<&mut F>,
    rx: &mut tokio::sync::mpsc::Receiver<watcher::WatchEvent>,
    dur: Duration,
) -> Flow
where
    F: Future<Output = ()>,
{
    let deadline = tokio::time::Instant::now() + dur;
    loop {
        tokio::select! {
            biased;

            _ = stop.as_mut() => return Flow::Shutdown,

            _ = tokio::time::sleep_until(deadline) => return Flow::Resume,

            maybe = rx.recv() => {
                match maybe {
                    Some(_) => { while rx.try_recv().is_ok() {} }
                    None => return Flow::WatcherDied,
                }
            }
        }
    }
}

fn rel_paths(paths: &[PathBuf], root: &Path) -> Vec<PathBuf> {
    paths
        .iter()
        .map(|p| p.strip_prefix(root).unwrap_or(p).to_path_buf())
        .collect()
}

/// Replaces the current process with `args` on Unix; spawns+waits on
/// Windows. Returns the exit code only on Windows or when exec fails — on
/// Unix the successful path never returns.
fn exec_wrapped(args: &[String]) -> Result<i32> {
    let (program, rest) = args
        .split_first()
        .ok_or_else(|| anyhow::anyhow!("no command provided"))?;

    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        // `exec` only returns when it fails — on success the process image
        // is replaced and this function never returns.
        let err = std::process::Command::new(program).args(rest).exec();
        Err(anyhow::Error::new(err).context(format!("exec `{program}`")))
    }

    #[cfg(not(unix))]
    {
        use anyhow::Context as _;
        let status = std::process::Command::new(program)
            .args(rest)
            .status()
            .with_context(|| format!("spawning `{program}`"))?;
        Ok(status.code().unwrap_or(1))
    }
}

enum RunOutcome {
    Completed(Result<Vec<StepResult>>),
    FileChange(Vec<PathBuf>),
    Shutdown,
    WatcherDied,
}

#[cfg(test)]
mod apply_profile_tests {
    use super::*;
    use crate::config::{Config, OnFailureConfig, OutputConfig, Step, WatchConfig};

    fn step(name: &str) -> Step {
        Step {
            name: name.into(),
            cmd: "true".into(),
            parallel: false,
            if_changed: Vec::new(),
        }
    }

    fn cfg_with_steps(names: &[&str]) -> Config {
        Config {
            watch: WatchConfig {
                extensions: vec!["rs".into()],
                debounce_ms: 1000,
                ignore: vec![],
            },
            output: OutputConfig::default(),
            on_failure: OnFailureConfig::default(),
            steps: names.iter().map(|n| step(n)).collect(),
            profiles: std::collections::HashMap::new(),
        }
    }

    #[test]
    fn filters_steps_to_profile_members_preserving_order() {
        let mut cfg = cfg_with_steps(&["fmt", "check", "clippy", "test"]);
        cfg.profiles
            .insert("quick".into(), vec!["check".into(), "fmt".into()]);

        apply_profile(&mut cfg, "quick").unwrap();

        let names: Vec<&str> = cfg.steps.iter().map(|s| s.name.as_str()).collect();
        assert_eq!(names, vec!["fmt", "check"]);
    }

    #[test]
    fn errors_when_profile_name_unknown() {
        let mut cfg = cfg_with_steps(&["fmt"]);
        cfg.profiles.insert("quick".into(), vec!["fmt".into()]);

        let err = apply_profile(&mut cfg, "missing").unwrap_err();
        let s = err.to_string();
        assert!(s.contains("profile `missing` not found"), "msg: {s}");
        assert!(s.contains("quick"), "expected available list in msg: {s}");
    }

    #[test]
    fn errors_when_no_profiles_defined() {
        let mut cfg = cfg_with_steps(&["fmt"]);
        let err = apply_profile(&mut cfg, "anything").unwrap_err();
        assert!(err.to_string().contains("no profiles defined"));
    }

    #[test]
    fn errors_when_profile_resolves_to_zero_steps() {
        let mut cfg = cfg_with_steps(&["fmt"]);
        cfg.profiles.insert("ghost".into(), vec!["nope".into()]);
        let err = apply_profile(&mut cfg, "ghost").unwrap_err();
        assert!(err.to_string().contains("zero steps"));
    }
}

#[cfg(test)]
mod run_until_helpers_tests {
    use super::*;
    use crate::config::{Config, OnFailureConfig, OutputConfig, WatchConfig};
    use crate::output::{PlainDisplay, Theme, Verbosity};

    fn mk_app(root: PathBuf) -> App {
        App {
            config: Config {
                watch: WatchConfig {
                    extensions: vec!["rs".into()],
                    debounce_ms: 1000,
                    ignore: vec![],
                },
                output: OutputConfig::default(),
                on_failure: OnFailureConfig::default(),
                steps: vec![],
                profiles: std::collections::HashMap::new(),
            },
            config_path: root.join(".baraddur.toml"),
            root,
            display_config: DisplayConfig {
                is_tty: false,
                no_clear: true,
                verbosity: Verbosity::Normal,
                format: OutputFormat::Auto,
            },
            profile: None,
        }
    }

    #[test]
    fn rerun_params_full_rerun_clears_paths_and_filter() {
        let last = Some(vec!["a".to_string()]);
        let (tp, rf) = App::rerun_params(&BrowseAction::Rerun, &last);
        assert_eq!(tp, None);
        assert_eq!(rf, None, "full rerun ignores the last-failed set");
    }

    #[test]
    fn rerun_params_failed_uses_last_failed_set() {
        let last = Some(vec!["check".to_string(), "test".to_string()]);
        let (tp, rf) = App::rerun_params(&BrowseAction::RerunFailed, &last);
        assert_eq!(tp, None);
        assert_eq!(rf, Some(vec!["check".to_string(), "test".to_string()]));
    }

    #[test]
    fn rerun_params_failed_with_no_prior_failures_is_none() {
        let (tp, rf) = App::rerun_params(&BrowseAction::RerunFailed, &None);
        assert_eq!(tp, None);
        assert_eq!(rf, None);
    }

    #[test]
    fn rerun_params_cursor_targets_single_named_step() {
        let (tp, rf) = App::rerun_params(&BrowseAction::RerunCursor("clippy".into()), &None);
        assert_eq!(tp, None);
        assert_eq!(rf, Some(vec!["clippy".to_string()]));
    }

    #[test]
    fn on_file_change_returns_relative_paths_and_drains_queue() {
        let root = PathBuf::from("/proj");
        let app = mk_app(root.clone());
        let (tx, mut rx) = tokio::sync::mpsc::channel::<watcher::WatchEvent>(8);
        // A second batch queued during the run must be drained so the next
        // pipeline uses current state, not a backlog.
        tx.try_send(vec![root.join("other.rs")]).unwrap();
        let mut display = PlainDisplay::new(Theme::new(false), Verbosity::Normal);

        let rel = app.on_file_change(&[root.join("src/foo.rs")], &mut rx, &mut display);

        assert_eq!(rel, vec![PathBuf::from("src/foo.rs")]);
        assert!(
            rx.try_recv().is_err(),
            "queued events should be fully drained"
        );
    }

    #[test]
    fn warn_loop_lines_no_paths_uses_the_none_recorded_branch() {
        let lines = warn_loop_lines(&[]);
        assert!(
            lines
                .iter()
                .any(|l| l.contains("no triggering paths recorded")),
            "expected the empty-paths branch; got {lines:#?}"
        );
        assert!(
            !lines.iter().any(|l| l.contains("triggered by:")),
            "must not print a path list when there are none"
        );
    }

    #[test]
    fn warn_loop_lines_lists_each_path_when_ten_or_fewer() {
        let paths: Vec<PathBuf> = (0..3)
            .map(|i| PathBuf::from(format!("src/f{i}.rs")))
            .collect();
        let lines = warn_loop_lines(&paths);
        assert!(
            lines
                .iter()
                .any(|l| l.contains("latest restart triggered by:"))
        );
        for i in 0..3 {
            assert!(
                lines.iter().any(|l| l.ends_with(&format!("src/f{i}.rs"))),
                "missing path f{i}; got {lines:#?}"
            );
        }
        assert!(
            !lines.iter().any(|l| l.contains("more")),
            "no overflow line expected for ≤10 paths"
        );
    }

    #[test]
    fn warn_loop_lines_truncates_to_ten_with_overflow_count() {
        let paths: Vec<PathBuf> = (0..12).map(|i| PathBuf::from(format!("f{i}.rs"))).collect();
        let lines = warn_loop_lines(&paths);
        let path_lines = lines.iter().filter(|l| l.contains(".rs")).count();
        assert_eq!(path_lines, 10, "should list exactly the first 10 paths");
        assert!(
            lines.iter().any(|l| l.contains("… and 2 more")),
            "expected overflow count of 2; got {lines:#?}"
        );
    }
}