rch 2.1.4

Remote Compilation Helper - PreToolUse hook CLI
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
//! E2E Tests for Hook Integration with Detailed Logging
//!
//! Tests the shell hook that intercepts compilation commands.
//! These tests verify:
//! - Command classification accuracy (intercept vs ignore)
//! - Timing budget compliance (P99 < 5ms for classification)
//! - Fallback behavior when daemon unavailable
//! - Environment variable handling
//!
//! Uses the E2E test harness from rch-common.

use rch_common::e2e::{HarnessResult, HookInputFixture, TestHarness, TestHarnessBuilder};
use rch_common::test_guard;
use rch_common::{Classification, TierDecision, classify_command, classify_command_detailed};
use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

// ============================================================================
// Test Helpers
// ============================================================================

/// Create a test harness configured for hook tests.
fn create_hook_harness(test_name: &str) -> HarnessResult<TestHarness> {
    // Respect CARGO_TARGET_DIR if set, otherwise use default target/debug
    let target_dir = if let Ok(target_dir) = std::env::var("CARGO_TARGET_DIR") {
        PathBuf::from(target_dir).join("debug")
    } else {
        let manifest_dir = std::env::var("CARGO_MANIFEST_DIR")
            .map(PathBuf::from)
            .unwrap_or_else(|_| PathBuf::from("."));
        let project_root = manifest_dir.parent().unwrap_or(&manifest_dir);
        project_root.join("target/debug")
    };

    TestHarnessBuilder::new(test_name)
        .cleanup_on_success(true)
        .cleanup_on_failure(false)
        .default_timeout(Duration::from_secs(30))
        .rch_binary(target_dir.join("rch"))
        .rchd_binary(target_dir.join("rchd"))
        .rch_wkr_binary(target_dir.join("rch-wkr"))
        .build()
}

/// Run the hook binary with stdin input and capture output.
/// Returns (exit_code, stdout, stderr, duration).
#[allow(dead_code)]
fn run_hook_with_input(
    harness: &TestHarness,
    hook_input: &str,
    env_vars: Option<Vec<(&str, &str)>>,
) -> HarnessResult<(i32, String, String, Duration)> {
    let start = Instant::now();

    let mut cmd = Command::new(&harness.config.rch_binary);
    cmd.arg("hook")
        .arg("--input-format=json")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .current_dir(harness.test_dir());

    // Add environment variables if provided
    if let Some(vars) = env_vars {
        for (key, value) in vars {
            cmd.env(key, value);
        }
    }

    let mut child = cmd.spawn().map_err(|e| {
        rch_common::e2e::HarnessError::ProcessStartFailed(format!("Failed to spawn hook: {}", e))
    })?;

    // Write input to stdin
    if let Some(mut stdin) = child.stdin.take() {
        use std::io::Write;
        stdin.write_all(hook_input.as_bytes()).ok();
    }

    // Wait for process to complete
    let output = child.wait_with_output().map_err(|e| {
        rch_common::e2e::HarnessError::ProcessStartFailed(format!("Failed to wait for hook: {}", e))
    })?;

    let duration = start.elapsed();

    Ok((
        output.status.code().unwrap_or(-1),
        String::from_utf8_lossy(&output.stdout).to_string(),
        String::from_utf8_lossy(&output.stderr).to_string(),
        duration,
    ))
}

/// Classify a command and log the result for test diagnostics.
fn classify_and_log(harness: &TestHarness, command: &str) -> Classification {
    let start = Instant::now();
    let result = classify_command(command);
    let duration = start.elapsed();

    harness.logger.log_with_context(
        rch_common::e2e::LogLevel::Info,
        rch_common::e2e::LogSource::Custom("classify".to_string()),
        format!(
            "command='{}' is_compilation={} confidence={:.2} kind={:?}",
            command, result.is_compilation, result.confidence, result.kind
        ),
        vec![
            ("duration_us".to_string(), duration.as_micros().to_string()),
            ("reason".to_string(), result.reason.to_string()),
        ],
    );

    result
}

// ============================================================================
// Classification Tests - Commands to INTERCEPT
// ============================================================================

#[test]
fn test_hook_intercepts_cargo_build() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_cargo_build").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_intercepts_cargo_build");

    // Test basic cargo build
    let result = classify_and_log(&harness, "cargo build");
    harness
        .assert(result.is_compilation, "cargo build should be intercepted")
        .unwrap();
    assert!(
        result.confidence >= 0.95,
        "cargo build confidence should be >= 0.95"
    );

    // Test cargo build --release
    let result = classify_and_log(&harness, "cargo build --release");
    harness
        .assert(
            result.is_compilation,
            "cargo build --release should be intercepted",
        )
        .unwrap();
    assert!(result.confidence >= 0.95);

    // Test cargo build with target
    let result = classify_and_log(&harness, "cargo build --target x86_64-unknown-linux-gnu");
    harness
        .assert(
            result.is_compilation,
            "cargo build with target should be intercepted",
        )
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_intercepts_cargo_build");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_cargo_test() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_cargo_test").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_intercepts_cargo_test");

    // Test cargo test
    let result = classify_and_log(&harness, "cargo test");
    harness
        .assert(result.is_compilation, "cargo test should be intercepted")
        .unwrap();
    assert!(result.confidence >= 0.95);

    // Test cargo test with package
    let result = classify_and_log(&harness, "cargo test -p my_crate");
    harness
        .assert(result.is_compilation, "cargo test -p should be intercepted")
        .unwrap();

    // Test cargo test with specific test
    let result = classify_and_log(&harness, "cargo test test_my_function");
    harness
        .assert(
            result.is_compilation,
            "cargo test with name should be intercepted",
        )
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_intercepts_cargo_test");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_cargo_check() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_cargo_check").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_intercepts_cargo_check");

    let result = classify_and_log(&harness, "cargo check");
    harness
        .assert(result.is_compilation, "cargo check should be intercepted")
        .unwrap();
    assert!(result.confidence >= 0.90);

    harness
        .logger
        .info("TEST PASS: test_hook_intercepts_cargo_check");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_rustc() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_rustc").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_intercepts_rustc");

    let result = classify_and_log(&harness, "rustc main.rs");
    harness
        .assert(result.is_compilation, "rustc should be intercepted")
        .unwrap();
    assert!(result.confidence >= 0.95);

    harness.logger.info("TEST PASS: test_hook_intercepts_rustc");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_bun_test() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_bun_test").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_intercepts_bun_test");

    let result = classify_and_log(&harness, "bun test");
    harness
        .assert(result.is_compilation, "bun test should be intercepted")
        .unwrap();
    assert!(result.confidence >= 0.95);

    // With coverage
    let result = classify_and_log(&harness, "bun test --coverage");
    harness
        .assert(
            result.is_compilation,
            "bun test --coverage should be intercepted",
        )
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_intercepts_bun_test");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_bun_typecheck() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_bun_typecheck").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_intercepts_bun_typecheck");

    let result = classify_and_log(&harness, "bun typecheck");
    harness
        .assert(result.is_compilation, "bun typecheck should be intercepted")
        .unwrap();
    assert!(result.confidence >= 0.95);

    harness
        .logger
        .info("TEST PASS: test_hook_intercepts_bun_typecheck");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_gcc() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_gcc").unwrap();

    harness.logger.info("TEST START: test_hook_intercepts_gcc");

    let result = classify_and_log(&harness, "gcc -o main main.c");
    harness
        .assert(
            result.is_compilation,
            "gcc compilation should be intercepted",
        )
        .unwrap();
    assert!(result.confidence >= 0.90);

    harness.logger.info("TEST PASS: test_hook_intercepts_gcc");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_make() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_make").unwrap();

    harness.logger.info("TEST START: test_hook_intercepts_make");

    let result = classify_and_log(&harness, "make -j8");
    harness
        .assert(result.is_compilation, "make -j8 should be intercepted")
        .unwrap();
    assert!(result.confidence >= 0.85);

    harness.logger.info("TEST PASS: test_hook_intercepts_make");
    harness.mark_passed();
}

#[test]
fn test_hook_intercepts_cmake_build() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_intercepts_cmake_build").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_intercepts_cmake_build");

    let result = classify_and_log(&harness, "cmake --build .");
    harness
        .assert(result.is_compilation, "cmake --build should be intercepted")
        .unwrap();
    assert!(result.confidence >= 0.85);

    harness
        .logger
        .info("TEST PASS: test_hook_intercepts_cmake_build");
    harness.mark_passed();
}

// ============================================================================
// Classification Tests - Commands to IGNORE
// ============================================================================

#[test]
fn test_hook_ignores_non_compilation() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_ignores_non_compilation").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_ignores_non_compilation");

    // Test ls
    let result = classify_and_log(&harness, "ls -la");
    harness
        .assert(!result.is_compilation, "ls should NOT be intercepted")
        .unwrap();

    // Test cd
    let result = classify_and_log(&harness, "cd /tmp");
    harness
        .assert(!result.is_compilation, "cd should NOT be intercepted")
        .unwrap();

    // Test echo
    let result = classify_and_log(&harness, "echo hello");
    harness
        .assert(!result.is_compilation, "echo should NOT be intercepted")
        .unwrap();

    // Test cat
    let result = classify_and_log(&harness, "cat file.txt");
    harness
        .assert(!result.is_compilation, "cat should NOT be intercepted")
        .unwrap();

    // Test git
    let result = classify_and_log(&harness, "git status");
    harness
        .assert(!result.is_compilation, "git should NOT be intercepted")
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_ignores_non_compilation");
    harness.mark_passed();
}

#[test]
fn test_hook_offloads_benign_piped_commands() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_offloads_benign_piped").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_offloads_benign_piped_commands");

    // Issue #24: pipes into benign pagers are preserved and offloaded.
    let result = classify_and_log(&harness, "cargo build | tee log");
    harness
        .assert(
            result.is_compilation,
            "cargo build piped into tee should be intercepted",
        )
        .unwrap();
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("cargo build | tee log")
    );

    // Piped with grep
    let result = classify_and_log(&harness, "cargo build 2>&1 | grep error");
    harness
        .assert(
            result.is_compilation,
            "cargo build piped into grep should be intercepted",
        )
        .unwrap();
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("cargo build 2>&1 | grep error")
    );

    // Piped bun test
    let result = classify_and_log(&harness, "bun test | grep PASS");
    harness
        .assert(
            result.is_compilation,
            "bun test piped into grep should be intercepted",
        )
        .unwrap();
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("bun test | grep PASS")
    );

    // Pipes into non-pagers remain fail-closed.
    let result = classify_and_log(&harness, "cargo build | xargs rm");
    harness
        .assert(
            !result.is_compilation,
            "cargo build piped into xargs must not be intercepted",
        )
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_offloads_benign_piped_commands");
    harness.mark_passed();
}

#[test]
fn test_hook_offloads_output_redirected_commands() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_offloads_output_redirected").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_offloads_output_redirected_commands");

    // Issue #24: output-only redirects are preserved and offloaded.
    let result = classify_and_log(&harness, "cargo build > output.txt");
    harness
        .assert(
            result.is_compilation,
            "stdout-redirected cargo build should be intercepted",
        )
        .unwrap();
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("cargo build > output.txt")
    );

    // Stderr redirection
    let result = classify_and_log(&harness, "cargo build 2> errors.txt");
    harness
        .assert(
            result.is_compilation,
            "stderr-redirected cargo build should be intercepted",
        )
        .unwrap();
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("cargo build 2> errors.txt")
    );

    // Combined redirection
    let result = classify_and_log(&harness, "cargo build > out.txt 2>&1");
    harness
        .assert(
            result.is_compilation,
            "combined output redirect should be intercepted",
        )
        .unwrap();
    assert_eq!(
        result.extracted_command.as_deref(),
        Some("cargo build > out.txt 2>&1")
    );

    // Input redirects alter the compiler's input and remain fail-closed.
    let result = classify_and_log(&harness, "cargo build < input.txt");
    harness
        .assert(
            !result.is_compilation,
            "input-redirected cargo build must not be intercepted",
        )
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_offloads_output_redirected_commands");
    harness.mark_passed();
}

#[test]
fn test_hook_offloads_background_commands() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_offloads_background").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_offloads_background_commands");

    // Issue #24: trailing background operators are preserved and offloaded.
    let result = classify_and_log(&harness, "cargo build &");
    harness
        .assert(
            result.is_compilation,
            "backgrounded cargo build should be intercepted",
        )
        .unwrap();
    assert_eq!(result.extracted_command.as_deref(), Some("cargo build &"));

    // Backgrounded bun test
    let result = classify_and_log(&harness, "bun test &");
    harness
        .assert(
            result.is_compilation,
            "backgrounded bun test should be intercepted",
        )
        .unwrap();
    assert_eq!(result.extracted_command.as_deref(), Some("bun test &"));

    // A command after the background operator is not a benign suffix.
    let result = classify_and_log(&harness, "cargo build & echo done");
    harness
        .assert(
            !result.is_compilation,
            "backgrounded cargo build followed by another command must not be intercepted",
        )
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_offloads_background_commands");
    harness.mark_passed();
}

#[test]
fn test_hook_handles_chained_commands() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_handles_chained").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_handles_chained_commands");

    // && chained with compilation at end - NOW ACCEPTED for patterns like "cd && cargo build"
    let result = classify_and_log(&harness, "cargo build && cargo test");
    harness
        .assert(
            result.is_compilation,
            "&& chained commands with compilation suffix should be accepted",
        )
        .unwrap();
    assert!(result.reason.contains("compound"));

    // && chained with non-compilation at end - should be rejected
    let result = classify_and_log(&harness, "cargo build && echo done");
    harness
        .assert(
            !result.is_compilation,
            "&& chained commands with non-compilation suffix should be rejected",
        )
        .unwrap();

    // ; chained - always rejected (not supported)
    let result = classify_and_log(&harness, "cargo build; cargo test");
    harness
        .assert(
            !result.is_compilation,
            "; chained commands should be rejected",
        )
        .unwrap();
    assert!(result.reason.contains("chained"));

    // || chained - always rejected (not supported)
    let result = classify_and_log(&harness, "cargo build || echo failed");
    harness
        .assert(
            !result.is_compilation,
            "|| chained commands should be rejected",
        )
        .unwrap();
    assert!(result.reason.contains("chained"));

    harness
        .logger
        .info("TEST PASS: test_hook_handles_chained_commands");
    harness.mark_passed();
}

#[test]
fn test_hook_ignores_cargo_fmt() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_ignores_cargo_fmt").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_ignores_cargo_fmt");

    let result = classify_and_log(&harness, "cargo fmt");
    harness
        .assert(
            !result.is_compilation,
            "cargo fmt should NOT be intercepted",
        )
        .unwrap();
    assert!(
        result.reason.contains("never-intercept"),
        "Should match never-intercept pattern"
    );

    harness
        .logger
        .info("TEST PASS: test_hook_ignores_cargo_fmt");
    harness.mark_passed();
}

#[test]
fn test_hook_ignores_bun_install() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_ignores_bun_install").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_ignores_bun_install");

    let result = classify_and_log(&harness, "bun install");
    harness
        .assert(
            !result.is_compilation,
            "bun install should NOT be intercepted",
        )
        .unwrap();

    let result = classify_and_log(&harness, "bun add lodash");
    harness
        .assert(!result.is_compilation, "bun add should NOT be intercepted")
        .unwrap();

    let result = classify_and_log(&harness, "bun run dev");
    harness
        .assert(!result.is_compilation, "bun run should NOT be intercepted")
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_ignores_bun_install");
    harness.mark_passed();
}

#[test]
fn test_hook_ignores_bun_watch_mode() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_ignores_bun_watch").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_ignores_bun_watch_mode");

    // Watch mode is interactive - should not be intercepted
    let result = classify_and_log(&harness, "bun test --watch");
    harness
        .assert(
            !result.is_compilation,
            "bun test --watch should NOT be intercepted",
        )
        .unwrap();
    assert!(
        result.reason.contains("interactive"),
        "Should indicate interactive mode"
    );

    let result = classify_and_log(&harness, "bun typecheck --watch");
    harness
        .assert(
            !result.is_compilation,
            "bun typecheck --watch should NOT be intercepted",
        )
        .unwrap();

    harness
        .logger
        .info("TEST PASS: test_hook_ignores_bun_watch_mode");
    harness.mark_passed();
}

// ============================================================================
// Timing Budget Tests
// ============================================================================

#[test]
fn test_hook_timing_budget() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_timing_budget").unwrap();

    harness.logger.info("TEST START: test_hook_timing_budget");

    // Collect timing data for many classifications
    let commands = [
        "ls -la",
        "echo hello",
        "cargo build",
        "cargo test --release",
        "bun test",
        "gcc -o main main.c",
        "make -j8",
        "git status",
        "npm install",
        "cd /tmp",
    ];

    let mut non_compilation_times: Vec<f64> = Vec::new();
    let mut compilation_times: Vec<f64> = Vec::new();

    // Run each command multiple times for better statistics
    for _ in 0..10 {
        for cmd in &commands {
            let start = Instant::now();
            let result = classify_command(cmd);
            let duration_ms = start.elapsed().as_secs_f64() * 1000.0;

            if result.is_compilation {
                compilation_times.push(duration_ms);
            } else {
                non_compilation_times.push(duration_ms);
            }
        }
    }

    // Calculate P99 for non-compilation
    non_compilation_times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let p99_idx = (non_compilation_times.len() as f64 * 0.99) as usize;
    let p99_non_compilation = non_compilation_times
        .get(p99_idx.min(non_compilation_times.len() - 1))
        .copied()
        .unwrap_or(0.0);

    // Calculate P99 for compilation
    compilation_times.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let p99_idx = (compilation_times.len() as f64 * 0.99) as usize;
    let p99_compilation = compilation_times
        .get(p99_idx.min(compilation_times.len() - 1))
        .copied()
        .unwrap_or(0.0);

    harness.logger.log_with_context(
        rch_common::e2e::LogLevel::Info,
        rch_common::e2e::LogSource::Custom("timing".to_string()),
        format!(
            "TIMING: non_compilation_p99={:.3}ms compilation_p99={:.3}ms",
            p99_non_compilation, p99_compilation
        ),
        vec![
            (
                "non_compilation_count".to_string(),
                non_compilation_times.len().to_string(),
            ),
            (
                "compilation_count".to_string(),
                compilation_times.len().to_string(),
            ),
        ],
    );

    // Verify timing budgets per AGENTS.md:
    // - Non-compilation: <1ms (we allow up to 5ms for P99 due to system variance)
    // - Compilation: <5ms
    assert!(
        p99_non_compilation < 5.0,
        "Non-compilation P99 {:.3}ms should be < 5ms",
        p99_non_compilation
    );
    assert!(
        p99_compilation < 5.0,
        "Compilation P99 {:.3}ms should be < 5ms",
        p99_compilation
    );

    harness.logger.info(format!(
        "TEST PASS: test_hook_timing_budget (non_comp_p99={:.3}ms, comp_p99={:.3}ms)",
        p99_non_compilation, p99_compilation
    ));
    harness.mark_passed();
}

// ============================================================================
// Detailed Classification Tests
// ============================================================================

#[test]
fn test_hook_classification_details() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_classification_details").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_classification_details");

    // Test detailed classification for diagnostics
    let detailed = classify_command_detailed("cargo build --release");

    // Verify tier progression
    assert!(detailed.tiers.len() >= 4, "Should have at least 4 tiers");

    // Tier 0: Should pass (command present)
    let tier0 = detailed.tiers.iter().find(|t| t.tier == 0).unwrap();
    assert_eq!(tier0.decision, TierDecision::Pass, "Tier 0 should pass");

    // Tier 1: Should pass (no structure issues)
    let tier1 = detailed.tiers.iter().find(|t| t.tier == 1).unwrap();
    assert_eq!(tier1.decision, TierDecision::Pass, "Tier 1 should pass");

    // Tier 2: Should pass (keyword present)
    let tier2 = detailed.tiers.iter().find(|t| t.tier == 2).unwrap();
    assert_eq!(tier2.decision, TierDecision::Pass, "Tier 2 should pass");

    // Tier 3: Should pass (not in never-intercept list)
    let tier3 = detailed.tiers.iter().find(|t| t.tier == 3).unwrap();
    assert_eq!(tier3.decision, TierDecision::Pass, "Tier 3 should pass");

    // Final classification
    assert!(detailed.classification.is_compilation);
    assert!(detailed.classification.confidence >= 0.95);

    harness
        .logger
        .info("TEST PASS: test_hook_classification_details");
    harness.mark_passed();
}

#[test]
fn test_hook_classification_details_piped_rejection() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_classification_details_piped").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_classification_details_piped_rejection");

    // Issue #24: a pipe into a NON-benign command is still rejected at Tier 1.
    // (Benign pagers such as `tee`/`head` are now offloaded instead.)
    let detailed = classify_command_detailed("cargo build | xargs rm");

    // Should be rejected at Tier 1 (structure analysis)
    let tier1 = detailed.tiers.iter().find(|t| t.tier == 1).unwrap();
    assert_eq!(
        tier1.decision,
        TierDecision::Reject,
        "Tier 1 should reject pipe into non-pager command"
    );
    assert!(
        tier1.reason.contains("piped"),
        "Reason should mention piped"
    );

    // Final classification should be non-compilation
    assert!(!detailed.classification.is_compilation);

    // A pipe into a benign pager IS now offloaded (Tier 1 passes).
    let offloaded = classify_command_detailed("cargo build | tee log.txt");
    assert!(offloaded.classification.is_compilation);
    assert_eq!(
        offloaded.classification.extracted_command.as_deref(),
        Some("cargo build | tee log.txt")
    );

    harness
        .logger
        .info("TEST PASS: test_hook_classification_details_piped_rejection");
    harness.mark_passed();
}

#[test]
fn test_hook_classification_details_never_intercept() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_classification_details_never_intercept").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_classification_details_never_intercept");

    let detailed = classify_command_detailed("cargo fmt");

    // Should pass Tier 0, 1, 2 but reject at Tier 3
    let tier3 = detailed.tiers.iter().find(|t| t.tier == 3).unwrap();
    assert_eq!(
        tier3.decision,
        TierDecision::Reject,
        "Tier 3 should reject cargo fmt"
    );
    assert!(
        tier3.reason.contains("never-intercept"),
        "Reason should mention never-intercept"
    );

    assert!(!detailed.classification.is_compilation);

    harness
        .logger
        .info("TEST PASS: test_hook_classification_details_never_intercept");
    harness.mark_passed();
}

// ============================================================================
// Wrapper Command Tests
// ============================================================================

#[test]
fn test_hook_wrapped_commands() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_wrapped_commands").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_wrapped_commands");

    // Commands with wrappers should be normalized and classified
    let result = classify_and_log(&harness, "time cargo build");
    harness
        .assert(
            result.is_compilation,
            "time cargo build should be intercepted",
        )
        .unwrap();

    let result = classify_and_log(&harness, "sudo cargo check");
    harness
        .assert(
            result.is_compilation,
            "sudo cargo check should be intercepted",
        )
        .unwrap();

    let result = classify_and_log(&harness, "env RUST_BACKTRACE=1 cargo test");
    harness
        .assert(
            result.is_compilation,
            "env-wrapped cargo test should be intercepted",
        )
        .unwrap();

    harness.logger.info("TEST PASS: test_hook_wrapped_commands");
    harness.mark_passed();
}

// ============================================================================
// Hook Input JSON Tests
// ============================================================================

#[test]
fn test_hook_input_fixture_format() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_input_fixture").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_input_fixture_format");

    // Test HookInputFixture generates valid JSON
    let input = HookInputFixture::cargo_build();
    let json = input.to_json();

    assert!(json.contains("\"tool_name\": \"Bash\""));
    assert!(json.contains("\"command\": \"cargo build\""));

    // Test custom command
    let input = HookInputFixture::custom("cargo test --release");
    let json = input.to_json();
    assert!(json.contains("\"command\": \"cargo test --release\""));

    harness
        .logger
        .info("TEST PASS: test_hook_input_fixture_format");
    harness.mark_passed();
}

// ============================================================================
// Environment Variable Tests
// ============================================================================

#[test]
fn test_hook_env_rch_disabled() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_env_disabled").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_env_rch_disabled");

    // When RCH_ENABLED=false, classification should still work
    // (the config check happens in the hook, not in classify_command)
    // This test verifies the classification logic is independent of config

    let result = classify_command("cargo build");
    assert!(
        result.is_compilation,
        "Classification should work regardless of RCH_ENABLED"
    );

    harness.logger.info("TEST PASS: test_hook_env_rch_disabled");
    harness.mark_passed();
}

// ============================================================================
// Edge Cases
// ============================================================================

#[test]
fn test_hook_empty_command() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_empty_command").unwrap();

    harness.logger.info("TEST START: test_hook_empty_command");

    let result = classify_command("");
    assert!(
        !result.is_compilation,
        "Empty command should not be intercepted"
    );
    assert!(
        result.reason.contains("empty"),
        "Reason should mention empty"
    );

    let result = classify_command("   ");
    assert!(
        !result.is_compilation,
        "Whitespace-only command should not be intercepted"
    );

    harness.logger.info("TEST PASS: test_hook_empty_command");
    harness.mark_passed();
}

#[test]
fn test_hook_subshell_capture() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_subshell_capture").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_subshell_capture");

    // Subshell capture should not be intercepted
    let result = classify_command("cargo build $(echo src/)");
    assert!(
        !result.is_compilation,
        "Subshell capture should not be intercepted"
    );
    assert!(
        result.reason.contains("subshell"),
        "Reason should mention subshell"
    );

    // Backtick subshell
    let result = classify_command("cargo build `echo flags`");
    assert!(
        !result.is_compilation,
        "Backtick subshell should not be intercepted"
    );

    harness.logger.info("TEST PASS: test_hook_subshell_capture");
    harness.mark_passed();
}

#[test]
fn test_hook_version_checks_not_intercepted() {
    let _guard = test_guard!();
    let harness = create_hook_harness("hook_version_checks").unwrap();

    harness
        .logger
        .info("TEST START: test_hook_version_checks_not_intercepted");

    // Version checks should not be intercepted
    let result = classify_command("cargo --version");
    assert!(
        !result.is_compilation,
        "cargo --version should not be intercepted"
    );

    let result = classify_command("rustc --version");
    assert!(
        !result.is_compilation,
        "rustc --version should not be intercepted"
    );

    let result = classify_command("gcc --version");
    assert!(
        !result.is_compilation,
        "gcc --version should not be intercepted"
    );

    let result = classify_command("bun --version");
    assert!(
        !result.is_compilation,
        "bun --version should not be intercepted"
    );

    harness
        .logger
        .info("TEST PASS: test_hook_version_checks_not_intercepted");
    harness.mark_passed();
}