vibestats 2.4.4

CLI that syncs Claude Code and Codex session activity to a private GitHub repo and renders a profile heatmap + analytics dashboard.
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
fn user_profile_dir() -> Option<std::path::PathBuf> {
    #[cfg(windows)]
    {
        std::env::var("USERPROFILE")
            .ok()
            .map(std::path::PathBuf::from)
    }

    #[cfg(not(windows))]
    {
        std::env::var("HOME").ok().map(std::path::PathBuf::from)
    }
}

/// Returns the path to the Claude settings file for the current platform.
fn settings_path() -> Option<std::path::PathBuf> {
    user_profile_dir().map(|h| h.join(".claude").join("settings.json"))
}

/// Returns the path to the Codex hooks file for the current platform.
fn codex_hooks_path() -> Option<std::path::PathBuf> {
    user_profile_dir().map(|h| h.join(".codex").join("hooks.json"))
}

/// Renames `path` aside and schedules the renamed file for deletion on next
/// reboot. Windows keeps a running exe's image file locked, so it can't be
/// deleted while `vibestats uninstall` (running as that same exe) is still
/// executing - but Windows does allow renaming a running exe, so this at
/// least frees up the original filename immediately.
#[cfg(windows)]
fn schedule_binary_delete_on_reboot(path: &std::path::Path) -> std::io::Result<()> {
    use std::os::windows::ffi::OsStrExt;

    let old_path = path.with_extension("exe.old");
    std::fs::rename(path, &old_path)?;

    #[link(name = "kernel32")]
    extern "system" {
        fn MoveFileExW(existing: *const u16, new: *const u16, flags: u32) -> i32;
    }
    const MOVEFILE_DELAY_UNTIL_REBOOT: u32 = 0x4;

    let wide: Vec<u16> = old_path
        .as_os_str()
        .encode_wide()
        .chain(std::iter::once(0))
        .collect();
    let ok =
        unsafe { MoveFileExW(wide.as_ptr(), std::ptr::null(), MOVEFILE_DELAY_UNTIL_REBOOT) != 0 };

    if ok {
        Ok(())
    } else {
        Err(std::io::Error::last_os_error())
    }
}

/// Returns the path to the installed vibestats binary for the current platform.
fn binary_path() -> Option<std::path::PathBuf> {
    #[cfg(windows)]
    {
        std::env::var("LOCALAPPDATA").ok().map(|h| {
            std::path::PathBuf::from(h)
                .join("Programs")
                .join("vibestats")
                .join("vibestats.exe")
        })
    }

    #[cfg(not(windows))]
    {
        std::env::var("HOME").ok().map(|h| {
            std::path::PathBuf::from(h)
                .join(".local")
                .join("bin")
                .join("vibestats")
        })
    }
}

fn first_command_token(command: &str) -> Option<&str> {
    let trimmed = command.trim_start();
    if trimmed.is_empty() {
        return None;
    }

    if let Some(rest) = trimmed.strip_prefix('"') {
        let end_quote = rest.find('"')?;
        return Some(&rest[..end_quote]);
    }

    trimmed.split_whitespace().next()
}

fn command_executable_basename(command: &str) -> Option<&str> {
    let token = first_command_token(command)?;
    token.rsplit(['/', '\\']).next()
}

/// True if a hook object's "command" field invokes the vibestats binary.
///
/// Supports both legacy PATH-based hooks such as `vibestats sync` and
/// full-path hooks written by the Windows installer such as
/// `"C:\\Users\\...\\vibestats.exe" sync`.
/// Narrow on purpose: only inspects the first executable token, avoiding false
/// positives like `"my-tool --flag vibestats-backup"`.
// ponytail: hook contract triplicated in install.sh + install.ps1 + here;
// fold into a `vibestats install-hooks` subcommand when the next harness
// or hook-format change lands.
fn is_vibestats_hook(hook_obj: &serde_json::Value) -> bool {
    hook_obj
        .get("command")
        .and_then(|c| c.as_str())
        .and_then(command_executable_basename)
        .map(|name| {
            name.eq_ignore_ascii_case("vibestats") || name.eq_ignore_ascii_case("vibestats.exe")
        })
        .unwrap_or(false)
}

/// Remove vibestats hook entries from a settings.json JSON Value in place.
/// Preserves all non-vibestats hooks and all other top-level settings keys.
/// Returns `true` if anything was removed, `false` otherwise.
///
/// Scope: only the `Stop` and `SessionStart` hook types — the only ones the vibestats
/// installer writes to. Cleans up empty groups, empty hook-type arrays, and the
/// top-level `hooks` object if it becomes empty.
fn remove_vibestats_hooks(settings: &mut serde_json::Value) -> bool {
    let mut changed = false;

    // First pass: operate only on Stop and SessionStart under the "hooks" object.
    for hook_type in &["Stop", "SessionStart"] {
        let Some(groups_arr) = settings
            .get_mut("hooks")
            .and_then(|h| h.get_mut(*hook_type))
            .and_then(|h| h.as_array_mut())
        else {
            continue;
        };

        // Filter inner "hooks" arrays inside each group.
        for group in groups_arr.iter_mut() {
            let Some(inner_hooks) = group.get_mut("hooks").and_then(|h| h.as_array_mut()) else {
                continue;
            };
            let before = inner_hooks.len();
            inner_hooks.retain(|hook| !is_vibestats_hook(hook));
            if inner_hooks.len() != before {
                changed = true;
            }
        }

        // Drop groups whose "hooks" array is now empty. Preserve groups without a
        // "hooks" key (unknown format — leave untouched).
        let before = groups_arr.len();
        groups_arr.retain(|group| {
            group
                .get("hooks")
                .and_then(|h| h.as_array())
                .map(|arr| !arr.is_empty())
                .unwrap_or(true)
        });
        if groups_arr.len() != before {
            changed = true;
        }
    }

    if !changed {
        return false;
    }

    // Second pass: drop hook-type keys whose value is now an empty array.
    if let Some(hooks_obj) = settings.get_mut("hooks").and_then(|h| h.as_object_mut()) {
        for hook_type in &["Stop", "SessionStart"] {
            let is_empty = hooks_obj
                .get(*hook_type)
                .and_then(|v| v.as_array())
                .map(|a| a.is_empty())
                .unwrap_or(false);
            if is_empty {
                hooks_obj.remove(*hook_type);
            }
        }
    }

    // Third pass: drop the top-level "hooks" key if the object is now empty.
    let hooks_empty = settings
        .get("hooks")
        .and_then(|h| h.as_object())
        .map(|o| o.is_empty())
        .unwrap_or(false);
    if hooks_empty {
        if let Some(root) = settings.as_object_mut() {
            root.remove("hooks");
        }
    }

    true
}

/// Entry point for `vibestats uninstall`.
///
/// Steps:
/// 1. Remove vibestats hook entries from ~/.claude/settings.json
/// 2. Delete the vibestats binary from ~/.local/bin/vibestats
/// 3. Print manual cleanup instructions
///
/// NEVER calls std::process::exit — main.rs handles exit.
pub fn run() {
    // Step 1: Remove vibestats hooks from ~/.claude/settings.json
    match settings_path() {
        None => {
            println!(
                "vibestats: {} not set — skipping hook removal",
                if cfg!(windows) { "USERPROFILE" } else { "HOME" }
            );
        }
        Some(path) => {
            if !path.exists() {
                println!("vibestats: no vibestats hooks found in settings.json (already clean)");
            } else {
                match std::fs::read_to_string(&path) {
                    Err(e) => {
                        println!("vibestats: could not read ~/.claude/settings.json: {e}");
                        println!("Hook removal skipped.");
                    }
                    Ok(contents) => match serde_json::from_str::<serde_json::Value>(&contents) {
                        Err(e) => {
                            println!("vibestats: could not parse ~/.claude/settings.json: {e}");
                            println!("Hook removal skipped.");
                        }
                        Ok(mut settings) => {
                            if remove_vibestats_hooks(&mut settings) {
                                match serde_json::to_string_pretty(&settings) {
                                    Err(e) => {
                                        println!(
                                            "vibestats: could not serialize ~/.claude/settings.json: {e}"
                                        );
                                    }
                                    Ok(updated) => {
                                        // Write atomically via a sibling .tmp file then
                                        // rename, so a crash or disk-full mid-write can
                                        // never leave settings.json truncated/corrupt.
                                        let mut tmp_path = path.clone();
                                        let mut tmp_name =
                                            path.file_name().unwrap_or_default().to_os_string();
                                        tmp_name.push(".tmp");
                                        tmp_path.set_file_name(tmp_name);
                                        let write_result =
                                            std::fs::write(&tmp_path, updated + "\n")
                                                .and_then(|()| std::fs::rename(&tmp_path, &path));
                                        match write_result {
                                            Err(e) => {
                                                // Clean up the temp file on failure (best effort).
                                                let _ = std::fs::remove_file(&tmp_path);
                                                println!(
                                                    "vibestats: could not write ~/.claude/settings.json: {e}"
                                                );
                                            }
                                            Ok(()) => {
                                                println!(
                                                    "vibestats: removed Stop and SessionStart hooks from ~/.claude/settings.json"
                                                );
                                            }
                                        }
                                    }
                                }
                            } else {
                                println!(
                                    "vibestats: no vibestats hooks found in settings.json (already clean)"
                                );
                            }
                        }
                    },
                }
            }
        }
    }

    // Step 1b: Remove vibestats hooks from ~/.codex/hooks.json
    if let Some(path) = codex_hooks_path() {
        if path.exists() {
            match std::fs::read_to_string(&path) {
                Err(e) => {
                    println!("vibestats: could not read ~/.codex/hooks.json: {e}");
                    println!("Codex hook removal skipped.");
                }
                Ok(contents) => match serde_json::from_str::<serde_json::Value>(&contents) {
                    Err(e) => {
                        println!("vibestats: could not parse ~/.codex/hooks.json: {e}");
                        println!("Codex hook removal skipped.");
                    }
                    Ok(mut settings) => {
                        if remove_vibestats_hooks(&mut settings) {
                            match serde_json::to_string_pretty(&settings) {
                                Err(e) => {
                                    println!(
                                        "vibestats: could not serialize ~/.codex/hooks.json: {e}"
                                    );
                                }
                                Ok(updated) => {
                                    let mut tmp_path = path.clone();
                                    let mut tmp_name =
                                        path.file_name().unwrap_or_default().to_os_string();
                                    tmp_name.push(".tmp");
                                    tmp_path.set_file_name(tmp_name);
                                    let write_result = std::fs::write(&tmp_path, updated + "\n")
                                        .and_then(|()| std::fs::rename(&tmp_path, &path));
                                    match write_result {
                                        Err(e) => {
                                            let _ = std::fs::remove_file(&tmp_path);
                                            println!(
                                                "vibestats: could not write ~/.codex/hooks.json: {e}"
                                            );
                                        }
                                        Ok(()) => {
                                            println!(
                                                "vibestats: removed Stop and SessionStart hooks from ~/.codex/hooks.json"
                                            );
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
            }
        }
    }

    // Step 2: Delete the vibestats binary from ~/.local/bin/vibestats (AC #4).
    // This is the installer's target location; it is deliberately NOT `current_exe()`
    // so a developer running `cargo run -- uninstall` does not nuke their dev build.
    match binary_path() {
        None => {
            println!(
                "vibestats: {} not set — skipping binary deletion",
                if cfg!(windows) {
                    "LOCALAPPDATA"
                } else {
                    "HOME"
                }
            );
        }
        Some(path) => match std::fs::remove_file(&path) {
            Ok(()) => println!("vibestats: deleted binary at {}", path.display()),
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                println!(
                    "vibestats: binary not found at {} (already removed?)",
                    path.display()
                );
            }
            Err(e) => {
                #[cfg(windows)]
                {
                    // The running exe's image file is locked on Windows; this
                    // is the expected path there, not just an error case.
                    match schedule_binary_delete_on_reboot(&path) {
                        Ok(()) => {
                            println!(
                                "vibestats: binary at {} is in use and will be removed on next reboot",
                                path.display()
                            );
                        }
                        Err(_) => {
                            println!(
                                "vibestats: could not delete binary at {}: {e}",
                                path.display()
                            );
                            println!(
                                "Delete it manually: Remove-Item -Force \"{}\"",
                                path.display()
                            );
                        }
                    }
                }
                #[cfg(not(windows))]
                {
                    println!(
                        "vibestats: could not delete binary at {}: {e}",
                        path.display()
                    );
                    println!("Delete it manually: rm \"{}\"", path.display());
                }
            }
        },
    }

    // Step 3: Print manual cleanup instructions
    println!();
    println!("vibestats: uninstall complete.");
    println!();
    println!("Optional manual cleanup (not done automatically):");
    println!("  1. Delete your vibestats-data repo if you no longer want the data:");
    println!("       gh repo delete <username>/vibestats-data --yes");
    println!("  2. Remove the heatmap markers from your profile README:");
    println!("       Delete the lines between <!-- vibestats-start --> and <!-- vibestats-end -->");
    println!("  3. Remove vibestats config and logs:");
    println!(
        "       {}",
        if cfg!(windows) {
            r#"Remove-Item -Recurse -Force "$env:LOCALAPPDATA\vibestats""#
        } else {
            "rm -rf ~/.config/vibestats"
        }
    );
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    /// Combined test for settings_path() under varying HOME state.
    /// Mutating env vars is process-global, so both branches are exercised
    /// serially inside one test to avoid races with parallel test execution.
    #[test]

    fn settings_path_reflects_home_state() {
        #[cfg(windows)]
        const ENV_NAME: &str = "USERPROFILE";

        #[cfg(not(windows))]
        const ENV_NAME: &str = "HOME";

        let saved = std::env::var(ENV_NAME).ok();

        #[cfg(windows)]
        unsafe {
            std::env::set_var(ENV_NAME, r"C:\Users\Test");
        }

        #[cfg(not(windows))]
        unsafe {
            std::env::set_var(ENV_NAME, "/tmp/vibestats-test-home");
        }

        let path = settings_path().expect("must return Some when profile env var is set");
        assert_eq!(
            path.file_name(),
            Some(std::ffi::OsStr::new("settings.json"))
        );
        assert_eq!(
            path.parent().and_then(|p| p.file_name()),
            Some(std::ffi::OsStr::new(".claude"))
        );

        unsafe {
            std::env::remove_var(ENV_NAME);
        }

        assert!(
            settings_path().is_none(),
            "settings_path must return None when {ENV_NAME} is unset"
        );

        if let Some(value) = saved {
            unsafe {
                std::env::set_var(ENV_NAME, value);
            }
        }
    }

    #[test]

    fn binary_path_builds_local_bin_path() {
        #[cfg(windows)]
        {
            let saved = std::env::var("LOCALAPPDATA").ok();

            unsafe {
                std::env::set_var("LOCALAPPDATA", r"C:\Users\Test\AppData\Local");
            }

            let path = binary_path().expect("must return Some when LOCALAPPDATA is set");
            assert_eq!(
                path.file_name(),
                Some(std::ffi::OsStr::new("vibestats.exe"))
            );
            assert_eq!(
                path.parent().and_then(|p| p.file_name()),
                Some(std::ffi::OsStr::new("vibestats"))
            );
            assert_eq!(
                path.parent()
                    .and_then(|p| p.parent())
                    .and_then(|p| p.file_name()),
                Some(std::ffi::OsStr::new("Programs"))
            );

            if let Some(value) = saved {
                unsafe {
                    std::env::set_var("LOCALAPPDATA", value);
                }
            } else {
                unsafe {
                    std::env::remove_var("LOCALAPPDATA");
                }
            }
        }

        #[cfg(not(windows))]
        {
            let saved = std::env::var("HOME").ok();

            unsafe {
                std::env::set_var("HOME", "/tmp/vibestats-test-home");
            }

            let path = binary_path().expect("must return Some when HOME is set");
            assert_eq!(path.file_name(), Some(std::ffi::OsStr::new("vibestats")));
            assert_eq!(
                path.parent().and_then(|p| p.file_name()),
                Some(std::ffi::OsStr::new("bin"))
            );
            assert_eq!(
                path.parent()
                    .and_then(|p| p.parent())
                    .and_then(|p| p.file_name()),
                Some(std::ffi::OsStr::new(".local"))
            );

            if let Some(value) = saved {
                unsafe {
                    std::env::set_var("HOME", value);
                }
            } else {
                unsafe {
                    std::env::remove_var("HOME");
                }
            }
        }
    }

    #[test]
    fn is_vibestats_hook_matches_legacy_and_full_path_commands() {
        assert!(is_vibestats_hook(&json!({ "command": "vibestats" })));
        assert!(is_vibestats_hook(&json!({ "command": "vibestats sync" })));
        assert!(is_vibestats_hook(
            &json!({ "command": "vibestats session-start" })
        ));

        assert!(is_vibestats_hook(
            &json!({ "command": r#""C:\Users\Test\AppData\Local\Programs\vibestats\vibestats.exe" sync"# })
        ));
        assert!(is_vibestats_hook(
            &json!({ "command": r#""C:\Users\Test\AppData\Local\Programs\vibestats\VIBESTATS.EXE" sync --quiet"# })
        ));
        assert!(is_vibestats_hook(
            &json!({ "command": "/home/test/.local/bin/vibestats sync" })
        ));

        // False positives the old `.contains()` implementation would have matched:
        assert!(!is_vibestats_hook(
            &json!({ "command": "my-tool --arg vibestats-fake" })
        ));
        assert!(!is_vibestats_hook(
            &json!({ "command": "vibestats-killer" })
        ));
        assert!(!is_vibestats_hook(
            &json!({ "command": r#""C:\Tools\vibestats-helper.exe" sync"# })
        ));
        assert!(!is_vibestats_hook(
            &json!({ "command": r#"python "C:\Tools\vibestats.exe" sync"# })
        ));
        assert!(!is_vibestats_hook(&json!({ "command": "not-vibestats" })));

        // Missing / non-string command:
        assert!(!is_vibestats_hook(&json!({})));
        assert!(!is_vibestats_hook(&json!({ "command": 42 })));
    }

    #[test]
    fn hook_filtering_removes_vibestats_commands() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [
                        { "type": "command", "command": "vibestats sync", "async": true },
                        { "type": "command", "command": "other-tool run" }
                    ]
                }]
            }
        });

        let changed = remove_vibestats_hooks(&mut settings);
        assert!(changed, "must report changed=true when hooks removed");

        let stop_hooks = &settings["hooks"]["Stop"][0]["hooks"];
        let arr = stop_hooks.as_array().expect("must be array");
        assert_eq!(arr.len(), 1, "only non-vibestats hook should remain");
        assert_eq!(arr[0]["command"], "other-tool run");
    }

    #[test]
    fn hook_filtering_preserves_non_vibestats_hooks() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [
                        { "type": "command", "command": "my-tool --do-thing" }
                    ]
                }],
                "SessionStart": [{
                    "hooks": [
                        { "type": "command", "command": "another-tool start" }
                    ]
                }]
            },
            "other_setting": "should remain"
        });

        let changed = remove_vibestats_hooks(&mut settings);
        assert!(
            !changed,
            "must report changed=false when nothing vibestats-related is found"
        );

        // Non-vibestats hooks must be preserved
        let stop_hooks = &settings["hooks"]["Stop"][0]["hooks"];
        assert_eq!(
            stop_hooks.as_array().unwrap().len(),
            1,
            "non-vibestats Stop hook must remain"
        );
        let session_hooks = &settings["hooks"]["SessionStart"][0]["hooks"];
        assert_eq!(
            session_hooks.as_array().unwrap().len(),
            1,
            "non-vibestats SessionStart hook must remain"
        );
        // Other top-level settings preserved
        assert_eq!(settings["other_setting"], "should remain");
    }

    #[test]
    fn hook_filtering_handles_missing_hook_keys_gracefully() {
        // No "hooks" key at all
        let mut settings = json!({ "some_other_key": 42 });
        let changed = remove_vibestats_hooks(&mut settings);
        assert!(!changed);
        assert_eq!(settings["some_other_key"], 42);
    }

    #[test]
    fn hook_filtering_removes_group_when_all_hooks_are_vibestats() {
        let mut settings = json!({
            "hooks": {
                "Stop": [
                    {
                        "hooks": [
                            { "type": "command", "command": "vibestats sync", "async": true }
                        ]
                    },
                    {
                        "hooks": [
                            { "type": "command", "command": "other-tool" }
                        ]
                    }
                ]
            }
        });

        let changed = remove_vibestats_hooks(&mut settings);
        assert!(changed);

        let stop_groups = settings["hooks"]["Stop"].as_array().expect("must be array");
        assert_eq!(
            stop_groups.len(),
            1,
            "empty vibestats group should be removed; only other-tool group remains"
        );
        assert_eq!(stop_groups[0]["hooks"][0]["command"], "other-tool");
    }

    #[test]
    fn hook_filtering_preserves_unknown_hook_types() {
        // Settings has PreToolUse which vibestats never writes — must be untouched.
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [{
                    "hooks": [{ "type": "command", "command": "some-tool" }]
                }]
            }
        });

        let changed = remove_vibestats_hooks(&mut settings);
        assert!(!changed);

        let pre_hooks = &settings["hooks"]["PreToolUse"][0]["hooks"];
        assert_eq!(
            pre_hooks.as_array().unwrap().len(),
            1,
            "unknown hook type must be preserved"
        );
    }

    #[test]
    fn hook_filtering_strips_empty_hook_type_and_hooks_key_when_only_vibestats_present() {
        let mut settings = json!({
            "hooks": {
                "Stop": [{
                    "hooks": [
                        { "type": "command", "command": "vibestats sync", "async": true }
                    ]
                }],
                "SessionStart": [{
                    "hooks": [
                        { "type": "command", "command": "vibestats session-start" }
                    ]
                }]
            },
            "model": "sonnet"
        });

        let changed = remove_vibestats_hooks(&mut settings);
        assert!(changed, "must report changed=true");

        // hooks object must be gone entirely (it was only vibestats).
        assert!(
            settings.get("hooks").is_none(),
            "top-level hooks key must be removed when empty"
        );
        // Unrelated top-level settings must be preserved.
        assert_eq!(settings["model"], "sonnet");
    }

    #[test]
    fn hook_filtering_does_not_touch_non_stop_sessionstart_types_even_if_vibestats_command() {
        // Spec scope: removal is limited to Stop/SessionStart. A vibestats command
        // placed under an unexpected hook type must be preserved (out of scope).
        let mut settings = json!({
            "hooks": {
                "PreToolUse": [{
                    "hooks": [
                        { "type": "command", "command": "vibestats weird-hook" }
                    ]
                }]
            }
        });

        let changed = remove_vibestats_hooks(&mut settings);
        assert!(
            !changed,
            "must not touch hook types outside Stop/SessionStart"
        );
        assert_eq!(
            settings["hooks"]["PreToolUse"][0]["hooks"][0]["command"],
            "vibestats weird-hook"
        );
    }

    // ── first_command_token and command_executable_basename ──────────────────

    #[test]
    fn first_command_token_extracts_plain_command() {
        assert_eq!(first_command_token("vibestats sync"), Some("vibestats"));
        assert_eq!(first_command_token("vibestats"), Some("vibestats"));
        assert_eq!(first_command_token("my-tool --flag arg"), Some("my-tool"));
    }

    #[test]
    fn first_command_token_handles_quoted_path() {
        assert_eq!(
            first_command_token(r#""C:\Users\x\vibestats.exe" sync"#),
            Some(r"C:\Users\x\vibestats.exe")
        );
        assert_eq!(
            first_command_token(r#""C:\Program Files\app\tool.exe" --flag"#),
            Some(r"C:\Program Files\app\tool.exe")
        );
    }

    #[test]
    fn first_command_token_returns_none_for_unterminated_quote() {
        assert_eq!(first_command_token(r#""C:\foo"#), None);
        assert_eq!(first_command_token(r#""unterminated"#), None);
    }

    #[test]
    fn first_command_token_handles_leading_whitespace() {
        assert_eq!(first_command_token("   vibestats"), Some("vibestats"));
        assert_eq!(first_command_token("  \t  other-cmd"), Some("other-cmd"));
    }

    #[test]
    fn first_command_token_returns_none_for_empty_or_whitespace() {
        assert_eq!(first_command_token(""), None);
        assert_eq!(first_command_token("   "), None);
        assert_eq!(first_command_token("\t\n"), None);
    }

    #[test]
    fn command_executable_basename_extracts_from_plain_command() {
        assert_eq!(
            command_executable_basename("vibestats sync"),
            Some("vibestats")
        );
        assert_eq!(
            command_executable_basename("my-tool --arg"),
            Some("my-tool")
        );
    }

    #[test]
    fn command_executable_basename_extracts_from_windows_path() {
        assert_eq!(
            command_executable_basename(
                r#""C:\Users\Test\AppData\Local\Programs\vibestats\vibestats.exe" sync"#
            ),
            Some("vibestats.exe")
        );
        assert_eq!(
            command_executable_basename(r#""C:\Program Files\App\tool.exe" --flag"#),
            Some("tool.exe")
        );
    }

    #[test]
    fn command_executable_basename_extracts_from_unix_path() {
        assert_eq!(
            command_executable_basename("/home/test/.local/bin/vibestats sync"),
            Some("vibestats")
        );
        assert_eq!(
            command_executable_basename("/usr/local/bin/my-tool --arg"),
            Some("my-tool")
        );
    }

    #[test]
    fn command_executable_basename_handles_mixed_separators() {
        // Windows paths can have backslashes; Unix paths use forward slashes
        assert_eq!(
            command_executable_basename(r"C:\tools\vibestats.exe"),
            Some("vibestats.exe")
        );
        assert_eq!(command_executable_basename("/path/to/app"), Some("app"));
    }

    #[test]
    fn command_executable_basename_returns_none_for_unterminated_quote() {
        assert_eq!(command_executable_basename(r#""C:\foo"#), None);
    }

    #[test]
    fn command_executable_basename_returns_none_for_empty_or_whitespace() {
        assert_eq!(command_executable_basename(""), None);
        assert_eq!(command_executable_basename("   "), None);
    }
}