pxh 0.9.9

pxh is a fast, cross-shell history mining tool with interactive fuzzy search, secret scanning, and bidirectional sync across machines. It indexes bash and zsh history in SQLite with rich metadata for powerful recall.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
use std::{fs, thread, time::Duration};

use pxh::test_utils::PxhTestHelper;
use rexpect::session::spawn_command;

type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

// Shell type enum for parameterized tests
#[derive(Clone, Copy)]
enum Shell {
    Bash,
    Zsh,
}

impl Shell {
    fn name(&self) -> &'static str {
        match self {
            Shell::Bash => "bash",
            Shell::Zsh => "zsh",
        }
    }

    fn rc_file(&self) -> &'static str {
        match self {
            Shell::Bash => ".bashrc",
            Shell::Zsh => ".zshrc",
        }
    }

    fn is_available(&self) -> bool {
        which::which(self.name()).is_ok()
    }
}

// Helper to count commands in a database using pxh
fn count_commands(helper: &PxhTestHelper) -> Result<usize> {
    let output = helper.command_with_args(&["show", "--suppress-headers"]).output()?;

    if !output.status.success() {
        return Ok(0);
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    Ok(stdout.lines().count())
}

// Helper to get commands from database using pxh export
fn get_commands(helper: &PxhTestHelper) -> Result<Vec<String>> {
    let output = helper.command_with_args(&["export"]).output()?;

    if !output.status.success() {
        return Ok(vec![]);
    }

    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;
    Ok(invocations.into_iter().map(|inv| inv.command.to_string()).collect())
}

#[test]
fn test_bash_interactive_shell() -> Result<()> {
    // Create test helper
    let helper = PxhTestHelper::new();
    let home_dir = helper.home_dir();
    let bashrc_path = home_dir.join(".bashrc");
    let pxh_db_path = helper.db_path();

    // Create empty .bashrc
    fs::write(&bashrc_path, "")?;

    // First, install pxh for bash
    let install_output = helper.command_with_args(&["install", "bash"]).output()?;

    eprintln!("Install output stdout: {}", String::from_utf8_lossy(&install_output.stdout));
    eprintln!("Install output stderr: {}", String::from_utf8_lossy(&install_output.stderr));

    assert!(
        install_output.status.success(),
        "Install failed: {}",
        String::from_utf8_lossy(&install_output.stderr)
    );

    // Verify bashrc was modified
    let bashrc_content = fs::read_to_string(&bashrc_path)?;
    eprintln!("Bashrc content after install:\n{}", bashrc_content);
    assert!(bashrc_content.contains("pxh shell-config bash"));

    // Now spawn an interactive bash session with proper environment
    let cmd = helper.shell_command("bash");
    eprintln!("Spawning bash with command: {:?}", cmd);
    let mut session = spawn_command(cmd, Some(30_000))?;

    // Wait for shell initialization and rc file loading
    thread::sleep(Duration::from_millis(1000));

    // Check if pxh is available
    session.send_line("which pxh")?;
    session.exp_regex(r"(/[^\r\n]+/pxh)")?;

    // Check environment variables
    session.send_line("echo PXH_DB_PATH=$PXH_DB_PATH")?;
    session.exp_string(&format!("PXH_DB_PATH={}", pxh_db_path.display()))?;

    // Give shell more time to initialize with preexec/precmd
    thread::sleep(Duration::from_millis(1000));

    // Run some test commands
    session.send_line("echo 'Hello from interactive bash'")?;
    session.exp_string("Hello from interactive bash")?;

    session.send_line("pwd")?;
    session.exp_regex(r"(/[^\r\n]+)")?;

    session.send_line("ls /tmp > /dev/null 2>&1")?;
    thread::sleep(Duration::from_millis(100));

    // Run a command that will fail
    session.send_line("false")?;
    thread::sleep(Duration::from_millis(100));

    // Exit the shell
    session.send_line("exit")?;
    session.exp_eof()?;

    // Give a moment for any final writes
    thread::sleep(Duration::from_millis(500));

    // Now verify that commands were recorded
    let command_count = count_commands(&helper)?;

    // Debug: Check if the database exists and has content
    if command_count == 0 {
        eprintln!("Debug: No commands found. Checking database path: {:?}", pxh_db_path);
        eprintln!("Debug: Database exists: {}", pxh_db_path.exists());

        // Try running pxh show directly to see what's happening
        let show_output = helper.command_with_args(&["show", "--suppress-headers"]).output()?;
        eprintln!("Debug: pxh show exit status: {}", show_output.status);
        eprintln!("Debug: pxh show stdout: {}", String::from_utf8_lossy(&show_output.stdout));
        eprintln!("Debug: pxh show stderr: {}", String::from_utf8_lossy(&show_output.stderr));
    }

    assert!(
        command_count >= 4,
        "Expected at least 4 commands (echo, pwd, ls, false), found {}",
        command_count
    );

    let commands = get_commands(&helper)?;
    assert!(
        commands.iter().any(|c| c.contains("echo 'Hello from interactive bash'")),
        "Should have recorded echo command"
    );
    assert!(commands.iter().any(|c| c == "pwd"), "Should have recorded pwd command");
    assert!(commands.iter().any(|c| c.contains("ls /tmp")), "Should have recorded ls command");
    assert!(commands.iter().any(|c| c == "false"), "Should have recorded false command");

    // Also verify using pxh show command
    let show_output = helper.command_with_args(&["show", "--limit", "10"]).output()?;

    assert!(show_output.status.success(), "Show command should succeed");
    let history = String::from_utf8_lossy(&show_output.stdout);
    assert!(history.contains("Hello from interactive bash"), "History should contain echo command");

    Ok(())
}

#[test]
fn test_zsh_interactive_shell() -> Result<()> {
    // Skip test if zsh is not available
    if which::which("zsh").is_err() {
        eprintln!("Skipping zsh integration test: zsh not found in PATH");
        return Ok(());
    }

    // Create test helper
    let helper = PxhTestHelper::new();
    let home_dir = helper.home_dir();
    let zshrc_path = home_dir.join(".zshrc");

    // Create empty .zshrc
    fs::write(&zshrc_path, "")?;

    // Install pxh for zsh
    let install_output = helper.command_with_args(&["install", "zsh"]).output()?;

    assert!(
        install_output.status.success(),
        "Install failed: {}",
        String::from_utf8_lossy(&install_output.stderr)
    );

    // Verify zshrc was modified
    let zshrc_content = fs::read_to_string(&zshrc_path)?;
    assert!(zshrc_content.contains("pxh shell-config zsh"));

    // Spawn an interactive zsh session with proper environment
    let cmd = helper.shell_command("zsh");
    let mut session = spawn_command(cmd, Some(30_000))?;

    // Wait for shell initialization and rc file loading
    thread::sleep(Duration::from_millis(1000));

    // Run test commands
    session.send_line("echo 'Hello from interactive zsh'")?;
    session.exp_string("Hello from interactive zsh")?;

    session.send_line("date +%Y-%m-%d")?;
    session.exp_regex(r"\d{4}-\d{2}-\d{2}")?;

    session.send_line("cd /tmp && pwd")?;
    session.exp_string("/tmp")?;

    // Exit the shell
    session.send_line("exit")?;
    session.exp_eof()?;

    // Verify commands were recorded
    let command_count = count_commands(&helper)?;
    assert!(command_count >= 3, "Expected at least 3 commands, found {}", command_count);

    let commands = get_commands(&helper)?;
    assert!(
        commands.iter().any(|c| c.contains("echo 'Hello from interactive zsh'")),
        "Should have recorded echo command"
    );
    assert!(
        commands.iter().any(|c| c.contains("date +%Y-%m-%d")),
        "Should have recorded date command"
    );

    Ok(())
}

#[test]
fn test_bash_command_with_exit_status() -> Result<()> {
    // This test verifies that exit statuses are properly recorded
    let helper = PxhTestHelper::new();
    let home_dir = helper.home_dir();
    let bashrc_path = home_dir.join(".bashrc");

    fs::write(&bashrc_path, "")?;

    // Install pxh
    let install_output = helper.command_with_args(&["install", "bash"]).output()?;

    assert!(install_output.status.success());

    // Spawn bash session with proper environment
    let cmd = helper.shell_command("bash");
    let mut session = spawn_command(cmd, Some(30_000))?;

    // Wait for shell initialization
    thread::sleep(Duration::from_millis(1000));

    // Run a successful command
    session.send_line("true")?;
    thread::sleep(Duration::from_millis(100));

    // Run a failing command
    session.send_line("false")?;
    thread::sleep(Duration::from_millis(100));

    // Run a command with specific exit code
    session.send_line("exit 42")?;
    session.exp_eof()?;

    // Check the database for exit statuses using pxh export
    let output = helper.command_with_args(&["export"]).output()?;
    assert!(output.status.success(), "Export should succeed");

    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;

    // Verify exit statuses
    assert!(
        invocations.iter().any(|inv| inv.command == "true" && inv.exit_status == Some(0)),
        "true command should have exit status 0"
    );
    assert!(
        invocations.iter().any(|inv| inv.command == "false" && inv.exit_status == Some(1)),
        "false command should have exit status 1"
    );

    Ok(())
}

#[test]
fn test_bash_working_directory_tracking() -> Result<()> {
    // Test that working directories are properly tracked
    let helper = PxhTestHelper::new();
    let home_dir = helper.home_dir();
    let bashrc_path = home_dir.join(".bashrc");

    fs::write(&bashrc_path, "")?;

    // Create test directories
    let test_dir1 = home_dir.join("test1");
    let test_dir2 = home_dir.join("test2");
    fs::create_dir(&test_dir1)?;
    fs::create_dir(&test_dir2)?;

    // Install pxh
    let install_output = helper.command_with_args(&["install", "bash"]).output()?;

    assert!(install_output.status.success());

    // Spawn bash session with proper environment
    let cmd = helper.shell_command("bash");
    let mut session = spawn_command(cmd, Some(30_000))?;

    // Wait for shell initialization
    thread::sleep(Duration::from_millis(1000));

    // Run commands in different directories
    // First cd to test1, then run a command
    session.send_line(&format!("cd {}", test_dir1.display()))?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("echo 'in test1'")?;
    session.exp_string("in test1")?;

    // Now cd to test2 and run another command
    session.send_line(&format!("cd {}", test_dir2.display()))?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("echo 'in test2'")?;
    session.exp_string("in test2")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    // Verify working directories were recorded using pxh export
    let output = helper.command_with_args(&["export"]).output()?;
    assert!(output.status.success(), "Export should succeed");

    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;

    assert!(
        invocations.iter().any(|inv| inv.command.to_string().contains("in test1")
            && inv
                .working_directory
                .as_ref()
                .map(|d| d.to_string().ends_with("test1"))
                .unwrap_or(false)),
        "Should record test1 directory"
    );
    assert!(
        invocations.iter().any(|inv| inv.command.to_string().contains("in test2")
            && inv
                .working_directory
                .as_ref()
                .map(|d| d.to_string().ends_with("test2"))
                .unwrap_or(false)),
        "Should record test2 directory"
    );

    Ok(())
}

#[test]
fn test_multiple_sessions() -> Result<()> {
    // Test that multiple concurrent sessions each get unique session IDs
    let helper = PxhTestHelper::new();
    let home_dir = helper.home_dir();
    let bashrc_path = home_dir.join(".bashrc");

    fs::write(&bashrc_path, "")?;

    // Install pxh
    let install_output = helper.command_with_args(&["install", "bash"]).output()?;

    assert!(install_output.status.success());

    // Spawn two bash sessions with proper environment
    let cmd1 = helper.shell_command("bash");
    let cmd2 = helper.shell_command("bash");

    let mut session1 = spawn_command(cmd1, Some(30_000))?;
    let mut session2 = spawn_command(cmd2, Some(30_000))?;

    // Wait for shell initialization
    thread::sleep(Duration::from_millis(1000));

    // Run commands in both sessions
    for (i, session) in [&mut session1, &mut session2].iter_mut().enumerate() {
        // Run a unique command in each session
        session.send_line(&format!("echo 'Hello from session {}'", i + 1))?;
        session.exp_string(&format!("Hello from session {}", i + 1))?;
    }

    // Exit both sessions
    session1.send_line("exit")?;
    session1.exp_eof()?;

    session2.send_line("exit")?;
    session2.exp_eof()?;

    // Verify that we have commands from two different sessions using pxh export
    let output = helper.command_with_args(&["export"]).output()?;
    assert!(output.status.success(), "Export should succeed");

    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;

    // Count unique session IDs
    let unique_sessions: std::collections::HashSet<_> =
        invocations.iter().map(|inv| inv.session_id).collect();

    assert_eq!(unique_sessions.len(), 2, "Should have exactly 2 different session IDs");

    // Verify each session has its command
    assert!(
        invocations.iter().any(|inv| inv.command.to_string().contains("Hello from session 1")),
        "Should have command from session 1"
    );
    assert!(
        invocations.iter().any(|inv| inv.command.to_string().contains("Hello from session 2")),
        "Should have command from session 2"
    );

    Ok(())
}

// ============================================================================
// SHELL PARITY TESTS - Ensure bash and zsh have equivalent coverage
// ============================================================================

/// Helper to set up a shell session and return the session handle
fn setup_shell_session(
    shell: Shell,
    helper: &PxhTestHelper,
) -> Result<rexpect::session::PtySession> {
    let home_dir = helper.home_dir();
    let rc_path = home_dir.join(shell.rc_file());

    // Create empty rc file
    fs::write(&rc_path, "")?;

    // Install pxh for the shell
    let install_output = helper.command_with_args(&["install", shell.name()]).output()?;
    assert!(
        install_output.status.success(),
        "Install failed for {}: {}",
        shell.name(),
        String::from_utf8_lossy(&install_output.stderr)
    );

    // Spawn shell session
    let cmd = helper.shell_command(shell.name());
    let session = spawn_command(cmd, Some(30_000))?;

    Ok(session)
}

// ----------------------------------------------------------------------------
// ZSH PARITY: Exit status tracking (matches test_bash_command_with_exit_status)
// ----------------------------------------------------------------------------

#[test]
fn test_zsh_command_with_exit_status() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Run a successful command
    session.send_line("true")?;
    thread::sleep(Duration::from_millis(100));

    // Run a failing command
    session.send_line("false")?;
    thread::sleep(Duration::from_millis(100));

    // Exit
    session.send_line("exit")?;
    session.exp_eof()?;

    // Check the database for exit statuses
    let output = helper.command_with_args(&["export"]).output()?;
    assert!(output.status.success(), "Export should succeed");

    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;

    assert!(
        invocations.iter().any(|inv| inv.command == "true" && inv.exit_status == Some(0)),
        "true command should have exit status 0"
    );
    assert!(
        invocations.iter().any(|inv| inv.command == "false" && inv.exit_status == Some(1)),
        "false command should have exit status 1"
    );

    Ok(())
}

// ----------------------------------------------------------------------------
// ZSH PARITY: Working directory tracking (matches test_bash_working_directory_tracking)
// ----------------------------------------------------------------------------

#[test]
fn test_zsh_working_directory_tracking() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let home_dir = helper.home_dir();

    // Create test directories
    let test_dir1 = home_dir.join("zsh_test1");
    let test_dir2 = home_dir.join("zsh_test2");
    fs::create_dir(&test_dir1)?;
    fs::create_dir(&test_dir2)?;

    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Run commands in different directories
    session.send_line(&format!("cd {}", test_dir1.display()))?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("echo 'in zsh_test1'")?;
    session.exp_string("in zsh_test1")?;

    session.send_line(&format!("cd {}", test_dir2.display()))?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("echo 'in zsh_test2'")?;
    session.exp_string("in zsh_test2")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    // Verify working directories were recorded
    let output = helper.command_with_args(&["export"]).output()?;
    assert!(output.status.success(), "Export should succeed");

    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;

    assert!(
        invocations.iter().any(|inv| inv.command.to_string().contains("in zsh_test1")
            && inv
                .working_directory
                .as_ref()
                .map(|d| d.to_string().ends_with("zsh_test1"))
                .unwrap_or(false)),
        "Should record zsh_test1 directory"
    );
    assert!(
        invocations.iter().any(|inv| inv.command.to_string().contains("in zsh_test2")
            && inv
                .working_directory
                .as_ref()
                .map(|d| d.to_string().ends_with("zsh_test2"))
                .unwrap_or(false)),
        "Should record zsh_test2 directory"
    );

    Ok(())
}

// ============================================================================
// PIPED COMMANDS - Test command pipelines
// ============================================================================

#[test]
fn test_bash_piped_commands() -> Result<()> {
    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Simple pipe
    session.send_line("echo 'hello world' | grep hello")?;
    session.exp_string("hello world")?;

    // Multi-stage pipeline
    session.send_line("echo -e 'b\\na\\nc' | sort | head -1")?;
    session.exp_string("a")?;

    // Pipeline with redirection
    session.send_line("echo 'test output' | cat > /dev/null")?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("echo 'hello world' | grep hello")),
        "Should record simple pipe command"
    );
    assert!(
        commands.iter().any(|c| c.contains("sort") && c.contains("head")),
        "Should record multi-stage pipeline"
    );

    Ok(())
}

#[test]
fn test_zsh_piped_commands() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Simple pipe
    session.send_line("echo 'hello world' | grep hello")?;
    session.exp_string("hello world")?;

    // Multi-stage pipeline
    session.send_line("echo -e 'b\\na\\nc' | sort | head -1")?;
    session.exp_string("a")?;

    // Pipeline with redirection
    session.send_line("echo 'test output' | cat > /dev/null")?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("echo 'hello world' | grep hello")),
        "Should record simple pipe command"
    );
    assert!(
        commands.iter().any(|c| c.contains("sort") && c.contains("head")),
        "Should record multi-stage pipeline"
    );

    Ok(())
}

// ============================================================================
// COMPOUND COMMANDS - Test &&, ||, and ; operators
// ============================================================================

#[test]
fn test_bash_compound_commands() -> Result<()> {
    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // AND operator
    session.send_line("true && echo 'and succeeded'")?;
    session.exp_string("and succeeded")?;

    // OR operator
    session.send_line("false || echo 'or fallback'")?;
    session.exp_string("or fallback")?;

    // Semicolon chaining
    session.send_line("echo 'first'; echo 'second'")?;
    session.exp_string("first")?;
    session.exp_string("second")?;

    // Mixed operators
    session.send_line("true && echo 'yes' || echo 'no'")?;
    session.exp_string("yes")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("&&") && c.contains("and succeeded")),
        "Should record AND compound command"
    );
    assert!(
        commands.iter().any(|c| c.contains("||") && c.contains("or fallback")),
        "Should record OR compound command"
    );
    assert!(
        commands.iter().any(|c| c.contains(";") && c.contains("first") && c.contains("second")),
        "Should record semicolon-chained command"
    );

    Ok(())
}

#[test]
fn test_zsh_compound_commands() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // AND operator
    session.send_line("true && echo 'and succeeded'")?;
    session.exp_string("and succeeded")?;

    // OR operator
    session.send_line("false || echo 'or fallback'")?;
    session.exp_string("or fallback")?;

    // Semicolon chaining
    session.send_line("echo 'first'; echo 'second'")?;
    session.exp_string("first")?;
    session.exp_string("second")?;

    // Mixed operators
    session.send_line("true && echo 'yes' || echo 'no'")?;
    session.exp_string("yes")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("&&") && c.contains("and succeeded")),
        "Should record AND compound command"
    );
    assert!(
        commands.iter().any(|c| c.contains("||") && c.contains("or fallback")),
        "Should record OR compound command"
    );
    assert!(
        commands.iter().any(|c| c.contains(";") && c.contains("first") && c.contains("second")),
        "Should record semicolon-chained command"
    );

    Ok(())
}

// ============================================================================
// MULTILINE COMMANDS - Test backslash continuation
// ============================================================================

#[test]
fn test_bash_multiline_commands() -> Result<()> {
    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Backslash continuation - send as separate lines
    session.send_line("echo 'line1' \\")?;
    thread::sleep(Duration::from_millis(50));
    session.send_line("'line2' \\")?;
    thread::sleep(Duration::from_millis(50));
    session.send_line("'line3'")?;
    session.exp_string("line1 line2 line3")?;

    // Simple heredoc (inline for easier testing)
    session.send_line("cat << 'ENDMARKER'\nheredoc content\nENDMARKER")?;
    session.exp_string("heredoc content")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    // The multiline command should be recorded - exact format may vary by shell
    // At minimum, the content should be captured
    assert!(
        commands.iter().any(|c| c.contains("line1") && c.contains("line2") && c.contains("line3")),
        "Should record multiline echo command. Commands: {:?}",
        commands
    );

    Ok(())
}

#[test]
fn test_zsh_multiline_commands() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Backslash continuation - send as separate lines
    session.send_line("echo 'line1' \\")?;
    thread::sleep(Duration::from_millis(50));
    session.send_line("'line2' \\")?;
    thread::sleep(Duration::from_millis(50));
    session.send_line("'line3'")?;
    session.exp_string("line1 line2 line3")?;

    // Simple heredoc (inline for easier testing)
    session.send_line("cat << 'ENDMARKER'\nheredoc content\nENDMARKER")?;
    session.exp_string("heredoc content")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    // The multiline command should be recorded - exact format may vary by shell
    assert!(
        commands.iter().any(|c| c.contains("line1") && c.contains("line2") && c.contains("line3")),
        "Should record multiline echo command. Commands: {:?}",
        commands
    );

    Ok(())
}

// ============================================================================
// BACKGROUND PROCESSES - Test & operator
// ============================================================================

#[test]
fn test_bash_background_commands() -> Result<()> {
    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Background command
    session.send_line("sleep 0.1 &")?;
    thread::sleep(Duration::from_millis(200));

    // Another command while background runs
    session.send_line("echo 'foreground'")?;
    session.exp_string("foreground")?;

    // Wait for background to complete
    session.send_line("wait")?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    // Background command should be recorded
    assert!(
        commands.iter().any(|c| c.contains("sleep") && c.contains("&")),
        "Should record background command. Commands: {:?}",
        commands
    );
    assert!(
        commands.iter().any(|c| c.contains("foreground")),
        "Should record foreground command while background runs"
    );

    Ok(())
}

#[test]
fn test_zsh_background_commands() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Background command
    session.send_line("sleep 0.1 &")?;
    thread::sleep(Duration::from_millis(200));

    // Another command while background runs
    session.send_line("echo 'foreground'")?;
    session.exp_string("foreground")?;

    // Wait for background to complete
    session.send_line("wait")?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    // Background command should be recorded
    assert!(
        commands.iter().any(|c| c.contains("sleep") && c.contains("&")),
        "Should record background command. Commands: {:?}",
        commands
    );
    assert!(
        commands.iter().any(|c| c.contains("foreground")),
        "Should record foreground command while background runs"
    );

    Ok(())
}

// ============================================================================
// SUBSHELLS - Test ( ) syntax
// Note: bash-preexec has known limitations with subshells
// ============================================================================

#[test]
fn test_bash_subshell_commands() -> Result<()> {
    // NOTE: bash-preexec has documented limitations with subshells.
    // Commands run inside ( ) are NOT captured - this is a known limitation.
    // However, command substitution $(...) within an outer command IS captured.
    // This test documents the current behavior.

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Parenthesized subshell - NOT captured by bash-preexec (known limitation)
    session.send_line("(cd /tmp && pwd)")?;
    session.exp_string("/tmp")?;

    // Command substitution - the outer command IS captured
    session.send_line("echo \"today is $(date +%Y)\"")?;
    session.exp_regex(r"today is \d{4}")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    // Parenthesized subshells (cd /tmp && pwd) are NOT captured - known bash-preexec limitation
    // But command substitution in echo is captured
    assert!(
        commands.iter().any(|c| c.contains("today is $(date")),
        "Should record command substitution. Commands: {:?}",
        commands
    );

    // Document the limitation: parenthesized subshells are not captured
    assert!(
        !commands.iter().any(|c| c.contains("(cd /tmp")),
        "KNOWN LIMITATION: Parenthesized subshells are not captured by bash-preexec"
    );

    Ok(())
}

#[test]
fn test_zsh_subshell_commands() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Subshell command
    session.send_line("(cd /tmp && pwd)")?;
    session.exp_string("/tmp")?;

    // Command substitution
    session.send_line("echo \"today is $(date +%Y)\"")?;
    session.exp_regex(r"today is \d{4}")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    // Zsh should capture subshell commands
    assert!(
        commands.iter().any(|c| c.contains("cd /tmp") || c.contains("(cd")),
        "Should record subshell command. Commands: {:?}",
        commands
    );

    Ok(())
}

// ============================================================================
// SPECIAL CHARACTERS - Test quoting and escaping
// ============================================================================

#[test]
fn test_bash_special_characters() -> Result<()> {
    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Single quotes
    session.send_line("echo 'single quoted $VAR'")?;
    session.exp_string("single quoted $VAR")?;

    // Double quotes with variable
    session.send_line("VAR=test; echo \"double quoted $VAR\"")?;
    session.exp_string("double quoted test")?;

    // Escaped characters
    session.send_line("echo \"quotes: \\\"nested\\\"\"")?;
    session.exp_string("quotes: \"nested\"")?;

    // Special shell characters
    session.send_line("echo 'asterisk * and question ?'")?;
    session.exp_string("asterisk * and question ?")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("single quoted")),
        "Should record single-quoted command"
    );
    assert!(
        commands.iter().any(|c| c.contains("double quoted")),
        "Should record double-quoted command"
    );

    Ok(())
}

#[test]
fn test_zsh_special_characters() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Single quotes
    session.send_line("echo 'single quoted $VAR'")?;
    session.exp_string("single quoted $VAR")?;

    // Double quotes with variable
    session.send_line("VAR=test; echo \"double quoted $VAR\"")?;
    session.exp_string("double quoted test")?;

    // Escaped characters
    session.send_line("echo \"quotes: \\\"nested\\\"\"")?;
    session.exp_string("quotes: \"nested\"")?;

    // Special shell characters
    session.send_line("echo 'asterisk * and question ?'")?;
    session.exp_string("asterisk * and question ?")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("single quoted")),
        "Should record single-quoted command"
    );
    assert!(
        commands.iter().any(|c| c.contains("double quoted")),
        "Should record double-quoted command"
    );

    Ok(())
}

// ============================================================================
// CONTROL STRUCTURES - Test loops and conditionals
// ============================================================================

#[test]
fn test_bash_control_structures() -> Result<()> {
    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // For loop (single line)
    session.send_line("for i in 1 2 3; do echo $i; done")?;
    session.exp_string("1")?;
    session.exp_string("2")?;
    session.exp_string("3")?;

    // If statement (single line)
    session.send_line("if true; then echo 'condition met'; fi")?;
    session.exp_string("condition met")?;

    // While loop (single line)
    session.send_line("x=0; while [ $x -lt 2 ]; do echo $x; x=$((x+1)); done")?;
    session.exp_string("0")?;
    session.exp_string("1")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("for") && c.contains("do") && c.contains("done")),
        "Should record for loop. Commands: {:?}",
        commands
    );
    assert!(
        commands.iter().any(|c| c.contains("if") && c.contains("then") && c.contains("fi")),
        "Should record if statement. Commands: {:?}",
        commands
    );

    Ok(())
}

#[test]
fn test_zsh_control_structures() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // For loop (single line)
    session.send_line("for i in 1 2 3; do echo $i; done")?;
    session.exp_string("1")?;
    session.exp_string("2")?;
    session.exp_string("3")?;

    // If statement (single line)
    session.send_line("if true; then echo 'condition met'; fi")?;
    session.exp_string("condition met")?;

    // While loop (single line)
    session.send_line("x=0; while [ $x -lt 2 ]; do echo $x; x=$((x+1)); done")?;
    session.exp_string("0")?;
    session.exp_string("1")?;

    session.send_line("exit")?;
    session.exp_eof()?;

    let commands = get_commands(&helper)?;

    assert!(
        commands.iter().any(|c| c.contains("for") && c.contains("do") && c.contains("done")),
        "Should record for loop. Commands: {:?}",
        commands
    );
    assert!(
        commands.iter().any(|c| c.contains("if") && c.contains("then") && c.contains("fi")),
        "Should record if statement. Commands: {:?}",
        commands
    );

    Ok(())
}

// ============================================================================
// TIMING AND DURATION - Verify command timing is recorded
// ============================================================================

#[test]
fn test_bash_command_timing() -> Result<()> {
    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Bash, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Run a command that takes measurable time
    session.send_line("sleep 0.5")?;
    thread::sleep(Duration::from_millis(600));

    // Run a quick command
    session.send_line("true")?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("exit")?;
    session.exp_eof()?;

    let output = helper.command_with_args(&["export"]).output()?;
    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;

    // Find the sleep command and verify it has timing
    let sleep_cmd = invocations.iter().find(|inv| inv.command.to_string().contains("sleep"));

    assert!(sleep_cmd.is_some(), "Should have recorded sleep command");

    // Verify start timestamp exists
    assert!(
        sleep_cmd.unwrap().start_unix_timestamp.is_some(),
        "Sleep command should have start timestamp"
    );

    Ok(())
}

#[test]
fn test_zsh_command_timing() -> Result<()> {
    if !Shell::Zsh.is_available() {
        eprintln!("Skipping zsh test: zsh not found in PATH");
        return Ok(());
    }

    let helper = PxhTestHelper::new();
    let mut session = setup_shell_session(Shell::Zsh, &helper)?;

    thread::sleep(Duration::from_millis(1000));

    // Run a command that takes measurable time
    session.send_line("sleep 0.5")?;
    thread::sleep(Duration::from_millis(600));

    // Run a quick command
    session.send_line("true")?;
    thread::sleep(Duration::from_millis(100));

    session.send_line("exit")?;
    session.exp_eof()?;

    let output = helper.command_with_args(&["export"]).output()?;
    let invocations: Vec<pxh::Invocation> = serde_json::from_slice(&output.stdout)?;

    // Find the sleep command and verify it has timing
    let sleep_cmd = invocations.iter().find(|inv| inv.command.to_string().contains("sleep"));

    assert!(sleep_cmd.is_some(), "Should have recorded sleep command");

    // Verify start timestamp exists
    assert!(
        sleep_cmd.unwrap().start_unix_timestamp.is_some(),
        "Sleep command should have start timestamp"
    );

    Ok(())
}