guardy 0.2.4

Fast, secure git hooks in Rust with secret scanning and protected file synchronization
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
use super::{
    cache::{HookFileCache, get_cached_git_repo},
    file_discovery::FileDiscoveryMethod,
    filters::{FilterParams, apply_file_filters},
};
use crate::{
    cli::output,
    config::hooks::{HookCommand, HookDefinition, HookScript},
    git::GitRepo,
    hooks::conditions,
    scan::Scanner,
};
use anyhow::{Context, Result, anyhow};
use std::{process::Command, sync::Arc, time::Duration};
#[derive(Debug, Clone)]
struct CommandResult {
    name: String,
    success: bool,
    skipped: bool,
    duration: Duration,
    output: String, // Captured stdout/stderr
}
#[derive(Default)]
pub struct HookExecutor;
impl HookExecutor {
    pub fn new() -> Self {
        Self
    }
    pub async fn execute(&self, hook_name: &str, args: &[String]) -> Result<()> {
        let total_start = std::time::Instant::now();
        tracing::trace!("🚀 Hook execution starting: {}", hook_name);
        use crate::config::CONFIG;
        // Access hooks config directly from CONFIG
        let config_start = std::time::Instant::now();
        let hooks_config = &CONFIG.hooks;
        tracing::trace!("⚡ Config access time: {:?}", config_start.elapsed());
        // TRACE: Check if config is being loaded
        tracing::trace!(
            "Hooks config loaded: skip_all={}, parallel={}",
            hooks_config.skip_all,
            hooks_config.parallel
        );
        tracing::trace!(
            "Pre-commit commands: {}",
            hooks_config.pre_commit.commands.len()
        );
        // Check global skip
        if hooks_config.skip_all {
            output::info!("All hooks are skipped (skip_all=true)");
            return Ok(());
        }
        // Get the specific hook config based on hook name
        let hook = match hook_name {
            "pre-commit" => &hooks_config.pre_commit,
            "commit-msg" => &hooks_config.commit_msg,
            "post-checkout" => &hooks_config.post_checkout,
            "pre-push" => &hooks_config.pre_push,
            "post-commit" => &hooks_config.post_commit,
            "post-merge" => &hooks_config.post_merge,
            _ => return Err(anyhow!("Hook '{}' not found in configuration", hook_name)),
        };
        if hook.skip {
            output::info!(&format!("Hook '{hook_name}' is skipped"));
            return Ok(());
        }
        // Print banner
        Self::print_banner(hook_name);
        // TRACE: Print hook configuration
        tracing::trace!(
            "Hook configuration: commands={}, scripts={}",
            hook.commands.len(),
            hook.scripts.len()
        );
        for (name, cmd) in &hook.commands {
            tracing::trace!("Command '{}': run='{}'", name, cmd.run);
        }
        // OPTIMIZATION: Use cached git repo and create lazy file cache
        let file_cache_start = std::time::Instant::now();
        let repo = get_cached_git_repo()?;
        let file_cache = Arc::new(HookFileCache::new(repo, hook_name));
        // Start parallel git precomputation (like lefthook) - now starts even earlier!
        file_cache.precompute();
        tracing::trace!(
            "⚡ File cache initialization time: {:?}",
            file_cache_start.elapsed()
        );
        // Collect all commands and scripts with their priorities
        let collect_start = std::time::Instant::now();
        let mut executables = self.collect_executables(hook, hook_name, args, &file_cache)?;
        tracing::trace!(
            "⚡ Executable collection time: {:?}",
            collect_start.elapsed()
        );
        // TRACE: Print collected executables
        tracing::trace!("Collected {} executables", executables.len());
        for exec in &executables {
            tracing::trace!(
                "Executable: name='{}', type={:?}, priority={}",
                exec.name,
                exec.exec_type,
                exec.priority
            );
        }
        // Sort by priority (lower numbers run first)
        let sort_start = std::time::Instant::now();
        executables.sort_by_key(|e| e.priority);
        tracing::trace!("⚡ Sort time: {:?}", sort_start.elapsed());
        // Group by priority for parallel execution within priority groups
        let group_start = std::time::Instant::now();
        let mut priority_groups: Vec<Vec<Executable>> = Vec::new();
        let mut current_priority = None;
        for exec in executables {
            if current_priority != Some(exec.priority) {
                priority_groups.push(Vec::new());
                current_priority = Some(exec.priority);
            }
            if let Some(group) = priority_groups.last_mut() {
                group.push(exec);
            }
        }
        tracing::trace!("⚡ Grouping time: {:?}", group_start.elapsed());
        // Execute each priority group and collect results
        let execution_start = std::time::Instant::now();
        let mut all_results = Vec::new();
        let mut has_failures = false;
        for (group_idx, group) in priority_groups.iter().enumerate() {
            if group.is_empty() {
                continue;
            }
            let group_exec_start = std::time::Instant::now();
            // Use hook-level or global parallel setting
            let parallel = hook.parallel || hooks_config.parallel;
            let max_concurrent = if parallel && group.len() > 1 {
                std::cmp::min(group.len(), system_profile::SYSTEM.recommended_cpu_workers)
            } else {
                1 // Sequential execution = parallel with concurrency 1
            };
            tracing::trace!(
                "🔀 Executing group {} with max {} concurrent ({} commands)",
                group_idx,
                max_concurrent,
                group.len()
            );
            match self
                .execute_group(group.clone(), &file_cache, max_concurrent, group_idx)
                .await
            {
                Ok(results) => {
                    all_results.extend(results);
                }
                Err(_) => {
                    has_failures = true;
                    // Continue to next group even if this one failed
                }
            }
            tracing::trace!(
                "⚡ Group {} execution time: {:?}",
                group_idx,
                group_exec_start.elapsed()
            );
        }
        tracing::trace!("⚡ Total execution time: {:?}", execution_start.elapsed());
        // Print summary with results
        Self::print_summary_with_results(total_start.elapsed(), &all_results);
        tracing::trace!("🏁 Total hook time: {:?}", total_start.elapsed());
        if has_failures {
            return Err(anyhow!("Hook failed"));
        }
        Ok(())
    }
    fn collect_executables(
        &self,
        hook: &HookDefinition,
        hook_name: &str,
        args: &[String],
        file_cache: &Arc<HookFileCache>,
    ) -> Result<Vec<Executable>> {
        let mut executables = Vec::new();
        let hook_def = Arc::new(hook.clone());
        // Create a single ConditionEvaluator with the cached repo for efficiency
        let evaluator = conditions::ConditionEvaluator::with_repo(file_cache.repo.clone());
        // Collect builtin commands from the builtin field
        for (idx, builtin_name) in hook.builtin.iter().enumerate() {
            executables.push(Executable {
                name: builtin_name.clone(),
                exec_type: ExecutableType::Builtin(builtin_name.clone()),
                priority: -(idx as i32) - 100, // Negative priority so builtins run before other commands
                command: None,
                script: None,
                hook_name: hook_name.to_string(),
                args: args.to_vec(),
                file_cache: file_cache.clone(),
                hook_definition: hook_def.clone(),
            });
        }
        // Collect commands
        for (name, cmd) in &hook.commands {
            // Check skip/only conditions
            if conditions::should_skip(&cmd.skip, &cmd.only, &evaluator)? {
                output::info!(&format!("Skipping command '{name}' due to conditions"));
                continue;
            }
            // Handle builtin commands
            if cmd.run.starts_with("guardy_builtin:") {
                let builtin = cmd.run.strip_prefix("guardy_builtin:").unwrap();
                executables.push(Executable {
                    name: name.clone(),
                    exec_type: ExecutableType::Builtin(builtin.to_string()),
                    priority: cmd.priority,
                    command: Some(cmd.clone()),
                    script: None,
                    hook_name: hook_name.to_string(),
                    args: args.to_vec(),
                    file_cache: file_cache.clone(),
                    hook_definition: hook_def.clone(),
                });
            } else {
                executables.push(Executable {
                    name: name.clone(),
                    exec_type: ExecutableType::Command,
                    priority: cmd.priority,
                    command: Some(cmd.clone()),
                    script: None,
                    hook_name: hook_name.to_string(),
                    args: args.to_vec(),
                    file_cache: file_cache.clone(),
                    hook_definition: hook_def.clone(),
                });
            }
        }
        // Collect scripts
        for (name, script) in &hook.scripts {
            executables.push(Executable {
                name: name.clone(),
                exec_type: ExecutableType::Script,
                priority: 0, // Scripts don't have explicit priority, use default
                command: None,
                script: Some(script.clone()),
                hook_name: hook_name.to_string(),
                args: args.to_vec(),
                file_cache: file_cache.clone(),
                hook_definition: hook_def.clone(),
            });
        }
        Ok(executables)
    }
    /// Execute a single executable with precomputed files for efficiency
    async fn run(exec: &Executable, precomputed_files: &PrecomputedFiles) -> CommandResult {
        let start = std::time::Instant::now();
        tracing::trace!(
            "▶️ Executing: {} ({})",
            exec.name,
            match &exec.exec_type {
                ExecutableType::Builtin(_) => "builtin",
                ExecutableType::Command => "command",
                ExecutableType::Script => "script",
            }
        );
        let result = match &exec.exec_type {
            ExecutableType::Builtin(builtin) => {
                let builtin_result = HookExecutor::run_builtin(
                    builtin,
                    &exec.hook_name,
                    &exec.args,
                    &exec.hook_definition,
                )
                .await;
                CommandResult {
                    name: exec.name.clone(),
                    success: builtin_result.is_ok(),
                    skipped: false,
                    duration: start.elapsed(),
                    output: String::new(), // Builtins print directly, no buffered output
                }
            }
            ExecutableType::Command => {
                let cmd = match exec.command.as_ref() {
                    Some(cmd) => cmd,
                    None => {
                        return CommandResult {
                            name: exec.name.clone(),
                            success: false,
                            skipped: false,
                            duration: start.elapsed(),
                            output: String::new(),
                        };
                    }
                };
                HookExecutor::run_command(
                    &exec.name,
                    cmd,
                    &exec.hook_name,
                    &exec.args,
                    &exec.file_cache,
                    precomputed_files,
                )
                .await
            }
            ExecutableType::Script => {
                let script = match exec.script.as_ref() {
                    Some(script) => script,
                    None => {
                        return CommandResult {
                            name: exec.name.clone(),
                            success: false,
                            skipped: false,
                            duration: start.elapsed(),
                            output: String::new(),
                        };
                    }
                };
                let script_result = HookExecutor::run_script(
                    &exec.name,
                    script,
                    &exec.hook_name,
                    precomputed_files,
                )
                .await;
                CommandResult {
                    name: exec.name.clone(),
                    success: script_result.is_ok(),
                    skipped: false,
                    duration: start.elapsed(),
                    output: String::new(), // Scripts print directly, no buffered output
                }
            }
        };
        tracing::trace!("⚡ Executable '{}' time: {:?}", exec.name, start.elapsed());
        result
    }
    async fn execute_group(
        &self,
        group: Vec<Executable>,
        file_cache: &Arc<HookFileCache>,
        max_concurrent: usize,
        group_idx: usize,
    ) -> Result<Vec<CommandResult>> {
        use tokio::sync::Mutex;
        // Analyze what file types are actually needed by commands in this group
        let precompute_start = std::time::Instant::now();
        let mut needs_staged_files = false;
        let mut needs_all_files = false;
        let mut needs_push_files = false;
        for exec in &group {
            if let Some(cmd) = &exec.command {
                // Check for file placeholders in command
                if cmd.run.contains("{staged_files}") {
                    needs_staged_files = true;
                }
                if cmd.run.contains("{all_files}") {
                    needs_all_files = true;
                }
                if cmd.run.contains("{push_files}") {
                    needs_push_files = true;
                }
                // Check for glob patterns that need file filtering
                // Determine what file list they would need based on hook type
                if !cmd.glob.is_empty() {
                    match exec.hook_name.as_str() {
                        "pre-commit" | "commit-msg" => {
                            needs_staged_files = true;
                        }
                        "pre-push" => {
                            needs_push_files = true;
                        }
                        _ => {
                            if cmd.all_files {
                                needs_all_files = true;
                            }
                        }
                    }
                }
            }
        }
        // Pre-compute only the file lists that are actually used
        let mut precomputed_files = PrecomputedFiles::default();
        if needs_staged_files {
            let staged_files: Vec<String> = file_cache
                .get_staged_files()
                .iter()
                .map(|p| p.to_string_lossy().to_string())
                .collect();
            precomputed_files.staged_files = Some(staged_files.into());
            tracing::trace!("Pre-computed staged_files for group {}", group_idx);
        }
        if needs_all_files {
            let all_files: Vec<String> = file_cache
                .get_all_files()
                .iter()
                .map(|p| p.to_string_lossy().to_string())
                .collect();
            precomputed_files.all_files = Some(all_files.into());
            tracing::trace!("Pre-computed all_files for group {}", group_idx);
        }
        if needs_push_files {
            let push_files: Vec<String> = file_cache
                .get_push_files()
                .iter()
                .map(|p| p.to_string_lossy().to_string())
                .collect();
            precomputed_files.push_files = Some(push_files.into());
            tracing::trace!("Pre-computed push_files for group {}", group_idx);
        }
        tracing::trace!(
            "⚡ File precomputation time: {:?}",
            precompute_start.elapsed()
        );
        // Execute commands in parallel, displaying output as each finishes
        let results = Arc::new(Mutex::new(Vec::new()));
        let semaphore = Arc::new(tokio::sync::Semaphore::new(max_concurrent));
        let precomputed_files = Arc::new(precomputed_files);
        let mut handles = Vec::new();
        for exec in group {
            let results = results.clone();
            let precomputed_files = precomputed_files.clone();
            let permit = semaphore.clone().acquire_owned().await?;

            // Show that this command is starting
            use supercli::starbase_styles::color::owo::OwoColorize;
            println!(
                "{}  {} {} {}",
                "".cyan(),
                exec.name.cyan(),
                "(started)".dimmed(),
                "".dimmed()
            );

            let handle = tokio::spawn(async move {
                let cmd_result = HookExecutor::run(&exec, &precomputed_files).await;

                // Display output immediately when this command finishes
                if !cmd_result.output.is_empty() {
                    print!("{}", cmd_result.output);
                }

                drop(permit);
                let mut res = results.lock().await;
                res.push(cmd_result);
            });
            handles.push(handle);
        }
        // Wait for all tasks to complete
        for handle in handles {
            handle.await?;
        }
        // Extract results
        let results = results.lock().await.clone();
        // Check if any failed
        let has_failures = results.iter().any(|r| !r.success);
        if has_failures {
            return Err(anyhow!("Some commands failed"));
        }
        Ok(results)
    }
    async fn run_script(
        name: &str,
        script: &HookScript,
        hook_name: &str,
        precomputed_files: &PrecomputedFiles,
    ) -> Result<()> {
        output::info!(&format!("Running script: {name}"));
        // Build script path
        let script_path = format!(".guardy/scripts/{hook_name}/{name}");
        if !std::path::Path::new(&script_path).exists() {
            return Err(anyhow!("Script file not found: {}", script_path));
        }
        // Build command based on runner
        let mut command = Command::new(&script.runner);
        command.arg(&script_path);
        // Add environment variables with placeholder substitution
        for (key, value) in &script.env {
            // For scripts, we don't have filtered_files, so use all available files
            let files = precomputed_files
                .staged_files
                .as_ref()
                .or(precomputed_files.all_files.as_ref())
                .map(|f| f.as_ref())
                .unwrap_or(&[]);
            let substituted_value = HookExecutor::substitute_placeholders(
                value,
                precomputed_files,
                files, // filtered_staged_files (not actually filtered for scripts)
                &[],   // filtered_custom_files (scripts don't support custom files command)
                hook_name,
                &[],  // hook_args (scripts don't get git hook arguments)
                name, // command_name (script name)
            )?;
            command.env(key, substituted_value);
        }
        let output = command.output()?;
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            output::error!(&format!("✗ Script '{name}' failed"));
            return Err(anyhow!("Script failed: {}", stderr));
        }
        output::success!(&format!("✓ Script '{name}' completed"));
        Ok(())
    }
    async fn run_builtin(
        builtin: &str,
        hook_name: &str,
        args: &[String],
        hook_def: &HookDefinition,
    ) -> Result<()> {
        match builtin {
            "scan_secrets" => {
                if hook_name != "pre-commit" {
                    return Ok(());
                }
                HookExecutor::scan_secrets().await
            }
            "conventional_commits" => {
                if hook_name != "commit-msg" || args.is_empty() {
                    return Ok(());
                }
                HookExecutor::validate_commit_msg(&args[0], hook_def).await
            }
            "ensure_clean" => {
                if hook_name != "pre-push" {
                    output::warning!("ensure_clean builtin only works in pre-push hook");
                    return Ok(());
                }
                HookExecutor::ensure_clean().await
            }
            unknown => {
                output::warning!(&format!("Unknown builtin command: {unknown}"));
                Ok(())
            }
        }
    }
    async fn scan_secrets() -> Result<()> {
        output::info!("Scanning for secrets...");
        let repo = GitRepo::discover()?;
        let staged_files = repo.get_staged_files()?;
        if staged_files.is_empty() {
            output::info!("No staged files to check");
            return Ok(());
        }
        let scanner = Scanner::new()?;
        let stats = scanner.scan(&staged_files)?;
        if stats.total_matches > 0 {
            output::error!(&format!(
                "❌ Found {} secrets in staged files",
                stats.total_matches
            ));
            // With streaming output, matches are already displayed during scan
            output::info!("See above for detailed match information.");
            println!("\nCommit aborted. Remove secrets before committing.");
            return Err(anyhow!("Secrets detected in staged files"));
        }
        output::success!(&format!(
            "✅ Scanned {} files - no secrets found",
            stats.files_scanned
        ));
        Ok(())
    }
    async fn validate_commit_msg(commit_file: &str, hook_def: &HookDefinition) -> Result<()> {
        output::info!("Validating commit message format...");

        // Get configuration (use defaults if not specified)
        let config = hook_def.conventional_commits.as_ref();
        let default_types = vec![
            "feat", "fix", "docs", "style", "refactor", "test", "chore", "build", "ci", "perf",
            "revert",
        ];
        let allowed_types = config
            .and_then(|c| c.allowed_types.as_ref())
            .map(|types| types.iter().map(|s| s.as_str()).collect::<Vec<_>>())
            .unwrap_or(default_types);
        let enforce_scope = config.map(|c| c.enforce_scope).unwrap_or(false);

        let commit_msg =
            std::fs::read_to_string(commit_file).context("Failed to read commit message file")?;

        // Remove comments and trailing whitespace
        let commit_msg = commit_msg
            .lines()
            .filter(|line| !line.starts_with('#'))
            .collect::<Vec<_>>()
            .join("\n")
            .trim()
            .to_string();

        if commit_msg.is_empty() {
            return Err(anyhow!("Empty commit message"));
        }

        // Use git-conventional to parse and validate
        // Note: git-conventional supports the ! breaking change indicator natively
        match git_conventional::Commit::parse(&commit_msg) {
            Ok(commit) => {
                let commit_type = commit.type_().as_str();

                // Check if the type is in allowed_types
                if !allowed_types.contains(&commit_type) {
                    output::error!(&format!(
                        "❌ Invalid commit type: '{}'\nAllowed types: {}",
                        commit_type,
                        allowed_types.join(", ")
                    ));
                    return Err(anyhow!("Commit type '{}' is not allowed", commit_type));
                }

                // Check scope requirement
                if enforce_scope && commit.scope().is_none() {
                    output::error!("❌ Scope is required but not provided");
                    output::info!("Expected format: <type>(<scope>): <description>");
                    output::info!("Examples:");
                    output::info!("  feat(auth): add login functionality");
                    output::info!("  fix(ui): correct button alignment");
                    return Err(anyhow!("Scope is required for all commits"));
                }

                let scope_str = commit.scope().map(|s| s.as_str()).unwrap_or("no scope");
                // Check if it's a breaking change (has ! or BREAKING CHANGE footer)
                let is_breaking = commit.breaking();
                let breaking_indicator = if is_breaking { " [BREAKING]" } else { "" };
                output::success!(&format!(
                    "✅ Valid conventional commit: {} ({}){breaking_indicator}",
                    commit_type, scope_str
                ));

                // Optional: Suggest adding scope for feat commits if not enforced
                if !enforce_scope && commit_type == "feat" && commit.scope().is_none() {
                    output::warning!("Consider adding a scope to feat commits");
                }
                Ok(())
            }
            Err(e) => {
                output::error!(&format!("❌ Invalid conventional commit format: {e}"));
                output::info!(&format!(
                    "Expected format: <type>(<scope>): <description>{}",
                    if enforce_scope {
                        " (scope required)"
                    } else {
                        ""
                    }
                ));
                output::info!("Examples:");
                output::info!("  feat(auth): add login functionality");
                output::info!("  fix(ui): correct button alignment");
                if !enforce_scope {
                    output::info!("  docs: update README");
                }
                Err(anyhow!(
                    "Commit message does not follow conventional commits format"
                ))
            }
        }
    }

    async fn ensure_clean() -> Result<()> {
        output::info!("Checking for uncommitted changes...");

        let repo = GitRepo::discover()?;
        let status = repo.get_status()?;

        if !status.is_empty() {
            output::error!(
                "Repository has uncommitted changes. Please commit them before pushing:"
            );
            for file in &status {
                println!("  {}", file);
            }
            return Err(anyhow!(
                "Uncommitted changes detected. Commit or stash them before pushing."
            ));
        }

        output::success!("✅ Repository is clean - ready to push");
        Ok(())
    }

    /// Execute command using precomputed files to avoid redundant operations
    async fn run_command(
        cmd_name: &str,
        cmd: &HookCommand,
        hook_name: &str,
        hook_args: &[String],
        _file_cache: &Arc<HookFileCache>,
        precomputed_files: &PrecomputedFiles,
    ) -> CommandResult {
        let cmd_start = std::time::Instant::now();
        // Use description if provided, otherwise use the command name from YAML
        let description = if !cmd.description.is_empty() {
            cmd.description.clone()
        } else {
            cmd_name.to_string()
        };
        // Determine file discovery method and use precomputed files when available
        let discovery_method = FileDiscoveryMethod::from_hook_command(cmd, hook_name);
        if discovery_method.should_skip() {
            use supercli::starbase_styles::color::owo::OwoColorize;
            let skip_msg = format!(
                " {} {} {} {}\n",
                "".dimmed(),
                description.dimmed(),
                "(skip)".dimmed(),
                "no matching files".yellow()
            );
            return CommandResult {
                name: description,
                success: true,
                skipped: true,
                duration: cmd_start.elapsed(),
                output: skip_msg,
            };
        }
        // Compute filtered_staged_files for {staged_files} placeholder (lefthook-compatible)
        // This applies glob/exclude/file_types filters to staged files
        let filtered_staged_files = if let Some(staged_files) = &precomputed_files.staged_files {
            let filter_params = FilterParams {
                glob: &cmd.glob,
                exclude: &cmd.exclude,
                root: cmd.root.as_deref(),
                file_types: &cmd.file_types,
            };
            match apply_file_filters(staged_files, filter_params) {
                Ok(filtered) => {
                    tracing::trace!("Filtered staged_files: {} files", filtered.len());
                    filtered
                }
                Err(e) => {
                    tracing::error!("Failed to filter staged files: {}", e);
                    return CommandResult {
                        name: description,
                        success: false,
                        skipped: false,
                        duration: cmd_start.elapsed(),
                        output: String::new(),
                    };
                }
            }
        } else {
            Vec::new()
        };
        // Compute filtered_custom_files for {files} placeholder (lefthook-compatible)
        // This runs the custom `files:` command and applies filters
        let filtered_custom_files = if let Some(files_cmd) = &cmd.files {
            tracing::trace!("Executing custom files command: {}", files_cmd);
            match HookExecutor::get_files_from_command(files_cmd) {
                Ok(custom_files) => {
                    let filter_params = FilterParams {
                        glob: &cmd.glob,
                        exclude: &cmd.exclude,
                        root: cmd.root.as_deref(),
                        file_types: &cmd.file_types,
                    };
                    match apply_file_filters(&custom_files, filter_params) {
                        Ok(filtered) => {
                            tracing::trace!("Filtered custom files: {} files", filtered.len());
                            filtered
                        }
                        Err(e) => {
                            tracing::error!("Failed to filter custom files: {}", e);
                            return CommandResult {
                                name: description,
                                success: false,
                                skipped: false,
                                duration: cmd_start.elapsed(),
                                output: String::new(),
                            };
                        }
                    }
                }
                Err(e) => {
                    tracing::error!("Failed to get files from command: {}", e);
                    return CommandResult {
                        name: description,
                        success: false,
                        skipped: false,
                        duration: cmd_start.elapsed(),
                        output: String::new(),
                    };
                }
            }
        } else {
            Vec::new()
        };
        // Skip command if glob patterns or file placeholders are specified but no files matched
        let has_file_requirement = !cmd.glob.is_empty()
            || cmd.run.contains("{staged_files}")
            || cmd.run.contains("{files}");
        let has_matching_files =
            !filtered_staged_files.is_empty() || !filtered_custom_files.is_empty();
        if has_file_requirement && !has_matching_files {
            use supercli::starbase_styles::color::owo::OwoColorize;
            let skip_msg = format!(
                " {} {} {} {}\n",
                "".dimmed(),
                description.dimmed(),
                "(skip)".dimmed(),
                "no matching files".yellow()
            );
            return CommandResult {
                name: description,
                success: true,
                skipped: true,
                duration: cmd_start.elapsed(),
                output: skip_msg,
            };
        }
        // Build command with file substitution
        let subst_start = std::time::Instant::now();
        let command_str = match HookExecutor::substitute_placeholders(
            &cmd.run,
            precomputed_files,
            &filtered_staged_files,
            &filtered_custom_files,
            hook_name,
            hook_args,
            cmd_name,
        ) {
            Ok(cmd_str) => cmd_str,
            Err(e) => {
                tracing::error!("Failed to substitute placeholders: {}", e);
                return CommandResult {
                    name: description,
                    success: false,
                    skipped: false,
                    duration: cmd_start.elapsed(),
                    output: String::new(),
                };
            }
        };
        tracing::trace!(
            "⚡ Placeholder substitution time: {:?}",
            subst_start.elapsed()
        );
        // Execute the command
        tracing::trace!("🔧 Executing command: {}", command_str);
        let exec_start = std::time::Instant::now();
        let mut command = Command::new("sh");
        command.arg("-c").arg(&command_str);
        // Set working directory if root is specified
        if let Some(root_dir) = &cmd.root {
            command.current_dir(root_dir);
            tracing::trace!("Setting working directory to: {}", root_dir);
        }
        // Set environment variables with placeholder substitution
        for (key, value) in &cmd.env {
            let substituted_value = match HookExecutor::substitute_placeholders(
                value,
                precomputed_files,
                &filtered_staged_files,
                &filtered_custom_files,
                hook_name,
                hook_args,
                cmd_name,
            ) {
                Ok(val) => val,
                Err(e) => {
                    tracing::error!("Failed to substitute env var placeholder: {}", e);
                    return CommandResult {
                        name: description,
                        success: false,
                        skipped: false,
                        duration: cmd_start.elapsed(),
                        output: String::new(),
                    };
                }
            };
            command.env(key, substituted_value);
        }
        use supercli::starbase_styles::color::owo::OwoColorize;

        // Execute command and capture output
        let output_result = command.output().unwrap_or_else(|e| {
            tracing::error!("Failed to execute command: {}", e);
            std::process::Output {
                status: std::process::ExitStatus::default(),
                stdout: Vec::new(),
                stderr: Vec::new(),
            }
        });
        tracing::trace!("⚡ Command execution time: {:?}", exec_start.elapsed());

        let success = output_result.status.success();

        // Build formatted output (starting line is printed separately when command starts)
        let mut output_buffer = String::new();

        // Add stdout if present
        if !output_result.stdout.is_empty() {
            let stdout = String::from_utf8_lossy(&output_result.stdout);
            output_buffer.push_str(&stdout);
            if !stdout.ends_with('\n') {
                output_buffer.push('\n');
            }
        }

        // Add stderr if present
        if !output_result.stderr.is_empty() {
            let stderr = String::from_utf8_lossy(&output_result.stderr);
            output_buffer.push_str(&stderr);
            if !stderr.ends_with('\n') {
                output_buffer.push('\n');
            }
        }

        // Add status line
        if success {
            output_buffer.push_str(&format!(
                " {} {} {}\n",
                "".bright_green(),
                description.cyan(),
                "(passed)".bright_green()
            ));
        } else {
            output_buffer.push_str(&format!(
                " {} {} {}\n",
                "".bright_red(),
                description.cyan(),
                "(failed)".bright_red()
            ));
        }

        tracing::trace!("⚡ Total command time: {:?}", cmd_start.elapsed());
        CommandResult {
            name: description,
            success,
            skipped: false,
            duration: cmd_start.elapsed(),
            output: output_buffer,
        }
    }
    /// Substitute placeholders using precomputed files (optimized for parallel execution)
    fn substitute_placeholders(
        command: &str,
        precomputed_files: &PrecomputedFiles,
        filtered_staged_files: &[String],
        filtered_custom_files: &[String],
        hook_name: &str,
        hook_args: &[String],
        command_name: &str,
    ) -> Result<String> {
        let mut result = command.to_string();
        // Substitute {staged_files} placeholder - use filtered staged files (lefthook-compatible)
        // This respects glob patterns, unlike the old behavior
        if result.contains("{staged_files}") {
            let files_str = filtered_staged_files.join(" ");
            result = result.replace("{staged_files}", &files_str);
        }
        // Substitute {files} placeholder - use filtered custom files (lefthook-compatible)
        // Requires a custom `files:` command in the configuration
        if result.contains("{files}") {
            let files_str = filtered_custom_files.join(" ");
            result = result.replace("{files}", &files_str);
        }
        // Substitute {all_files} placeholder
        if result.contains("{all_files}")
            && let Some(all_files) = &precomputed_files.all_files
        {
            let files_str = all_files.join(" ");
            result = result.replace("{all_files}", &files_str);
        }
        // Substitute {push_files} placeholder
        if result.contains("{push_files}")
            && hook_name == "pre-push"
            && let Some(push_files) = &precomputed_files.push_files
        {
            let files_str = push_files.join(" ");
            result = result.replace("{push_files}", &files_str);
        }
        // Substitute {cmd} placeholder - the command itself
        if result.contains("{cmd}") {
            result = result.replace("{cmd}", command);
        }
        // Substitute {guardy_job_name} placeholder - current command name
        if result.contains("{guardy_job_name}") {
            result = result.replace("{guardy_job_name}", command_name);
        }
        // Substitute {0} - all hook arguments as a single space-joined string
        if result.contains("{0}") {
            let args_str = hook_args.join(" ");
            result = result.replace("{0}", &args_str);
        }
        // Substitute {N} - Nth hook argument (1-indexed like lefthook)
        for (idx, arg) in hook_args.iter().enumerate() {
            let placeholder = format!("{{{}}}", idx + 1);
            if result.contains(&placeholder) {
                result = result.replace(&placeholder, arg);
            }
        }
        Ok(result)
    }
    /// Execute a custom files command and return the list of files
    fn get_files_from_command(files_cmd: &str) -> Result<Vec<String>> {
        tracing::trace!("Executing files command: {}", files_cmd);
        let output = if cfg!(target_os = "windows") {
            Command::new("cmd")
                .args(["/C", files_cmd])
                .output()
                .with_context(|| format!("Failed to execute files command: {files_cmd}"))?
        } else {
            Command::new("sh")
                .args(["-c", files_cmd])
                .output()
                .with_context(|| format!("Failed to execute files command: {files_cmd}"))?
        };
        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(anyhow!("Files command failed: {}", stderr));
        }
        let stdout = String::from_utf8_lossy(&output.stdout);
        let files: Vec<String> = stdout
            .lines()
            .map(|line| line.trim().to_string())
            .filter(|line| !line.is_empty())
            .collect();
        tracing::trace!("Files command returned {} files", files.len());
        Ok(files)
    }
    fn print_banner(hook_name: &str) {
        use crate::cli::banner;
        use supercli::starbase_styles::color::owo::OwoColorize;

        // Format hook context with color and pass to shared banner
        let hook_context = format!("hook: {}", hook_name.yellow().bold());
        banner::print_banner(Some(&hook_context));
    }
    /// Print summary at the end
    fn print_summary_with_results(duration: std::time::Duration, results: &[CommandResult]) {
        use supercli::starbase_styles::color::owo::OwoColorize;
        let secs = duration.as_secs_f64();
        println!("  {}", "".repeat(35).dimmed());
        println!(
            "{} {}",
            "summary:".cyan(),
            format!("(done in {:.2} seconds)", secs).dimmed()
        );
        // Print results
        for result in results {
            let duration_secs = result.duration.as_secs_f64();
            if result.skipped {
                println!(
                    "{} {} {}",
                    result.name.dimmed(),
                    "(skipped)".dimmed(),
                    format!("({:.2} seconds)", duration_secs).dimmed()
                );
            } else if result.success {
                println!(
                    "{} {}",
                    result.name.green(),
                    format!("({:.2} seconds)", duration_secs).dimmed()
                );
            } else {
                println!(
                    "{} {}",
                    result.name.red(),
                    format!("({:.2} seconds)", duration_secs).dimmed()
                );
            }
        }
    }
}
// Optimized file storage for group-level precomputation
// Arc<[String]> is more efficient than Arc<Vec<String>> (no capacity field)
#[derive(Default)]
struct PrecomputedFiles {
    staged_files: Option<Arc<[String]>>,
    all_files: Option<Arc<[String]>>,
    push_files: Option<Arc<[String]>>,
}
// Structures for organizing executables
#[derive(Clone)]
struct Executable {
    name: String,
    exec_type: ExecutableType,
    priority: i32,
    command: Option<HookCommand>,
    script: Option<HookScript>,
    hook_name: String,
    args: Vec<String>,
    file_cache: Arc<HookFileCache>,
    hook_definition: Arc<HookDefinition>,
}
#[derive(Clone, Debug)]
enum ExecutableType {
    Builtin(String),
    Command,
    Script,
}