runex 0.1.13

Cross-shell abbreviation engine that expands short tokens into full commands
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
/// End-to-end CLI tests for runex commands.
///
/// These tests invoke the compiled binary as a subprocess and assert on
/// stdout/stderr/exit-code, using:
///   --config <tempfile>   to supply isolated config without touching ~/.config
///   --path-prepend <dir>  to inject fake command presence without altering PATH
use std::io::Write;
use std::path::Path;
use std::process::{Command, Stdio};
use tempfile::{NamedTempFile, TempDir};

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_runex")
}

/// Write a TOML config to a NamedTempFile and return it.
fn write_config(toml: &str) -> NamedTempFile {
    let mut f = NamedTempFile::new().unwrap();
    f.write_all(toml.as_bytes()).unwrap();
    f.flush().unwrap();
    f
}

/// Create a temporary directory with the given executable stubs (empty files).
fn fake_bin_dir(cmds: &[&str]) -> TempDir {
    let dir = tempfile::tempdir().unwrap();
    for cmd in cmds {
        let path = dir.path().join(cmd);
        std::fs::write(&path, b"").unwrap();
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let mut perms = std::fs::metadata(&path).unwrap().permissions();
            perms.set_mode(0o755);
            std::fs::set_permissions(&path, perms).unwrap();
        }
    }
    dir
}

/// Run `runex` with the given arguments, config override, and optional path_prepend.
/// Returns (stdout, stderr, exit_success).
fn run(
    args: &[&str],
    config: Option<&Path>,
    path_prepend: Option<&Path>,
) -> (String, String, bool) {
    let mut cmd = Command::new(bin());

    if let Some(p) = config {
        cmd.arg("--config").arg(p);
    }
    if let Some(p) = path_prepend {
        cmd.arg("--path-prepend").arg(p);
    }
    cmd.args(args);

    let out = cmd.output().unwrap();
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.success(),
    )
}

// ─── expand ───────────────────────────────────────────────────────────────────

#[test]
fn expand_known_token() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(&["expand", "--token", "gcm"], Some(cfg.path()), None);
    assert!(ok);
    assert_eq!(stdout, "git commit -m");
}

#[test]
fn expand_unknown_token_passthrough() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(&["expand", "--token", "xyz"], Some(cfg.path()), None);
    assert!(ok);
    assert_eq!(stdout, "xyz");
}

#[test]
fn expand_condition_skipped_when_command_absent() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"__runex_fake_lsd__\"\nwhen_command_exists = [\"__runex_fake_lsd__\"]\n",
    );
    let (stdout, _, ok) = run(&["expand", "--token", "ls"], Some(cfg.path()), None);
    assert!(ok);
    assert_eq!(stdout, "ls");
}

#[test]
fn expand_condition_passes_with_path_prepend() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"__runex_fake_lsd__\"\nwhen_command_exists = [\"__runex_fake_lsd__\"]\n",
    );
    let bins = fake_bin_dir(&["__runex_fake_lsd__"]);
    let (stdout, _, ok) =
        run(&["expand", "--token", "ls"], Some(cfg.path()), Some(bins.path()));
    assert!(ok);
    assert_eq!(stdout, "__runex_fake_lsd__");
}

// ─── expand --dry-run ─────────────────────────────────────────────────────────

#[test]
fn dry_run_shows_expanded_result() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) =
        run(&["expand", "--token", "gcm", "--dry-run"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("token: gcm"), "stdout: {stdout}");
    assert!(stdout.contains("git commit -m"), "stdout: {stdout}");
    assert!(stdout.contains("expanded"), "stdout: {stdout}");
}

#[test]
fn dry_run_shows_condition_failed() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"__runex_fake_lsd__\"\nwhen_command_exists = [\"__runex_fake_lsd__\"]\n",
    );
    let (stdout, _, ok) =
        run(&["expand", "--token", "ls", "--dry-run"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("__runex_fake_lsd__: NOT FOUND"), "stdout: {stdout}");
    assert!(stdout.contains("pass-through"), "stdout: {stdout}");
}

#[test]
fn dry_run_condition_passes_with_path_prepend() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"__runex_fake_lsd__\"\nwhen_command_exists = [\"__runex_fake_lsd__\"]\n",
    );
    let bins = fake_bin_dir(&["__runex_fake_lsd__"]);
    let (stdout, _, ok) = run(
        &["expand", "--token", "ls", "--dry-run"],
        Some(cfg.path()),
        Some(bins.path()),
    );
    assert!(ok);
    assert!(stdout.contains("found"), "stdout: {stdout}");
    assert!(stdout.contains("expanded  ->  __runex_fake_lsd__"), "stdout: {stdout}");
}

#[test]
fn dry_run_no_match() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) =
        run(&["expand", "--token", "xyz", "--dry-run"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("no rule matched"), "stdout: {stdout}");
    assert!(stdout.contains("pass-through"), "stdout: {stdout}");
}

// ─── list ────────────────────────────────────────────────────────────────────

#[test]
fn list_shows_all_abbrs() {
    let cfg = write_config(
        "version = 1\n\
         [[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n\
         [[abbr]]\nkey = \"gp\"\nexpand = \"git push\"\n",
    );
    let (stdout, _, ok) = run(&["list"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("gcm"), "stdout: {stdout}");
    assert!(stdout.contains("git commit -m"), "stdout: {stdout}");
    assert!(stdout.contains("gp"), "stdout: {stdout}");
    assert!(stdout.contains("git push"), "stdout: {stdout}");
}

#[test]
fn list_json_is_valid_json_array() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(&["list", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("list --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert!(parsed.is_array());
    let arr = parsed.as_array().unwrap();
    assert!(!arr.is_empty());
    assert_eq!(arr[0]["key"], "gcm");
    assert_eq!(arr[0]["expand"], "git commit -m");
}

// ─── which ───────────────────────────────────────────────────────────────────

#[test]
fn which_known_token_shows_expansion() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(&["which", "gcm"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("gcm"), "stdout: {stdout}");
    assert!(stdout.contains("git commit -m"), "stdout: {stdout}");
}

#[test]
fn which_unknown_token_says_no_rule() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(&["which", "zzz"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("no rule found"), "stdout: {stdout}");
}

#[test]
fn which_skipped_shows_missing_command() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"__runex_fake_lsd__\"\nwhen_command_exists = [\"__runex_fake_lsd__\"]\n",
    );
    let (stdout, _, ok) = run(&["which", "ls"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("skipped"), "stdout: {stdout}");
    assert!(stdout.contains("__runex_fake_lsd__"), "stdout: {stdout}");
}

#[test]
fn which_why_shows_rule_index() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(&["which", "gcm", "--why"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("rule #1"), "stdout: {stdout}");
}

#[test]
fn which_json_is_valid_json() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(&["which", "gcm", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("which --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert_eq!(v["result"], "expanded");
    assert_eq!(v["expansion"], "git commit -m");
}

#[test]
fn which_json_no_match() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(&["which", "zzz", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("which --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert_eq!(v["result"], "no_match");
}

/// JSON output must use 1-based `rule_index` to match the text output ("rule #1").
#[test]
fn which_json_rule_index_is_one_based() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(&["which", "gcm", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(
        v["rule_index"], 1,
        "rule_index must be 1-based (got {})",
        v["rule_index"]
    );
}

/// Skipped entries in JSON output must also use 1-based indices.
#[test]
fn which_json_skipped_indices_are_one_based() {
    let cfg = write_config(
        "version = 1\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"ls\"\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"lsd\"\n",
    );
    let (stdout, _, ok) = run(&["which", "ls", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(v["result"], "expanded");
    let skipped = v["skipped"].as_array().expect("skipped must be array");
    assert!(!skipped.is_empty(), "expected at least one skipped entry");
    assert_eq!(
        skipped[0][0], 1,
        "skipped rule index must be 1-based (got {})",
        skipped[0][0]
    );
}

#[test]
fn dry_run_json_rule_index_is_one_based() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(
        &["expand", "--token", "gcm", "--dry-run", "--json"],
        Some(cfg.path()),
        None,
    );
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert_eq!(v["result"], "expanded");
    assert_eq!(
        v["rule_index"], 1,
        "dry-run --json rule_index must be 1-based (got {})",
        v["rule_index"]
    );
}

#[test]
fn which_with_path_prepend_resolves_condition() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"__runex_fake_lsd__\"\nwhen_command_exists = [\"__runex_fake_lsd__\"]\n",
    );
    let bins = fake_bin_dir(&["__runex_fake_lsd__"]);
    let (stdout, _, ok) =
        run(&["which", "ls"], Some(cfg.path()), Some(bins.path()));
    assert!(ok);
    assert!(stdout.contains("->"), "stdout: {stdout}");
    assert!(!stdout.contains("skipped"), "stdout: {stdout}");
}

// ─── doctor ──────────────────────────────────────────────────────────────────

#[test]
fn doctor_passes_with_valid_config() {
    let cfg = write_config("version = 1\n");
    let (_, _, ok) = run(&["doctor"], Some(cfg.path()), None);
    assert!(ok, "doctor should exit 0 with valid config");
}

#[test]
fn doctor_fails_with_missing_config() {
    let (_, _, ok) = run(&["doctor", "--config", "/nonexistent/path/config.toml"], None, None);
    assert!(!ok, "doctor should exit non-zero when config file missing");
}

#[test]
fn doctor_json_is_valid_json_array() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(&["doctor", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("doctor --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert!(parsed.is_array());
}

#[test]
fn doctor_with_path_prepend_finds_command() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"__runex_fake_lsd__\"\nwhen_command_exists = [\"__runex_fake_lsd__\"]\n",
    );
    let bins = fake_bin_dir(&["__runex_fake_lsd__"]);
    let (stdout, _, ok) =
        run(&["doctor", "--json"], Some(cfg.path()), Some(bins.path()));
    assert!(ok, "doctor should exit 0 when required command is found");
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let checks = parsed.as_array().unwrap();
    let fake_cmd_check = checks
        .iter()
        .find(|c| c["name"].as_str() == Some("command:__runex_fake_lsd__"));
    assert!(fake_cmd_check.is_some(), "expected command:__runex_fake_lsd__ check in output");
    assert_eq!(
        fake_cmd_check.unwrap()["status"].as_str(),
        Some("ok"),
        "__runex_fake_lsd__ should be ok with path_prepend"
    );
}

// ─── version ─────────────────────────────────────────────────────────────────

#[test]
fn version_shows_version_string() {
    let (stdout, _, ok) = run(&["version"], None, None);
    assert!(ok);
    assert!(stdout.starts_with("runex "), "stdout: {stdout}");
}

#[test]
fn version_json_has_version_field() {
    let (stdout, _, ok) = run(&["version", "--json"], None, None);
    assert!(ok);
    let parsed: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("version --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert!(parsed["version"].is_string());
    let ver = parsed["version"].as_str().unwrap();
    assert!(!ver.is_empty());
}

// ─── duplicate-key fallthrough (bug regression) ──────────────────────────────

/// Rule 1 is a self-loop (skipped by expand); rule 2 is the real expansion.
#[test]
fn expand_duplicate_key_self_loop_then_real() {
    let cfg = write_config(
        "version = 1\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"ls\"\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"lsd2\"\n",
    );
    let (stdout, _, ok) = run(&["expand", "--token", "ls"], Some(cfg.path()), None);
    assert!(ok);
    assert_eq!(stdout.trim(), "lsd2");
}

#[test]
fn which_duplicate_key_shows_skipped_and_final() {
    let cfg = write_config(
        "version = 1\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"ls\"\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"lsd2\"\n",
    );
    let (stdout, _, ok) = run(&["which", "ls", "--why"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("rule #1 skipped"), "stdout: {stdout}");
    assert!(stdout.contains("lsd2"), "stdout: {stdout}");
}

#[test]
fn dry_run_duplicate_key_shows_skip_trace() {
    let cfg = write_config(
        "version = 1\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"ls\"\n\
         [[abbr]]\nkey = \"ls\"\nexpand = \"lsd2\"\n",
    );
    let (stdout, _, ok) =
        run(&["expand", "--token", "ls", "--dry-run"], Some(cfg.path()), None);
    assert!(ok);
    assert!(stdout.contains("rule #1 skipped"), "stdout: {stdout}");
    assert!(stdout.contains("lsd2"), "stdout: {stdout}");
}

// ─── export --config validation ───────────────────────────────────────────────

#[test]
fn export_explicit_invalid_config_fails() {
    let (_, _, ok) = run(
        &["export", "bash", "--config", "/nonexistent/config.toml"],
        None,
        None,
    );
    assert!(!ok, "export with explicit invalid --config should fail");
}

/// `--config` can appear before the subcommand; that variant must also fail when the path is invalid.
#[test]
fn export_explicit_missing_config_also_fails() {
    let (stdout, _, ok) =
        run(&["--config", "/nonexistent/config.toml", "export", "bash"], None, None);
    assert!(!ok, "stdout: {stdout}");
}

#[test]
fn export_bash_bootstrap_calls_runex_hook() {
    // With the hook-based design, templates no longer embed the abbreviation
    // list as inline `case` arms. Instead the bootstrap must delegate to
    // `runex hook` at keypress time.
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n",
    );
    let (stdout, _, ok) = run(&["export", "bash"], Some(cfg.path()), None);
    assert!(ok);
    assert!(
        stdout.contains("hook --shell bash"),
        "bash bootstrap should invoke `runex hook --shell bash`; got:\n{stdout}"
    );
}

// ─── config error policy ─────────────────────────────────────────────────────

#[test]
fn explicit_config_not_found_exits_nonzero_and_mentions_path() {
    let (_, stderr, ok) = run(&["list"], Some(std::path::Path::new("/nonexistent/config.toml")), None);
    assert!(!ok, "list with missing --config must exit non-zero");
    assert!(stderr.contains("nonexistent"), "stderr must mention the path: {stderr}");
}

#[test]
fn explicit_config_parse_error_exits_nonzero() {
    let cfg = write_config("this is not valid toml [[[");
    let (_, _, ok) = run(&["list"], Some(cfg.path()), None);
    assert!(!ok, "list with broken config must exit non-zero");
}

/// `doctor` reports `config_file` as Error when the file doesn't exist and exits non-zero.
#[test]
fn doctor_with_missing_explicit_config_exits_nonzero() {
    let (_, _, ok) = run(&["doctor"], Some(std::path::Path::new("/nonexistent/config.toml")), None);
    assert!(!ok, "doctor must exit non-zero when config file is missing");
}

#[test]
fn doctor_shows_parse_error_in_output() {
    let cfg = write_config("[keybind]\ntrigger = \"space\"\n");
    let (stdout, _, ok) = run(&["doctor"], Some(cfg.path()), None);
    assert!(!ok, "doctor must exit non-zero with broken config");
    assert!(stdout.contains("config_parse"), "stdout must contain config_parse check: {stdout}");
    assert!(stdout.contains("failed to load config"), "stdout must contain error message: {stdout}");
}

#[test]
fn doctor_verbose_shows_multiline_parse_error() {
    let cfg = write_config("[keybind]\ntrigger = \"space\"\n");
    let (stdout_normal, _, _) = run(&["doctor"], Some(cfg.path()), None);
    let (stdout_verbose, _, _) = run(&["doctor", "--verbose"], Some(cfg.path()), None);
    assert!(
        stdout_verbose.lines().count() > stdout_normal.lines().count(),
        "doctor --verbose must produce more output lines than plain doctor\nnormal: {stdout_normal}\nverbose: {stdout_verbose}"
    );
}

#[test]
fn doctor_parse_error_unsupported_version() {
    let cfg = write_config("version = 99\n");
    let (stdout, _, ok) = run(&["doctor"], Some(cfg.path()), None);
    assert!(!ok, "doctor must exit non-zero for unsupported version");
    assert!(stdout.contains("config_parse"), "stdout must contain config_parse check: {stdout}");
    assert!(stdout.contains("failed to load config"), "stdout must mention the error: {stdout}");
}

#[test]
fn doctor_parse_error_key_too_long() {
    let long_key = "a".repeat(1025);
    let cfg = write_config(&format!("version = 1\n[[abbr]]\nkey = \"{long_key}\"\nexpand = \"x\"\n"));
    let (stdout, _, ok) = run(&["doctor"], Some(cfg.path()), None);
    assert!(!ok, "doctor must exit non-zero for key too long");
    assert!(stdout.contains("config_parse"), "stdout must contain config_parse check: {stdout}");
    assert!(stdout.contains("failed to load config"), "stdout must mention the error: {stdout}");
}

#[test]
fn expand_with_missing_explicit_config_exits_nonzero() {
    let (_, _, ok) = run(&["expand", "--token", "ls"], Some(std::path::Path::new("/nonexistent/config.toml")), None);
    assert!(!ok, "expand with missing config must exit non-zero");
}

#[test]
fn which_with_missing_explicit_config_exits_nonzero() {
    let (_, _, ok) = run(&["which", "ls"], Some(std::path::Path::new("/nonexistent/config.toml")), None);
    assert!(!ok, "which with missing config must exit non-zero");
}

// ─── JSON schema regression ───────────────────────────────────────────────────

#[test]
fn json_version_has_required_fields() {
    let (stdout, _, ok) = run(&["version", "--json"], None, None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("version --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert!(v.get("version").and_then(|v| v.as_str()).is_some(), "must have string 'version' field");
}

#[test]
fn json_list_is_array_with_key_and_expand() {
    let cfg = write_config("version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n");
    let (stdout, _, ok) = run(&["list", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("list --json is not valid JSON: {e}"));
    let arr = v.as_array().expect("list --json must be an array");
    assert!(!arr.is_empty());
    assert!(arr[0].get("key").is_some(), "each entry must have 'key'");
    assert!(arr[0].get("expand").is_some(), "each entry must have 'expand'");
}

#[test]
fn json_doctor_is_array_with_name_and_status() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(&["doctor", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("doctor --json is not valid JSON: {e}"));
    let arr = v.as_array().expect("doctor --json must be an array");
    assert!(!arr.is_empty());
    assert!(arr[0].get("name").is_some(), "each check must have 'name'");
    assert!(arr[0].get("status").is_some(), "each check must have 'status'");
}

// ─── init --config ────────────────────────────────────────────────────────────

/// Build a Command for `runex init` with HOME/USERPROFILE/PSModulePath/SHELL all
/// redirected into `home_dir` so that shell detection and rc-file resolution
/// stay entirely inside the temp directory on every platform.
///
/// `PSModulePath` is removed to suppress pwsh detection on Windows; `SHELL` is
/// forced to `/bin/bash` so that `rc_file_for()` resolves to `$HOME/.bashrc`
/// inside the temp directory.
fn init_cmd_in_dir(home_dir: &std::path::Path) -> Command {
    let mut cmd = Command::new(bin());
    cmd.env("HOME", home_dir)
        .env("USERPROFILE", home_dir)
        .env("XDG_CONFIG_HOME", home_dir.join(".config"))
        .env_remove("PSModulePath")
        .env("SHELL", "/bin/bash");
    cmd
}

#[test]
fn init_config_creates_file_at_given_path() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("custom_config.toml");
    assert!(!config_path.exists());

    let out = init_cmd_in_dir(dir.path())
        .args([
            "--config",
            config_path.to_str().unwrap(),
            "init",
            "--yes",
        ])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "stderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(config_path.exists(), "config file must be created at the given path");
}

/// init must succeed even when the shell rc file's parent directory does not yet exist.
#[test]
fn init_creates_rc_parent_dir_if_missing() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let out = init_cmd_in_dir(dir.path())
        .args([
            "--config",
            config_path.to_str().unwrap(),
            "init",
            "--yes",
        ])
        .output()
        .unwrap();
    assert!(
        out.status.success(),
        "init must exit 0 even when rc parent dir is missing\nstderr: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn init_config_already_exists_does_not_overwrite() {
    let cfg = write_config("version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n");
    let dir = tempfile::tempdir().unwrap();

    let out = init_cmd_in_dir(dir.path())
        .args([
            "--config",
            cfg.path().to_str().unwrap(),
            "init",
            "--yes",
        ])
        .output()
        .unwrap();
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("already exists"), "stdout: {stdout}");
    let content = std::fs::read_to_string(cfg.path()).unwrap();
    assert!(content.contains("gcm"), "config must not be overwritten");
}

// ─── --path-prepend silent ignore ────────────────────────────────────────────

#[test]
fn list_ignores_path_prepend() {
    let cfg = write_config(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"lsd\"\nwhen_command_exists = [\"lsd\"]\n",
    );
    let bins = fake_bin_dir(&["lsd"]);
    let (stdout_with, _, ok_with) = run(&["list"], Some(cfg.path()), Some(bins.path()));
    let (stdout_without, _, ok_without) = run(&["list"], Some(cfg.path()), None);
    assert!(ok_with && ok_without);
    assert_eq!(
        stdout_with, stdout_without,
        "--path-prepend must not affect list output"
    );
}

// ─── expand --json ───────────────────────────────────────────────────────────

#[test]
fn expand_json_expanded() {
    let cfg = write_config("version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n");
    let (stdout, _, ok) = run(&["expand", "--token", "gcm", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("expand --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert_eq!(v["result"], "expanded");
    assert_eq!(v["expansion"], "git commit -m");
}

#[test]
fn expand_json_pass_through() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(&["expand", "--token", "xyz", "--json"], Some(cfg.path()), None);
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("expand --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert_eq!(v["result"], "pass_through");
}

#[test]
fn dry_run_json_expanded() {
    let cfg = write_config("version = 1\n[[abbr]]\nkey = \"gcm\"\nexpand = \"git commit -m\"\n");
    let (stdout, _, ok) = run(
        &["expand", "--token", "gcm", "--dry-run", "--json"],
        Some(cfg.path()),
        None,
    );
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("expand --dry-run --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert_eq!(v["result"], "expanded");
}

#[test]
fn dry_run_json_no_match() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(
        &["expand", "--token", "xyz", "--dry-run", "--json"],
        Some(cfg.path()),
        None,
    );
    assert!(ok);
    let v: serde_json::Value = serde_json::from_str(&stdout)
        .unwrap_or_else(|e| panic!("expand --dry-run --json is not valid JSON: {e}\nstdout: {stdout}"));
    assert_eq!(v["result"], "no_match");
}

// ─── doctor --no-shell-aliases ────────────────────────────────────────────────

/// `--no-shell-aliases` must not spawn pwsh/bash, so the test completes quickly
/// and no `shell:pwsh:*` or `shell:bash:*` checks appear in JSON output.
#[test]
fn doctor_no_shell_aliases_skips_external_shells() {
    let cfg = write_config("version = 1\n");
    let (stdout, _, ok) = run(
        &["doctor", "--no-shell-aliases", "--json"],
        Some(cfg.path()),
        None,
    );
    assert!(ok, "stdout: {stdout}");
    let parsed: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    let checks = parsed.as_array().unwrap();
    let shell_checks: Vec<_> = checks
        .iter()
        .filter(|c| {
            c["name"]
                .as_str()
                .map(|n| n.starts_with("shell:"))
                .unwrap_or(false)
        })
        .collect();
    assert!(
        shell_checks.is_empty(),
        "expected no shell alias checks, got: {shell_checks:?}"
    );
}

// --- Terminal escape sequence injection: expansion values must not pass ANSI escapes ---

/// TOML spec forbids raw control characters (U+0000–U+001F, U+007F) in strings.
/// A config containing a raw ESC byte (`\x1b`) in an expansion value must be
/// rejected by the TOML parser, preventing terminal escape injection via `list`.
#[test]
fn list_rejects_config_with_ansi_escape_in_expansion() {
    let mut toml = String::from("version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"");
    toml.push('\x1b'); // literal ESC byte — invalid in TOML string
    toml.push_str("[2Jmalicious\"\n");
    let cfg = write_config(&toml);
    let (_, _, ok) = run(&["list"], Some(cfg.path()), None);
    assert!(
        !ok,
        "list must reject a config with a raw ESC byte in expansion (TOML spec violation)"
    );
}

#[test]
fn which_rejects_config_with_ansi_escape_in_expansion() {
    let mut toml = String::from("version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"");
    toml.push('\x1b');
    toml.push_str("[2Jmalicious\"\n");
    let cfg = write_config(&toml);
    let (_, _, ok) = run(&["which", "ls"], Some(cfg.path()), None);
    assert!(
        !ok,
        "which must reject a config with a raw ESC byte in expansion (TOML spec violation)"
    );
}

// --- doctor/expand: when_command_exists with path-like values ---

/// `when_command_exists` values must be bare command names, not filesystem paths.
/// A value containing a path separator is rejected at config parse time, preventing
/// filesystem probing via `dir.join("../target_file")`.
#[test]
fn expand_when_command_exists_with_path_separator_not_satisfied() {
    let traversal_cmd = "../target_file";
    let toml = format!(
        "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"lsd\"\nwhen_command_exists = [\"{traversal_cmd}\"]\n"
    );
    let cfg = write_config(&toml);
    let (_, stderr, ok) = run(&["expand", "--token=ls"], Some(cfg.path()), None);
    assert!(
        !ok,
        "expand must fail when when_command_exists entry contains a path separator (config rejected at parse)"
    );
    assert!(
        stderr.contains("path separator") || stderr.contains("failed to load"),
        "stderr must mention path separator rejection: {stderr:?}"
    );
}

// --- when_command_exists: Windows drive-letter colon must be rejected ─────────

/// On Windows, `dir.join("C:foo")` resolves as an absolute path, bypassing the
/// intended `--path-prepend` directory restriction.  A `when_command_exists` entry
/// containing `:` is rejected at config parse time.
#[test]
#[cfg(windows)]
fn expand_when_command_exists_with_colon_not_satisfied() {
    let toml = "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"lsd\"\nwhen_command_exists = [\"C:lsd\"]\n";
    let cfg = write_config(toml);
    let bins = fake_bin_dir(&["lsd"]);
    let (_, stderr, ok) = run(&["expand", "--token=ls"], Some(cfg.path()), Some(bins.path()));
    assert!(
        !ok,
        "expand must fail when when_command_exists entry contains ':' (config rejected at parse)"
    );
    assert!(
        stderr.contains("path separator") || stderr.contains("failed to load"),
        "stderr must mention rejection: {stderr:?}"
    );
}

// --- doctor: when_command_exists with absolute path must not probe filesystem ---

/// `when_command_exists` values containing path separators are rejected at config parse time,
/// so a path like `"/etc/passwd"` can never be probed via doctor output. The config must be
/// rejected, never confirming file existence via "found" in the output.
#[test]
fn doctor_when_command_exists_absolute_path_is_treated_as_not_found() {
    #[cfg(unix)]
    {
        let cfg = write_config(
            "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"lsd\"\nwhen_command_exists = [\"/etc/passwd\"]\n",
        );
        let (stdout, _stderr, _ok) = run(&["doctor", "--json"], Some(cfg.path()), None);
        let checks: serde_json::Value = serde_json::from_str(&stdout).unwrap_or_default();
        let empty = vec![];
        let check_arr = checks.as_array().unwrap_or(&empty);
        for check in check_arr {
            let detail = check["detail"].as_str().unwrap_or("");
            assert!(
                !detail.contains("/etc/passwd: found"),
                "doctor must not report absolute path /etc/passwd as found: {detail}"
            );
            let name = check["name"].as_str().unwrap_or("");
            assert!(
                !name.contains("/etc/passwd"),
                "doctor check name must not contain raw path /etc/passwd: {name}"
            );
        }
    }
}

// ─── init: rc file symlink safety ────────────────────────────────────────────

/// init must not follow a symlink at the rc file path (O_NOFOLLOW protection).
/// If the rc path is a symlink, init must refuse to append to it.
#[test]
#[cfg(unix)]
fn init_does_not_follow_symlink_at_rc_file() {
    use std::os::unix::fs::symlink;
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");
    let target = dir.path().join("sensitive_target.txt");
    std::fs::write(&target, b"original content").unwrap();
    let bashrc = dir.path().join(".bashrc");
    symlink(&target, &bashrc).unwrap();

    let out = init_cmd_in_dir(dir.path())
        .args(["--config", config_path.to_str().unwrap(), "init", "--yes"])
        .output()
        .unwrap();

    let content = std::fs::read_to_string(&target).unwrap();
    assert_eq!(
        content, "original content",
        "init must not follow symlink at rc file path and write to the symlink target"
    );
    let _ = out;
}

// ─── export --bin validation ──────────────────────────────────────────────────

/// export with an empty --bin must exit non-zero; an empty bin name would
/// produce a broken shell script (e.g. `eval "$('' export bash)"`).
#[test]
fn export_with_empty_bin_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let (_, stderr, ok) = run(&["export", "bash", "--bin="], Some(cfg.path()), None);
    assert!(!ok, "export --bin='' must exit non-zero");
    assert!(
        stderr.contains("bin") || stderr.contains("empty") || stderr.contains("invalid"),
        "stderr must mention the invalid bin: {stderr}"
    );
}

/// export with a whitespace-only --bin must also exit non-zero.
#[test]
fn export_with_whitespace_only_bin_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let (_, stderr, ok) = run(&["export", "bash", "--bin=   "], Some(cfg.path()), None);
    assert!(!ok, "export --bin='   ' must exit non-zero");
    assert!(
        stderr.contains("bin") || stderr.contains("empty") || stderr.contains("invalid"),
        "stderr must mention the invalid bin: {stderr}"
    );
}

/// export with a --bin containing control characters must exit non-zero.
/// Silent dropping would produce a silently different binary name.
/// `\x07` (BEL) and `\x7f` (DEL) must both be rejected.
#[test]
fn export_with_control_char_in_bin_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let (_, stderr, ok) = run(&["export", "bash", "--bin=run\x07ex"], Some(cfg.path()), None);
    assert!(!ok, "export --bin with control char must exit non-zero");
    assert!(
        stderr.contains("bin") || stderr.contains("control") || stderr.contains("invalid"),
        "stderr must mention the invalid bin: {stderr}"
    );
}

/// export with --bin containing a Unicode right-to-left override (U+202E) must exit non-zero.
/// Such characters can deceive users about what binary name is embedded in the script.
#[test]
fn export_with_rlo_in_bin_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let bin_with_rlo = format!("run\u{202e}ex");
    let (_, stderr, ok) = run(&["export", "bash", &format!("--bin={bin_with_rlo}")], Some(cfg.path()), None);
    assert!(!ok, "export --bin with RLO (U+202E) must exit non-zero");
    assert!(
        stderr.contains("bin") || stderr.contains("invalid") || stderr.contains("ASCII"),
        "stderr must mention the invalid bin: {stderr}"
    );
}

/// export with --bin containing a zero-width joiner (U+200D) must exit non-zero.
#[test]
fn export_with_zero_width_joiner_in_bin_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let bin_with_zwj = format!("run\u{200d}ex");
    let (_, stderr, ok) = run(&["export", "bash", &format!("--bin={bin_with_zwj}")], Some(cfg.path()), None);
    assert!(!ok, "export --bin with ZWJ (U+200D) must exit non-zero");
    assert!(
        stderr.contains("bin") || stderr.contains("invalid") || stderr.contains("ASCII"),
        "stderr must mention the invalid bin: {stderr}"
    );
}

/// export with a --bin containing DEL (\x7f) must exit non-zero.
#[test]
fn export_with_del_in_bin_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let (_, stderr, ok) = run(&["export", "bash", "--bin=run\x7fex"], Some(cfg.path()), None);
    assert!(!ok, "export --bin with DEL (\\x7f) must exit non-zero");
    assert!(
        stderr.contains("bin") || stderr.contains("control") || stderr.contains("invalid"),
        "stderr must mention the invalid bin: {stderr}"
    );
}

// --- list: terminal injection via Unicode-escaped control chars in config -----

/// `runex list` must not emit raw ANSI escape sequences in human output.
/// parse_config now rejects ASCII control characters (including those injected
/// via TOML \uXXXX escapes), so configs containing them must fail to load.
/// This is the primary defense; sanitize_for_display is defense-in-depth.
#[test]
fn list_rejects_config_with_control_char_in_expansion() {
    let toml = "version = 1\n[[abbr]]\nkey = \"ls\"\nexpand = \"\\u001B[2Jmalicious\"\n";
    let cfg = write_config(toml);
    let (_, _, ok) = run(&["list"], Some(cfg.path()), None);
    assert!(
        !ok,
        "list must reject a config with ESC in expansion (parse_config control char check)"
    );
}

/// A key containing BEL (`\u{0007}`) via TOML Unicode escape must be rejected by `parse_config`.
#[test]
fn list_rejects_config_with_control_char_in_key() {
    let toml = "version = 1\n[[abbr]]\nkey = \"k\\u0007ey\"\nexpand = \"git commit -m\"\n";
    let cfg = write_config(toml);
    let (_, _, ok) = run(&["list"], Some(cfg.path()), None);
    assert!(
        !ok,
        "list must reject a config with BEL in key (parse_config control char check)"
    );
}

/// export with an extremely long --bin must exit non-zero to prevent DoS via huge rc-file writes.
#[test]
fn export_with_oversized_bin_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let huge_bin = "a".repeat(5000);
    let (_, stderr, ok) = run(&["export", "bash", &format!("--bin={huge_bin}")], Some(cfg.path()), None);
    assert!(!ok, "export --bin with 5000 chars must exit non-zero");
    assert!(
        stderr.contains("bin") || stderr.contains("long") || stderr.contains("invalid"),
        "stderr must mention the invalid bin: {stderr}"
    );
}

// ─── export --shell: terminal injection in error messages ─────────────────────

/// export with an unknown shell containing an ANSI escape sequence must not
/// echo the raw ESC byte into stderr (terminal injection via error message).
/// `ShellParseError` embeds the user-supplied shell name in its Display output;
/// that output must be sanitized before reaching the terminal.
#[test]
fn export_unknown_shell_with_control_char_in_name_does_not_inject_into_stderr() {
    let cfg = write_config("version = 1\n");
    let evil_shell = "bash\x1b[2Jevil";
    let (_, stderr, ok) = run(
        &["export", evil_shell, "--bin=runex"],
        Some(cfg.path()),
        None,
    );
    assert!(!ok, "export with unknown shell must exit non-zero");
    assert!(
        !stderr.contains('\x1b'),
        "stderr must not contain raw ESC from shell name (terminal injection risk): {stderr:?}"
    );
}

/// export with an unknown shell containing a BEL byte (\x07) must not
/// echo the raw BEL byte into stderr.
#[test]
fn export_unknown_shell_with_bel_in_name_does_not_inject_into_stderr() {
    let cfg = write_config("version = 1\n");
    let evil_shell = "bash\x07evil";
    let (_, stderr, ok) = run(
        &["export", evil_shell, "--bin=runex"],
        Some(cfg.path()),
        None,
    );
    assert!(!ok, "export with unknown shell must exit non-zero");
    assert!(
        !stderr.contains('\x07'),
        "stderr must not contain raw BEL from shell name (terminal injection risk): {stderr:?}"
    );
}

/// export with an unknown shell containing U+202E (RIGHT-TO-LEFT OVERRIDE) must not
/// echo the raw RLO into stderr. RLO reverses the visual display order of text, so
/// "bash\u{202E}lve" would appear as "bash evil" in some terminals even though the
/// byte content is different.
#[test]
fn export_unknown_shell_with_rlo_in_name_does_not_inject_into_stderr() {
    let cfg = write_config("version = 1\n");
    let evil_shell = "bash\u{202E}lve";
    let (_, stderr, ok) = run(
        &["export", evil_shell, "--bin=runex"],
        Some(cfg.path()),
        None,
    );
    assert!(!ok, "export with unknown shell must exit non-zero");
    assert!(
        !stderr.contains('\u{202E}'),
        "stderr must not contain raw RLO U+202E from shell name: {stderr:?}"
    );
}

/// export with an unknown shell containing U+FEFF (BOM / zero-width no-break space)
/// must not echo the raw BOM into stderr.
#[test]
fn export_unknown_shell_with_bom_in_name_does_not_inject_into_stderr() {
    let cfg = write_config("version = 1\n");
    let evil_shell = "bash\u{FEFF}evil";
    let (_, stderr, ok) = run(
        &["export", evil_shell, "--bin=runex"],
        Some(cfg.path()),
        None,
    );
    assert!(!ok, "export with unknown shell must exit non-zero");
    assert!(
        !stderr.contains('\u{FEFF}'),
        "stderr must not contain raw BOM U+FEFF from shell name: {stderr:?}"
    );
}

/// export with an unknown shell containing U+200B (ZERO-WIDTH SPACE) must not
/// echo the raw ZWSP into stderr.
#[test]
fn export_unknown_shell_with_zwsp_in_name_does_not_inject_into_stderr() {
    let cfg = write_config("version = 1\n");
    let evil_shell = "ba\u{200B}sh";
    let (_, stderr, ok) = run(
        &["export", evil_shell, "--bin=runex"],
        Some(cfg.path()),
        None,
    );
    assert!(!ok, "export with unknown shell must exit non-zero");
    assert!(
        !stderr.contains('\u{200B}'),
        "stderr must not contain raw ZWSP U+200B from shell name: {stderr:?}"
    );
}

// ─── expand / which: --token length limit ────────────────────────────────────
//
// The shell integration passes the token from the command-line buffer to
// `runex expand --token=<token>`.  Without a length guard, a user pasting a
// huge buffer could cause runex to allocate and process an arbitrarily large
// string.  Any token longer than MAX_KEY_BYTES (1024) can never match an abbr
// rule and must be rejected with a non-zero exit code so the shell integration
// falls back to a plain space insertion.

/// expand --token exceeding the maximum key length must exit non-zero.
#[test]
fn expand_with_oversized_token_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let huge_token = "k".repeat(1025);
    let (_, stderr, ok) = run(
        &["expand", &format!("--token={huge_token}")],
        Some(cfg.path()),
        None,
    );
    assert!(
        !ok,
        "expand --token longer than 1024 bytes must exit non-zero"
    );
    assert!(
        stderr.contains("token") || stderr.contains("long") || stderr.contains("invalid"),
        "stderr must mention the invalid token: {stderr}"
    );
}

/// which <token> exceeding the maximum key length must exit non-zero.
#[test]
fn which_with_oversized_token_exits_nonzero() {
    let cfg = write_config("version = 1\n");
    let huge_token = "k".repeat(1025);
    let (_, stderr, ok) = run(
        &["which", &huge_token],
        Some(cfg.path()),
        None,
    );
    assert!(
        !ok,
        "which <token> longer than 1024 bytes must exit non-zero"
    );
    assert!(
        stderr.contains("token") || stderr.contains("long") || stderr.contains("invalid"),
        "stderr must mention the invalid token: {stderr}"
    );
}

// ─── init: prompt_confirm stdin DoS ──────────────────────────────────────────
//
// `prompt_confirm` reads a line from stdin to ask the user y/N. Without a
// maximum read size, piping a huge amount of data (e.g. 10 MB of 'a' with no
// newline) causes read_line to buffer it all into a String, consuming memory
// proportional to the input size.
//
// The fix must truncate or discard input beyond MAX_CONFIRM_BYTES, so the
// process stays within expected memory bounds and terminates promptly.

/// `init` must exit promptly even when stdin contains 10 MB of data without a newline.
/// Without a read limit, read_line() buffers all of stdin before returning.
#[test]
fn init_prompt_confirm_handles_huge_stdin_without_oom() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let mut child = init_cmd_in_dir(dir.path())
        .args(["--config", config_path.to_str().unwrap(), "init"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    {
        let stdin = child.stdin.take().unwrap();
        let mut writer = std::io::BufWriter::new(stdin);
        let chunk = vec![b'y'; 65_536];
        for _ in 0..160 {
            if writer.write_all(&chunk).is_err() {
                break;
            }
        }
    }

    let status = child.wait().unwrap();
    let _ = status;
}

/// `init` with 2 KB of 'y' (no newline) as stdin must not treat the input as "yes".
/// After reading MAX_CONFIRM_BYTES, content beyond the limit is discarded;
/// a blob of raw 'y' bytes without a valid "y\n" response must be treated as "no".
#[test]
fn init_prompt_confirm_huge_stdin_is_treated_as_no() {
    let dir = tempfile::tempdir().unwrap();
    let config_path = dir.path().join("config.toml");

    let mut child = init_cmd_in_dir(dir.path())
        .args(["--config", config_path.to_str().unwrap(), "init"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();

    {
        let stdin = child.stdin.take().unwrap();
        let mut writer = std::io::BufWriter::new(stdin);
        let blob = vec![b'y'; 2048];
        let _ = writer.write_all(&blob);
    }

    let output = child.wait_with_output().unwrap();
    let stdout = String::from_utf8_lossy(&output.stdout);
    assert!(
        !config_path.exists() || stdout.contains("Skipped"),
        "huge 'yyy...' blob without newline must not be treated as 'yes': stdout={stdout}"
    );
}