sidekick 0.6.1

Protects your unsaved Neovim work from Claude Code.
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
//! `sidekick doctor` — diagnose a sidekick install.
//!
//! On a terminal, checks animate: every row prints up front with a spinner,
//! and they resolve one at a time. The first failure halts the cascade and
//! the remaining rows render as skipped. When stdout is not a terminal we
//! just run everything sequentially and print the final block.

use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::thread;
use std::time::Duration;

use chrono::{DateTime, Utc};

use crate::analytics::event::{Decision, Event, ToolKind};
use crate::analytics::store;
use crate::utils;

pub(crate) const SPINNER_FRAMES: &[&str] = &["", "", "", "", "", "", "", "", "", ""];
const FRAMES_PER_CHECK: u32 = 3;
const FRAME_DELAY: Duration = Duration::from_millis(70);

// Brand accents (truecolor ANSI params) for the AI-integration rows, applied
// to the label only when that integration is configured correctly.
pub(crate) const CLAUDE_ACCENT: &str = "38;2;217;119;87"; // #D97757
pub(crate) const OPENCODE_ACCENT: &str = "38;2;91;155;213"; // #5B9BD5
pub(crate) const PI_ACCENT: &str = "38;2;157;124;216"; // #9D7CD8

enum Status {
    Pass,
    Fail { remedy: Vec<String> },
    Info,
}

struct Check {
    label: String,
    detail: Option<String>,
    status: Status,
}

struct Row {
    pending_label: &'static str,
    run: fn() -> Check,
    result: Option<Check>,
    skipped: bool,
    /// Truecolor ANSI params for the label, applied only when the check passes.
    accent: Option<&'static str>,
    /// A prerequisite failure halts the cascade; other failures don't.
    prerequisite: bool,
}

impl Row {
    fn is_failed(&self) -> bool {
        matches!(
            self.result,
            Some(Check {
                status: Status::Fail { .. },
                ..
            })
        )
    }

    /// A failed prerequisite (e.g. missing `nvim`) makes the rest moot, so the
    /// remaining rows are skipped. A failed integration check does not.
    fn halts_cascade(&self) -> bool {
        self.prerequisite && self.is_failed()
    }
}

/// Runs every check and renders the report. Returns whether anything failed —
/// the caller owns the exit code, so `--fix` can run before the process ends.
pub fn run(no_color: bool, fix: bool) -> anyhow::Result<bool> {
    let theme = Theme::new(!no_color);
    let mut rows = build_rows();

    if io::stdout().is_terminal() {
        animate(&theme, &mut rows)?;
    } else {
        run_static(&mut rows);
        let mut stdout = io::stdout().lock();
        render_block_to(&mut stdout, &theme, &rows, 0)?;
    }

    let any_failed = rows.iter().any(Row::is_failed);

    // When something's wrong, point at --fix — unless --fix is already running.
    if any_failed && !fix {
        let mut stdout = io::stdout().lock();
        writeln!(
            stdout,
            "  {}sidekick doctor --fix{}",
            theme.dim("Run "),
            theme.dim(" to fix the issues above.")
        )?;
        writeln!(stdout)?;
    }

    Ok(any_failed)
}

fn row(
    pending_label: &'static str,
    run: fn() -> Check,
    accent: Option<&'static str>,
    prerequisite: bool,
) -> Row {
    Row {
        pending_label,
        run,
        result: None,
        skipped: false,
        accent,
        prerequisite,
    }
}

/// The discovery step runs first; the per-harness rows below it are built only
/// for the AI harnesses actually present, so an absent harness gets no row.
fn build_rows() -> Vec<Row> {
    let mut rows = vec![
        row("sidekick version", check_version, None, false),
        row("nvim on PATH", check_nvim_on_path, None, true),
        row("AI harnesses", check_harnesses, None, false),
    ];

    if uses_claude_code() {
        rows.push(row(
            "Claude Code hook registered",
            check_claude_hook,
            Some(CLAUDE_ACCENT),
            false,
        ));
    }
    if uses_opencode() {
        rows.push(row(
            "opencode plugin",
            check_opencode_plugin,
            Some(OPENCODE_ACCENT),
            false,
        ));
    }
    if uses_pi() {
        rows.push(row(
            "pi extension",
            check_pi_extension,
            Some(PI_ACCENT),
            false,
        ));
    }

    rows.push(row("nvim alias", check_shell_alias, None, false));
    rows.push(row(
        "Neovim sockets opened here",
        check_sockets,
        None,
        false,
    ));
    rows.push(row("last activity", check_last_hook, None, false));
    rows
}

fn animate(theme: &Theme, rows: &mut [Row]) -> io::Result<()> {
    let mut stdout = io::stdout().lock();
    let mut last_height = 0usize;
    let mut spin = 0usize;

    // Hide cursor while we redraw; restore on the way out (incl. failure path).
    write!(stdout, "\x1b[?25l")?;
    let result = animate_inner(&mut stdout, theme, rows, &mut last_height, &mut spin);
    write!(stdout, "\x1b[?25h")?;
    stdout.flush()?;
    result
}

fn animate_inner(
    stdout: &mut impl Write,
    theme: &Theme,
    rows: &mut [Row],
    last_height: &mut usize,
    spin: &mut usize,
) -> io::Result<()> {
    redraw(stdout, theme, rows, *spin, last_height)?;

    for i in 0..rows.len() {
        for _ in 0..FRAMES_PER_CHECK {
            *spin = spin.wrapping_add(1);
            thread::sleep(FRAME_DELAY);
            redraw(stdout, theme, rows, *spin, last_height)?;
        }

        rows[i].result = Some((rows[i].run)());

        if rows[i].halts_cascade() {
            for row in rows.iter_mut().skip(i + 1) {
                row.skipped = true;
            }
            redraw(stdout, theme, rows, *spin, last_height)?;
            return Ok(());
        }

        redraw(stdout, theme, rows, *spin, last_height)?;
    }
    Ok(())
}

fn redraw(
    w: &mut impl Write,
    theme: &Theme,
    rows: &[Row],
    spin: usize,
    last_height: &mut usize,
) -> io::Result<()> {
    if *last_height > 0 {
        write!(w, "\x1b[{}A\r", *last_height)?;
    }
    write!(w, "\x1b[J")?;
    *last_height = render_block_to(w, theme, rows, spin)?;
    w.flush()
}

fn run_static(rows: &mut [Row]) {
    let mut failed = false;
    for row in rows.iter_mut() {
        if failed {
            row.skipped = true;
            continue;
        }
        row.result = Some((row.run)());
        if row.halts_cascade() {
            failed = true;
        }
    }
}

fn render_block_to(
    w: &mut impl Write,
    theme: &Theme,
    rows: &[Row],
    spin: usize,
) -> io::Result<usize> {
    let mut height = 0;
    writeln!(w)?;
    height += 1;
    writeln!(w, "  {}", theme.bold("sidekick doctor"))?;
    height += 1;
    writeln!(w)?;
    height += 1;

    for row in rows {
        for line in render_row(theme, row, spin) {
            writeln!(w, "{line}")?;
            height += 1;
        }
    }

    writeln!(w)?;
    height += 1;
    Ok(height)
}

fn render_row(theme: &Theme, row: &Row, spin: usize) -> Vec<String> {
    if row.skipped {
        let marker = theme.dim("");
        let body = theme.dim(&format!("{} (skipped)", row.pending_label));
        return vec![format!("  {marker} {body}")];
    }

    match &row.result {
        None => {
            let marker = theme.cyan(SPINNER_FRAMES[spin % SPINNER_FRAMES.len()]);
            vec![format!("  {marker} {}", row.pending_label)]
        }
        Some(check) => {
            let marker = match &check.status {
                Status::Pass => theme.green(""),
                Status::Fail { .. } => theme.red(""),
                Status::Info => theme.dim("·"),
            };
            let label = match (&check.status, row.accent) {
                (Status::Pass, Some(code)) => theme.wrap(code, &check.label),
                _ => check.label.clone(),
            };
            let mut out = vec![format!("  {marker} {label}")];
            if let Some(detail) = &check.detail {
                for line in detail.lines() {
                    out.push(format!("      {}", theme.dim(line)));
                }
            }
            if let Status::Fail { remedy } = &check.status {
                for line in remedy {
                    out.push(format!("      {line}"));
                }
            }
            out
        }
    }
}

fn check_version() -> Check {
    let version = env!("CARGO_PKG_VERSION");
    let exe = std::env::current_exe()
        .ok()
        .map(|p| display_path(&p))
        .unwrap_or_else(|| "(unknown path)".to_string());
    Check {
        label: format!("sidekick v{version} on PATH"),
        detail: Some(exe),
        status: Status::Pass,
    }
}

fn check_nvim_on_path() -> Check {
    match Command::new("nvim").arg("--version").output() {
        Ok(out) if out.status.success() => {
            let first_line = String::from_utf8_lossy(&out.stdout)
                .lines()
                .next()
                .unwrap_or("nvim")
                .trim()
                .to_string();
            let label = if first_line.is_empty() {
                "nvim on PATH".to_string()
            } else {
                format!("{first_line} on PATH")
            };
            Check {
                label,
                detail: None,
                status: Status::Pass,
            }
        }
        _ => Check {
            label: "Neovim (`nvim`) not on PATH".into(),
            detail: None,
            status: Status::Fail {
                remedy: vec!["Install Neovim: https://neovim.io/".into()],
            },
        },
    }
}

/// Discover which AI harnesses are present. Drives both this row's summary and
/// (via the same `uses_*` checks) which per-harness rows get built at all.
fn check_harnesses() -> Check {
    let mut found: Vec<&str> = Vec::new();
    if uses_claude_code() {
        found.push("Claude Code");
    }
    if uses_opencode() {
        found.push("opencode");
    }
    if uses_pi() {
        found.push("pi");
    }

    if found.is_empty() {
        Check {
            label: "no AI harness found".into(),
            detail: None,
            status: Status::Fail {
                remedy: vec![
                    "Install Claude Code, opencode, or pi — sidekick has nothing to guard without one"
                        .into(),
                ],
            },
        }
    } else {
        Check {
            label: format!("AI harnesses: {}", found.join(", ")),
            detail: None,
            status: Status::Info,
        }
    }
}

/// Config files that already wire up `sidekick hook` for Claude Code.
pub(crate) fn claude_hook_files() -> Vec<PathBuf> {
    let mut matched: Vec<PathBuf> = Vec::new();

    let mut candidates: Vec<PathBuf> = Vec::new();
    if let Some(home) = dirs::home_dir() {
        candidates.push(home.join(".claude").join("settings.json"));
        candidates.push(home.join(".claude").join("settings.local.json"));
    }
    if let Ok(cwd) = std::env::current_dir() {
        candidates.push(cwd.join(".claude").join("settings.json"));
    }

    for path in &candidates {
        if file_mentions_sidekick_hook(path) {
            matched.push(path.clone());
        }
    }

    if let Some(home) = dirs::home_dir() {
        walk_for_json_mentioning_hook(&home.join(".claude").join("plugins"), &mut matched, 4);
    }

    matched.sort();
    matched.dedup();
    matched
}

fn check_claude_hook() -> Check {
    let matched = claude_hook_files();

    if !matched.is_empty() {
        let detail = matched
            .iter()
            .map(|p| display_path(p))
            .collect::<Vec<_>>()
            .join("\n");
        return Check {
            label: "Claude Code hook registered".into(),
            detail: Some(detail),
            status: Status::Pass,
        };
    }

    Check {
        label: "Claude Code hook not registered".into(),
        detail: None,
        status: Status::Fail {
            remedy: vec![
                "Install the plugin:  /plugin install sidekick@nishant-plugins".into(),
                "Or add `sidekick hook` to ~/.claude/settings.json".into(),
            ],
        },
    }
}

/// Plugin files that already wire up sidekick for opencode.
pub(crate) fn opencode_plugin_files() -> Vec<PathBuf> {
    let mut matched: Vec<PathBuf> = Vec::new();

    // opencode globs `{plugin,plugins}/*.{ts,js}` under its global config dir
    // (~/.config/opencode) and per-project (.opencode).
    let mut plugin_dirs: Vec<PathBuf> = Vec::new();
    if let Some(home) = dirs::home_dir() {
        plugin_dirs.push(home.join(".config").join("opencode"));
    }
    if let Ok(cwd) = std::env::current_dir() {
        plugin_dirs.push(cwd.join(".opencode"));
    }
    for base in &plugin_dirs {
        for dir in ["plugin", "plugins"] {
            for ext in ["ts", "js"] {
                let candidate = base.join(dir).join(format!("sidekick.{ext}"));
                if candidate.is_file() {
                    matched.push(candidate);
                }
            }
        }
    }

    matched.sort();
    matched.dedup();
    matched
}

fn check_opencode_plugin() -> Check {
    let matched = opencode_plugin_files();

    if matched.is_empty() {
        return Check {
            label: "opencode plugin not installed".into(),
            detail: None,
            status: Status::Fail {
                remedy: vec![
                    "Drop plugins/opencode/sidekick.ts into ~/.config/opencode/plugin/".into(),
                ],
            },
        };
    }

    let detail = matched
        .iter()
        .map(|p| display_path(p))
        .collect::<Vec<_>>()
        .join("\n");

    // Presence isn't enough — a stale or hand-edited plugin is missing fixes.
    // The binary embeds the canonical plugin, so compare byte-for-byte.
    let all_current = matched.iter().all(|p| {
        std::fs::read_to_string(p).ok().as_deref() == Some(crate::fix::OPENCODE_PLUGIN_SRC)
    });

    if all_current {
        Check {
            label: "opencode plugin installed".into(),
            detail: Some(detail),
            status: Status::Pass,
        }
    } else {
        Check {
            label: "opencode plugin out of sync".into(),
            detail: Some(detail),
            status: Status::Fail {
                remedy: vec!["The installed plugin differs from this sidekick build.".into()],
            },
        }
    }
}

/// Extension files that already wire up sidekick for the pi coding agent.
pub(crate) fn pi_extension_files() -> Vec<PathBuf> {
    let mut matched: Vec<PathBuf> = Vec::new();

    // pi loads `extensions/*.{ts,js}` from its global agent config dir
    // (~/.pi/agent) and per-project (.pi).
    let mut extension_dirs: Vec<PathBuf> = Vec::new();
    if let Some(home) = dirs::home_dir() {
        extension_dirs.push(home.join(".pi").join("agent").join("extensions"));
    }
    if let Ok(cwd) = std::env::current_dir() {
        extension_dirs.push(cwd.join(".pi").join("extensions"));
    }
    for dir in &extension_dirs {
        for ext in ["ts", "js"] {
            let candidate = dir.join(format!("sidekick.{ext}"));
            if candidate.is_file() {
                matched.push(candidate);
            }
        }
    }

    matched.sort();
    matched.dedup();
    matched
}

fn check_pi_extension() -> Check {
    let matched = pi_extension_files();

    if matched.is_empty() {
        return Check {
            label: "pi extension not installed".into(),
            detail: None,
            status: Status::Fail {
                remedy: vec!["Drop plugins/pi/sidekick.ts into ~/.pi/agent/extensions/".into()],
            },
        };
    }

    let detail = matched
        .iter()
        .map(|p| display_path(p))
        .collect::<Vec<_>>()
        .join("\n");

    // Presence isn't enough — a stale or hand-edited extension is missing
    // fixes. The binary embeds the canonical extension, so compare byte-for-byte.
    let all_current = matched
        .iter()
        .all(|p| std::fs::read_to_string(p).ok().as_deref() == Some(crate::fix::PI_EXTENSION_SRC));

    if all_current {
        Check {
            label: "pi extension installed".into(),
            detail: Some(detail),
            status: Status::Pass,
        }
    } else {
        Check {
            label: "pi extension out of sync".into(),
            detail: Some(detail),
            status: Status::Fail {
                remedy: vec!["The installed extension differs from this sidekick build.".into()],
            },
        }
    }
}

/// Whether an executable of this name is on `$PATH`.
fn binary_on_path(name: &str) -> bool {
    std::env::var_os("PATH")
        .map(|path| std::env::split_paths(&path).any(|dir| dir.join(name).is_file()))
        .unwrap_or(false)
}

/// Whether this machine looks like a Claude Code user.
pub(crate) fn uses_claude_code() -> bool {
    binary_on_path("claude")
        || dirs::home_dir()
            .map(|h| h.join(".claude").is_dir())
            .unwrap_or(false)
}

#[derive(PartialEq)]
pub(crate) enum AliasStatus {
    Active,
    Missing,
    Unknown,
}

/// Runtime check of whether `nvim` resolves to `sidekick neovim` in the login
/// shell — the same probe `check_shell_alias` renders, shared so `--fix` never
/// offers an alias that's already live.
pub(crate) fn nvim_alias_status() -> AliasStatus {
    let Ok(shell) = std::env::var("SHELL") else {
        return AliasStatus::Unknown;
    };
    match Command::new(&shell)
        .args(["-i", "-c", "type nvim"])
        .output()
    {
        Ok(out) => {
            if String::from_utf8_lossy(&out.stdout).contains("sidekick neovim") {
                AliasStatus::Active
            } else {
                AliasStatus::Missing
            }
        }
        Err(_) => AliasStatus::Unknown,
    }
}

/// Whether this machine looks like an opencode user.
pub(crate) fn uses_opencode() -> bool {
    binary_on_path("opencode")
        || dirs::home_dir()
            .map(|h| h.join(".config").join("opencode").is_dir())
            .unwrap_or(false)
}

/// Whether this machine looks like a pi coding agent user. The `~/.pi/agent`
/// directory is pi-specific; `pi` alone is a short name that could collide.
pub(crate) fn uses_pi() -> bool {
    binary_on_path("pi")
        || dirs::home_dir()
            .map(|h| h.join(".pi").join("agent").is_dir())
            .unwrap_or(false)
}

fn check_shell_alias() -> Check {
    let Ok(shell) = std::env::var("SHELL") else {
        return Check {
            label: "nvim alias: $SHELL is not set".into(),
            detail: None,
            status: Status::Info,
        };
    };

    let shell_name = Path::new(&shell)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("shell")
        .to_string();

    // `-i` makes the shell source the user's rc files (.zshrc, .bashrc, …)
    // so aliases defined there resolve. `type nvim` works in bash/zsh/fish.
    match Command::new(&shell)
        .args(["-i", "-c", "type nvim"])
        .output()
    {
        Ok(out) => {
            let stdout = String::from_utf8_lossy(&out.stdout);
            if stdout.contains("sidekick neovim") {
                Check {
                    label: format!("nvim alias: nvim → sidekick neovim ({shell_name})"),
                    detail: None,
                    status: Status::Pass,
                }
            } else {
                let current =
                    first_meaningful_line(&stdout).unwrap_or_else(|| "(no output)".to_string());
                Check {
                    label: format!("nvim alias not set ({shell_name})"),
                    detail: Some(format!("`type nvim` → {current}")),
                    status: Status::Fail {
                        remedy: vec![format!(
                            "Add to your {shell_name} config:  alias nvim='sidekick neovim'"
                        )],
                    },
                }
            }
        }
        Err(e) => Check {
            label: format!("nvim alias: couldn't run {shell_name}"),
            detail: Some(e.to_string()),
            status: Status::Info,
        },
    }
}

fn first_meaningful_line(s: &str) -> Option<String> {
    s.lines()
        .find(|l| !l.trim().is_empty())
        .map(|l| l.trim().to_string())
}

fn check_sockets() -> Check {
    match utils::find_matching_sockets() {
        Ok(sockets) if !sockets.is_empty() => {
            let count = sockets.len();
            let detail = sockets
                .iter()
                .map(|p| p.display().to_string())
                .collect::<Vec<_>>()
                .join("\n");
            Check {
                label: format!(
                    "{count} Neovim socket{} opened here",
                    if count == 1 { "" } else { "s" }
                ),
                detail: Some(detail),
                status: Status::Info,
            }
        }
        _ => Check {
            label: "no Neovim opened here".into(),
            detail: None,
            status: Status::Info,
        },
    }
}

fn check_last_hook() -> Check {
    let last = store::read_all()
        .unwrap_or_default()
        .into_iter()
        .filter_map(|e| match e {
            Event::HookDecision(d) => Some(d),
            _ => None,
        })
        .max_by_key(|d| d.at);

    match last {
        Some(d) => {
            let when = relative_time(d.at);
            let tool = match d.tool {
                ToolKind::Edit => "Edit",
                ToolKind::Write => "Write",
                ToolKind::MultiEdit => "MultiEdit",
            };
            let decision = match d.decision {
                Decision::Allow => "allowed",
                Decision::Deny => "blocked",
            };
            let file = Path::new(&d.file)
                .file_name()
                .map(|s| s.to_string_lossy().into_owned())
                .unwrap_or_else(|| d.file.clone());
            Check {
                label: format!("last activity: {when}"),
                detail: Some(format!("{decision} · {tool} · {file}")),
                status: Status::Info,
            }
        }
        None => Check {
            label: "last activity: never".into(),
            detail: Some("Ask Claude to edit a file to see one.".into()),
            status: Status::Info,
        },
    }
}

fn relative_time(at: DateTime<Utc>) -> String {
    let secs = Utc::now().signed_duration_since(at).num_seconds().max(0);
    if secs < 60 {
        format!("{secs}s ago")
    } else if secs < 3600 {
        format!("{}m ago", secs / 60)
    } else if secs < 86_400 {
        format!("{}h ago", secs / 3600)
    } else {
        format!("{}d ago", secs / 86_400)
    }
}

fn file_mentions_sidekick_hook(path: &Path) -> bool {
    std::fs::read_to_string(path)
        .map(|c| c.contains("sidekick hook"))
        .unwrap_or(false)
}

fn walk_for_json_mentioning_hook(dir: &Path, matched: &mut Vec<PathBuf>, depth: usize) {
    if depth == 0 {
        return;
    }
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let path = entry.path();
        if path.is_dir() {
            walk_for_json_mentioning_hook(&path, matched, depth - 1);
        } else if path.extension().and_then(|e| e.to_str()) == Some("json")
            && file_mentions_sidekick_hook(&path)
        {
            matched.push(path);
        }
    }
}

pub(crate) fn display_path(p: &Path) -> String {
    if let Some(home) = dirs::home_dir()
        && let Ok(rel) = p.strip_prefix(&home)
    {
        return format!("~/{}", rel.display());
    }
    p.display().to_string()
}

pub(crate) struct Theme {
    color: bool,
}

impl Theme {
    pub(crate) fn new(color: bool) -> Self {
        Self { color }
    }
    pub(crate) fn wrap(&self, code: &str, s: &str) -> String {
        if self.color {
            format!("\x1b[{code}m{s}\x1b[0m")
        } else {
            s.to_string()
        }
    }
    pub(crate) fn green(&self, s: &str) -> String {
        self.wrap("32", s)
    }
    pub(crate) fn red(&self, s: &str) -> String {
        self.wrap("31", s)
    }
    pub(crate) fn cyan(&self, s: &str) -> String {
        self.wrap("36", s)
    }
    pub(crate) fn dim(&self, s: &str) -> String {
        self.wrap("2", s)
    }
    pub(crate) fn bold(&self, s: &str) -> String {
        self.wrap("1", s)
    }
}