rskim 2.3.0

The most intelligent context optimization engine for coding agents. Code-aware AST parsing, command rewriting, output compression.
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
//! Integration tests for `skim init` and `skim rewrite --hook` (#44).
//!
//! All tests use `tempfile::TempDir` + `CLAUDE_CONFIG_DIR` env override for
//! isolation. Non-interactive tests pass `--yes`.

use assert_cmd::Command;
use predicates::prelude::*;
use std::fs;
use std::os::unix::fs::PermissionsExt;
use tempfile::TempDir;

// ============================================================================
// Helper: build an isolated `skim init` command with CLAUDE_CONFIG_DIR override
// ============================================================================

fn skim_init_cmd(config_dir: &std::path::Path) -> Command {
    let mut cmd = Command::cargo_bin("skim").unwrap();
    cmd.arg("init")
        .env("CLAUDE_CONFIG_DIR", config_dir.as_os_str());
    cmd
}

/// Returns true if the hook entry references the skim-rewrite script.
fn is_skim_hook(entry: &serde_json::Value) -> bool {
    entry
        .get("hooks")
        .and_then(|h| h.as_array())
        .map(|hooks| {
            hooks.iter().any(|h| {
                h.get("command")
                    .and_then(|c| c.as_str())
                    .is_some_and(|s| s.contains("skim-rewrite"))
            })
        })
        .unwrap_or(false)
}

// ============================================================================
// Fresh install tests
// ============================================================================

#[test]
fn test_init_creates_hook_script() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    skim_init_cmd(config)
        .args(["--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Created").or(predicate::str::contains("Patched")));

    let hook_script = config.join("hooks/skim-rewrite.sh");
    assert!(hook_script.exists(), "Hook script should be created");

    let content = fs::read_to_string(&hook_script).unwrap();
    assert!(
        content.starts_with("#!/usr/bin/env bash"),
        "Should have shebang"
    );
    assert!(
        content.contains("SKIM_HOOK_VERSION"),
        "Should export version"
    );
    assert!(
        content.contains("rewrite --hook"),
        "Should exec rewrite --hook"
    );

    // Check executable permissions
    let perms = fs::metadata(&hook_script).unwrap().permissions();
    assert_eq!(
        perms.mode() & 0o111,
        0o111,
        "Hook script should be executable"
    );
}

#[test]
fn test_init_creates_settings_from_scratch() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    let settings_path = config.join("settings.json");
    assert!(settings_path.exists(), "settings.json should be created");

    let contents = fs::read_to_string(&settings_path).unwrap();
    let json: serde_json::Value = serde_json::from_str(&contents).unwrap();

    // Verify hooks.PreToolUse exists with a skim entry
    let ptu = &json["hooks"]["PreToolUse"];
    assert!(ptu.is_array(), "PreToolUse should be an array");
    let arr = ptu.as_array().unwrap();
    assert!(!arr.is_empty(), "PreToolUse should have at least one entry");

    let skim_entry = arr.iter().find(|e| is_skim_hook(e));
    assert!(skim_entry.is_some(), "Should have a skim hook entry");
}

#[test]
fn test_init_preserves_existing_hooks() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    fs::create_dir_all(config).unwrap();

    // Pre-populate with an existing hook
    let existing = serde_json::json!({
        "hooks": {
            "PreToolUse": [
                {
                    "matcher": "Bash",
                    "hooks": [{"type": "command", "command": "/usr/bin/other-hook", "timeout": 10}]
                }
            ]
        }
    });
    fs::write(
        config.join("settings.json"),
        serde_json::to_string_pretty(&existing).unwrap(),
    )
    .unwrap();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    let json: serde_json::Value = serde_json::from_str(&contents).unwrap();

    let ptu = json["hooks"]["PreToolUse"].as_array().unwrap();
    assert!(
        ptu.len() >= 2,
        "Should have both existing and new hooks, got {}",
        ptu.len()
    );

    let other_exists = ptu.iter().any(|e| {
        e.get("hooks")
            .and_then(|h| h.as_array())
            .map(|hooks| {
                hooks.iter().any(|h| {
                    h.get("command")
                        .and_then(|c| c.as_str())
                        .is_some_and(|s| s.contains("other-hook"))
                })
            })
            .unwrap_or(false)
    });
    assert!(other_exists, "Existing hook should be preserved");
}

// ============================================================================
// Idempotency
// ============================================================================

#[test]
fn test_init_idempotent_no_duplicates() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    // Run init twice
    skim_init_cmd(config).args(["--yes"]).assert().success();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    let json: serde_json::Value = serde_json::from_str(&contents).unwrap();

    let ptu = json["hooks"]["PreToolUse"].as_array().unwrap();
    // Count skim entries
    let skim_count = ptu.iter().filter(|e| is_skim_hook(e)).count();

    assert_eq!(
        skim_count, 1,
        "Should have exactly one skim entry, not duplicates"
    );
}

#[test]
fn test_init_updates_stale_hook_version() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    // Run init once
    skim_init_cmd(config).args(["--yes"]).assert().success();

    // Manually overwrite the hook script with an old version
    let hook_path = config.join("hooks/skim-rewrite.sh");
    let old_content = "#!/usr/bin/env bash\n# skim-hook v0.0.1\nexport SKIM_HOOK_VERSION=\"0.0.1\"\nexec skim rewrite --hook\n";
    fs::write(&hook_path, old_content).unwrap();

    // Run init again — should update the script
    skim_init_cmd(config)
        .args(["--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Updated").or(predicate::str::contains("Created")));

    // Verify new version in script
    let content = fs::read_to_string(&hook_path).unwrap();
    assert!(
        !content.contains("v0.0.1"),
        "Should have been updated from v0.0.1"
    );
}

// ============================================================================
// Settings structure
// ============================================================================

#[test]
fn test_init_hook_structure() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    let json: serde_json::Value = serde_json::from_str(&contents).unwrap();

    let ptu = json["hooks"]["PreToolUse"].as_array().unwrap();
    let skim_entry = ptu.iter().find(|e| is_skim_hook(e)).unwrap();

    // Check structure: matcher, hooks array with type, command, timeout
    assert_eq!(skim_entry["matcher"], "Bash");
    let hooks = skim_entry["hooks"].as_array().unwrap();
    assert_eq!(hooks.len(), 1);
    assert_eq!(hooks[0]["type"], "command");
    assert_eq!(hooks[0]["timeout"], 5);
}

#[test]
fn test_init_no_permission_decision() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    assert!(
        !contents.contains("permissionDecision"),
        "SECURITY: must never contain permissionDecision"
    );
}

// ============================================================================
// Marketplace
// ============================================================================

#[test]
fn test_init_adds_marketplace() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    let json: serde_json::Value = serde_json::from_str(&contents).unwrap();

    let skim_mkt = &json["extraKnownMarketplaces"]["skim"];
    assert!(
        skim_mkt.is_object(),
        "Should have extraKnownMarketplaces.skim"
    );
    assert_eq!(skim_mkt["source"]["repo"], "dean0x/skim");
}

// ============================================================================
// Symlinks
// ============================================================================

#[test]
fn test_init_preserves_symlinks() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    let real_dir = dir.path().join("real_claude");
    fs::create_dir_all(&real_dir).unwrap();

    // Create a real settings.json in the "real" location
    fs::write(real_dir.join("settings.json"), "{}").unwrap();

    // Create config dir and symlink settings.json
    fs::create_dir_all(config).unwrap();
    std::os::unix::fs::symlink(real_dir.join("settings.json"), config.join("settings.json"))
        .unwrap();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    // The symlink should still exist
    assert!(
        config.join("settings.json").is_symlink(),
        "Symlink should be preserved"
    );

    // The real file should have the hook content
    let real_contents = fs::read_to_string(real_dir.join("settings.json")).unwrap();
    assert!(
        real_contents.contains("PreToolUse"),
        "Real file should have hook content"
    );
}

// ============================================================================
// Project mode
// ============================================================================

#[test]
fn test_init_project_mode() {
    let dir = TempDir::new().unwrap();
    let project_dir = dir.path().join("my-project");
    fs::create_dir_all(&project_dir).unwrap();

    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes"])
        .current_dir(&project_dir)
        .assert()
        .success();

    // Should create .claude/ directory in project
    let claude_dir = project_dir.join(".claude");
    assert!(claude_dir.exists(), ".claude dir should be created");
    assert!(
        claude_dir.join("settings.json").exists(),
        "settings.json should exist"
    );
    assert!(
        claude_dir.join("hooks/skim-rewrite.sh").exists(),
        "Hook script should exist"
    );
}

// ============================================================================
// Non-interactive mode
// ============================================================================

#[test]
fn test_init_yes_flag() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    // --yes should complete without stdin
    skim_init_cmd(config)
        .args(["--yes"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("Done!").or(predicate::str::contains("Already up to date")),
        );
}

#[test]
fn test_init_project_yes() {
    let dir = TempDir::new().unwrap();
    let project_dir = dir.path().join("proj");
    fs::create_dir_all(&project_dir).unwrap();

    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes"])
        .current_dir(&project_dir)
        .assert()
        .success();

    assert!(project_dir.join(".claude/settings.json").exists());
}

// ============================================================================
// Non-TTY detection
// ============================================================================

#[test]
fn test_init_non_tty_without_yes_fails() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    // When invoked without --yes and stdin is not a terminal (piped),
    // should fail with a hint.
    // Note: assert_cmd by default provides non-TTY stdin.
    skim_init_cmd(config)
        .assert()
        .failure()
        .stderr(predicate::str::contains("interactive terminal"))
        .stderr(predicate::str::contains("--yes"));
}

// ============================================================================
// Dry-run
// ============================================================================

#[test]
fn test_init_dry_run() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    skim_init_cmd(config)
        .args(["--yes", "--dry-run"])
        .assert()
        .success()
        .stdout(predicate::str::contains("[dry-run]"));

    // No files should have been created
    assert!(
        !config.join("settings.json").exists(),
        "Dry-run should not create files"
    );
    assert!(
        !config.join("hooks/skim-rewrite.sh").exists(),
        "Dry-run should not create hook script"
    );
}

// ============================================================================
// Uninstall
// ============================================================================

#[test]
fn test_init_uninstall() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    // First install
    skim_init_cmd(config).args(["--yes"]).assert().success();

    // Then uninstall
    skim_init_cmd(config)
        .args(["--uninstall", "--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Removed").or(predicate::str::contains("Deleted")));

    // Hook script should be gone
    assert!(
        !config.join("hooks/skim-rewrite.sh").exists(),
        "Hook script should be deleted"
    );

    // Settings should exist but without skim entries
    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    assert!(
        !contents.contains("skim-rewrite"),
        "Hook entry should be removed"
    );
    assert!(
        !contents.contains("\"skim\""),
        "Marketplace entry should be removed"
    );
}

#[test]
fn test_init_uninstall_preserves_other_hooks() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    // Install skim
    skim_init_cmd(config).args(["--yes"]).assert().success();

    // Manually add another hook
    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    let mut json: serde_json::Value = serde_json::from_str(&contents).unwrap();
    let ptu = json["hooks"]["PreToolUse"].as_array_mut().unwrap();
    ptu.push(serde_json::json!({
        "matcher": "Bash",
        "hooks": [{"type": "command", "command": "/usr/bin/other-hook", "timeout": 10}]
    }));
    fs::write(
        config.join("settings.json"),
        serde_json::to_string_pretty(&json).unwrap(),
    )
    .unwrap();

    // Uninstall skim
    skim_init_cmd(config)
        .args(["--uninstall", "--yes"])
        .assert()
        .success();

    // Other hook should remain
    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    assert!(
        contents.contains("other-hook"),
        "Other hooks should be preserved"
    );
}

#[test]
fn test_init_uninstall_when_not_installed() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    skim_init_cmd(config)
        .args(["--uninstall", "--yes"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Nothing to uninstall"));
}

// ============================================================================
// Backup
// ============================================================================

#[test]
fn test_init_creates_backup() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    fs::create_dir_all(config).unwrap();

    // Create an existing settings.json
    fs::write(config.join("settings.json"), "{}\n").unwrap();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    assert!(
        config.join("settings.json.bak").exists(),
        "Backup should be created"
    );
}

// ============================================================================
// Edge cases
// ============================================================================

#[test]
fn test_init_empty_settings_file() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    fs::create_dir_all(config).unwrap();

    // Create a 0-byte settings.json
    fs::write(config.join("settings.json"), "").unwrap();

    skim_init_cmd(config).args(["--yes"]).assert().success();

    let contents = fs::read_to_string(config.join("settings.json")).unwrap();
    let json: serde_json::Value = serde_json::from_str(&contents).unwrap();
    assert!(
        json["hooks"]["PreToolUse"].is_array(),
        "Should create valid structure from empty file"
    );
}

#[test]
fn test_init_malformed_json() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    fs::create_dir_all(config).unwrap();

    // Create a malformed settings.json
    fs::write(config.join("settings.json"), "{not valid json}").unwrap();

    skim_init_cmd(config)
        .args(["--yes"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("Failed to parse"));
}

// ============================================================================
// Hook mode tests (skim rewrite --hook)
// ============================================================================

fn hook_payload(command: &str) -> String {
    serde_json::json!({
        "hook_event_name": "PreToolUse",
        "tool_name": "Bash",
        "tool_input": {
            "command": command
        }
    })
    .to_string()
}

#[test]
fn test_hook_cargo_test_match() {
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin(hook_payload("cargo test"))
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    assert_eq!(json["hookSpecificOutput"]["hookEventName"], "PreToolUse");
    assert!(json["hookSpecificOutput"]["updatedInput"]["command"]
        .as_str()
        .unwrap()
        .contains("skim test cargo"));
}

#[test]
fn test_hook_no_match_empty_output() {
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin(hook_payload("echo hello"))
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.trim().is_empty(),
        "No match should produce empty stdout"
    );
}

#[test]
fn test_hook_already_rewritten_passthrough() {
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin(hook_payload("skim test cargo"))
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.trim().is_empty(),
        "Already-rewritten command should pass through"
    );
}

#[test]
fn test_hook_no_permission_decision() {
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin(hook_payload("cargo test"))
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    assert!(
        !stdout.contains("permissionDecision"),
        "SECURITY: hook must never set permissionDecision"
    );
}

#[test]
fn test_hook_malformed_json_exits_zero() {
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin("not json at all")
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.trim().is_empty(),
        "Malformed JSON should exit 0 with empty stdout"
    );
}

#[test]
fn test_hook_missing_command_field() {
    let payload = serde_json::json!({
        "tool_name": "Bash",
        "tool_input": {
            "description": "no command field here"
        }
    })
    .to_string();

    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin(payload)
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.trim().is_empty(),
        "Missing command field should exit 0 with empty stdout"
    );
}

// ============================================================================
// Hook mode — compound commands (#45)
// ============================================================================

#[test]
fn test_hook_compound_command_rewrite() {
    // Send a compound command (&&) through hook mode — first segment should be rewritten
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin(hook_payload("cargo test && cargo clippy"))
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();

    assert_eq!(json["hookSpecificOutput"]["hookEventName"], "PreToolUse");
    let rewritten = json["hookSpecificOutput"]["updatedInput"]["command"]
        .as_str()
        .unwrap();
    assert!(
        rewritten.contains("skim test cargo"),
        "First segment should be rewritten, got: {rewritten}"
    );
    assert!(
        rewritten.contains("&&"),
        "Compound operator should be preserved, got: {rewritten}"
    );
}

#[test]
fn test_hook_pipe_command_passthrough() {
    // Pipe command where neither segment matches a rewrite rule — empty output
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .write_stdin(hook_payload("echo hello | grep world"))
        .assert()
        .success();

    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    assert!(
        stdout.trim().is_empty(),
        "Non-matching pipe command should produce empty stdout, got: {stdout}"
    );
}

// ============================================================================
// Hook mode — version mismatch warning (#44 A2)
// ============================================================================

#[test]
fn test_hook_version_mismatch_warning() {
    // Use a temp dir for cache to avoid stamp file pollution across tests.
    let cache_dir = TempDir::new().unwrap();

    // Set SKIM_HOOK_VERSION to a value that differs from the compiled version.
    // The warning now goes to hook.log (NEVER stderr -- GRANITE #361 Bug 3).
    let output = Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--hook"])
        .env("SKIM_HOOK_VERSION", "0.0.1")
        .env("SKIM_CACHE_DIR", cache_dir.path().as_os_str())
        .write_stdin(hook_payload("cargo test"))
        .assert()
        .success();

    // CRITICAL: stderr MUST be empty in hook mode (zero-stderr invariant)
    let stderr = String::from_utf8(output.get_output().stderr.clone()).unwrap();
    assert!(
        stderr.is_empty(),
        "Hook mode must have zero stderr even on version mismatch, got: {stderr}"
    );

    // The rewrite should still succeed
    let stdout = String::from_utf8(output.get_output().stdout.clone()).unwrap();
    let json: serde_json::Value = serde_json::from_str(&stdout).unwrap();
    assert!(
        json["hookSpecificOutput"]["updatedInput"]["command"]
            .as_str()
            .unwrap()
            .contains("skim test cargo"),
        "Rewrite should succeed despite version mismatch"
    );

    // Verify warning went to hook.log file instead
    let hook_log = cache_dir.path().join("hook.log");
    assert!(
        hook_log.exists(),
        "Version mismatch warning should be written to hook.log"
    );
    let log_content = fs::read_to_string(&hook_log).unwrap();
    assert!(
        log_content.contains("version mismatch"),
        "hook.log should contain version mismatch warning, got: {log_content}"
    );
}

// ============================================================================
// Help text
// ============================================================================

#[test]
fn test_init_help() {
    Command::cargo_bin("skim")
        .unwrap()
        .args(["init", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("skim init"))
        .stdout(predicate::str::contains("--global"))
        .stdout(predicate::str::contains("--project"))
        .stdout(predicate::str::contains("--yes"))
        .stdout(predicate::str::contains("--dry-run"))
        .stdout(predicate::str::contains("--uninstall"));
}

#[test]
fn test_rewrite_hook_help() {
    Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--hook"));
}

// ============================================================================
// Guidance injection
// ============================================================================

#[test]
fn test_init_creates_guidance() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();

    // Create a CLAUDE.md at the "global" location (config_dir/../CLAUDE.md won't work,
    // so we test via project mode which creates CLAUDE.md in CWD)
    let project_dir = TempDir::new().unwrap();

    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes"])
        .env("CLAUDE_CONFIG_DIR", config.as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    // Check that CLAUDE.md was created with guidance
    let claude_md = project_dir.path().join("CLAUDE.md");
    assert!(
        claude_md.exists(),
        "CLAUDE.md should be created with guidance"
    );
    let content = fs::read_to_string(&claude_md).unwrap();
    assert!(
        content.contains("<!-- skim-start"),
        "CLAUDE.md should contain skim guidance section"
    );
    assert!(
        content.contains("<!-- skim-end -->"),
        "CLAUDE.md should have closing marker"
    );
    assert!(
        content.contains("npx rskim"),
        "Guidance should reference npx rskim"
    );
}

#[test]
fn test_init_no_guidance_flag() {
    let dir = TempDir::new().unwrap();
    let project_dir = TempDir::new().unwrap();

    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes", "--no-guidance"])
        .env("CLAUDE_CONFIG_DIR", dir.path().as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    // CLAUDE.md should not exist (no guidance injected, file not created)
    let claude_md = project_dir.path().join("CLAUDE.md");
    assert!(
        !claude_md.exists(),
        "CLAUDE.md should not be created with --no-guidance"
    );
}

#[test]
fn test_init_uninstall_removes_guidance() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    let project_dir = TempDir::new().unwrap();

    // First install with guidance
    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes"])
        .env("CLAUDE_CONFIG_DIR", config.as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    // Verify install created guidance
    let claude_md = project_dir.path().join("CLAUDE.md");
    assert!(claude_md.exists(), "CLAUDE.md should exist after install");

    // Then uninstall
    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--uninstall", "--yes"])
        .env("CLAUDE_CONFIG_DIR", config.as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    // CLAUDE.md should not contain skim guidance (or be deleted if it was the only content)
    let claude_md = project_dir.path().join("CLAUDE.md");
    if claude_md.exists() {
        let content = fs::read_to_string(&claude_md).unwrap();
        assert!(
            !content.contains("skim-start"),
            "Guidance section should be removed after uninstall"
        );
    }
    // If file doesn't exist, that's also correct (was only skim content)
}

#[test]
fn test_init_guidance_idempotent() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    let project_dir = TempDir::new().unwrap();

    // Install twice
    for _ in 0..2 {
        Command::cargo_bin("skim")
            .unwrap()
            .arg("init")
            .args(["--project", "--yes"])
            .env("CLAUDE_CONFIG_DIR", config.as_os_str())
            .current_dir(project_dir.path())
            .assert()
            .success();
    }

    // CLAUDE.md should have exactly one skim section
    let claude_md = project_dir.path().join("CLAUDE.md");
    assert!(claude_md.exists(), "CLAUDE.md should exist after init");
    let content = fs::read_to_string(&claude_md).unwrap();
    let start_count = content.matches("<!-- skim-start").count();
    assert_eq!(
        start_count, 1,
        "Should have exactly one skim section, found {}",
        start_count
    );
}

#[test]
fn test_init_dry_run_shows_guidance() {
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    let project_dir = TempDir::new().unwrap();

    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes", "--dry-run"])
        .env("CLAUDE_CONFIG_DIR", config.as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success()
        .stdout(predicate::str::contains("guidance"));
}

// ============================================================================
// Cursor .mdc format
// ============================================================================

#[test]
fn test_init_cursor_creates_mdc() {
    let config_dir = TempDir::new().unwrap();
    let project_dir = TempDir::new().unwrap();

    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes", "--agent", "cursor"])
        .env("CLAUDE_CONFIG_DIR", config_dir.path().as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    // Should create .cursor/rules/skim.mdc with frontmatter
    let mdc = project_dir.path().join(".cursor/rules/skim.mdc");
    assert!(mdc.exists(), ".cursor/rules/skim.mdc should be created");
    let content = fs::read_to_string(&mdc).unwrap();
    assert!(content.starts_with("---\n"), "Should have YAML frontmatter");
    assert!(
        content.contains("alwaysApply: true"),
        "Should have alwaysApply"
    );
    assert!(
        content.contains("<!-- skim-start"),
        "Should have skim start marker"
    );
    assert!(
        content.contains("<!-- skim-end -->"),
        "Should have skim end marker"
    );
}

#[test]
fn test_init_cursor_uninstall_deletes_mdc() {
    let config_dir = TempDir::new().unwrap();
    let project_dir = TempDir::new().unwrap();

    // Install
    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes", "--agent", "cursor"])
        .env("CLAUDE_CONFIG_DIR", config_dir.path().as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    let mdc = project_dir.path().join(".cursor/rules/skim.mdc");
    assert!(mdc.exists(), "skim.mdc should exist after install");

    // Uninstall
    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--uninstall", "--yes", "--agent", "cursor"])
        .env("CLAUDE_CONFIG_DIR", config_dir.path().as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    assert!(!mdc.exists(), "skim.mdc should be deleted on uninstall");
}

#[test]
fn test_init_cursor_cleans_legacy_cursorrules() {
    let config_dir = TempDir::new().unwrap();
    let project_dir = TempDir::new().unwrap();

    // Pre-populate a .cursorrules with skim markers (legacy format)
    let cursorrules = project_dir.path().join(".cursorrules");
    fs::write(
        &cursorrules,
        "# User rules\n\n<!-- skim-start v1.0.0 -->\nold guidance\n<!-- skim-end -->\n\n# More user rules\n",
    )
    .unwrap();

    // Install Cursor (should create .mdc AND clean legacy .cursorrules)
    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes", "--agent", "cursor"])
        .env("CLAUDE_CONFIG_DIR", config_dir.path().as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    // New .mdc should exist
    let mdc = project_dir.path().join(".cursor/rules/skim.mdc");
    assert!(mdc.exists(), ".cursor/rules/skim.mdc should be created");

    // Legacy .cursorrules should still exist (user may have created it)
    assert!(
        cursorrules.exists(),
        ".cursorrules should NOT be deleted (user owns it)"
    );

    // But skim markers should be removed from .cursorrules
    let content = fs::read_to_string(&cursorrules).unwrap();
    assert!(
        !content.contains("skim-start"),
        "Skim markers should be removed from .cursorrules, got: {content}"
    );
    assert!(
        content.contains("User rules"),
        "User content should be preserved in .cursorrules"
    );
}

// ============================================================================
// Phase 6: Multi-agent awareness in skim init
// ============================================================================

#[test]
fn test_init_help_mentions_agent_flag() {
    // init --help should document the --agent flag for multi-agent support
    Command::cargo_bin("skim")
        .unwrap()
        .args(["init", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--agent"));
}

#[test]
fn test_rewrite_help_mentions_agent_flag() {
    // rewrite --help should mention the --agent flag
    Command::cargo_bin("skim")
        .unwrap()
        .args(["rewrite", "--help"])
        .assert()
        .success()
        .stdout(predicate::str::contains("--agent"));
}

// ============================================================================
// Guidance upgrade bypass tests (issue 11)
// ============================================================================

#[test]
fn test_init_guidance_upgrade_updates_stale_version() {
    // Verifies that is_guidance_current returns false when the guidance section
    // contains a stale version marker, causing a re-run of init --yes to
    // update guidance rather than print "Already up to date".
    let dir = TempDir::new().unwrap();
    let config = dir.path();
    let project_dir = TempDir::new().unwrap();

    // Step 1: fresh install — creates guidance at the current version
    Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes"])
        .env("CLAUDE_CONFIG_DIR", config.as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success();

    let claude_md = project_dir.path().join("CLAUDE.md");
    assert!(
        claude_md.exists(),
        "CLAUDE.md should exist after initial install"
    );

    // Step 2: manually overwrite the guidance section with an old version marker
    let content = fs::read_to_string(&claude_md).unwrap();
    assert!(
        content.contains("<!-- skim-start"),
        "Initial install should have created a skim-start marker"
    );
    // Replace the versioned marker with an obviously stale one
    let stale_content = {
        let start = content
            .find("<!-- skim-start")
            .expect("start marker must exist");
        let marker_end = content[start..]
            .find(" -->")
            .expect("marker closing must exist");
        let mut s = content.clone();
        s.replace_range(start..start + marker_end + 4, "<!-- skim-start v0.0.1 -->");
        s
    };
    fs::write(&claude_md, &stale_content).unwrap();
    assert!(
        stale_content.contains("<!-- skim-start v0.0.1 -->"),
        "Stale marker should be present after manual overwrite"
    );

    // Step 3: re-run init --yes — should NOT say "Already up to date"
    let output = Command::cargo_bin("skim")
        .unwrap()
        .arg("init")
        .args(["--project", "--yes"])
        .env("CLAUDE_CONFIG_DIR", config.as_os_str())
        .current_dir(project_dir.path())
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let stdout = String::from_utf8_lossy(&output);

    assert!(
        !stdout.contains("Already up to date"),
        "Should not say 'Already up to date' when guidance version is stale; got:\n{stdout}"
    );

    // Step 4: verify the guidance was updated to the current version
    let updated = fs::read_to_string(&claude_md).unwrap();
    assert!(
        !updated.contains("v0.0.1"),
        "Stale version marker should have been replaced"
    );
    assert!(
        updated.contains("<!-- skim-start v"),
        "Updated file should have a versioned skim-start marker"
    );
    // The new marker should not be the old stale version
    let current_version = env!("CARGO_PKG_VERSION");
    assert!(
        updated.contains(&format!("<!-- skim-start v{current_version} -->")),
        "Updated marker should reference the current binary version ({current_version})"
    );
}