sidekick 0.7.0

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
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
//! `sidekick doctor --fix` — consent-gated repair of doctor findings.
//!
//! Every fix is shown as a diff before anything is written; nothing touches
//! disk until the user presses `y`. Once answered, the card collapses to a
//! single-line result and the next one opens. When stdout is not a terminal
//! the plan is printed and nothing is applied — consent can't be given
//! non-interactively.

use std::io::{self, IsTerminal, Write};
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use similar::{ChangeTag, TextDiff};
use toml_edit::{DocumentMut, table, value};

use crate::doctor::{self, Theme, display_path};

/// The opencode plugin, baked in so `--fix` needs no repo checkout or network.
/// Also the reference the doctor compares an installed plugin against.
pub(crate) const OPENCODE_PLUGIN_SRC: &str = include_str!("../plugins/opencode/sidekick.ts");

/// The pi extension, baked in so `--fix` needs no repo checkout or network.
/// Also the reference the doctor compares an installed extension against.
pub(crate) const PI_EXTENSION_SRC: &str = include_str!("../plugins/pi/sidekick.ts");
pub(crate) const CODEX_PLUGIN_SRC: &str =
    include_str!("../plugins/codex/.codex-plugin/plugin.json");
pub(crate) const CODEX_HOOKS_SRC: &str = include_str!("../plugins/codex/hooks.json");

/// One file edit inside a repair.
pub(crate) struct FileFix {
    pub(crate) path: PathBuf,
    /// `None` when the file does not exist yet.
    pub(crate) before: Option<String>,
    pub(crate) after: String,
}

/// A repair, which may touch one file or a small group of related files.
///
/// Shared with `sidekick init` — both commands write config the same way,
/// they only present it differently.
pub(crate) struct Fix {
    pub(crate) title: String,
    pub(crate) files: Vec<FileFix>,
}

impl Fix {
    fn single(
        title: impl Into<String>,
        path: PathBuf,
        before: Option<String>,
        after: String,
    ) -> Self {
        Self {
            title: title.into(),
            files: vec![FileFix {
                path,
                before,
                after,
            }],
        }
    }

    pub(crate) fn verb(&self) -> &'static str {
        let mut has_create = false;
        let mut has_update = false;
        for file in &self.files {
            if file.before.is_some() {
                has_update = true;
            } else {
                has_create = true;
            }
        }
        match (has_create, has_update) {
            (true, false) => "create",
            (false, true) => "update",
            _ => "change",
        }
    }

    pub(crate) fn target_summary(&self) -> String {
        if self.files.len() == 1 {
            display_path(&self.files[0].path)
        } else {
            format!("{} files", self.files.len())
        }
    }

    pub(crate) fn apply(&self) -> Result<()> {
        for file in &self.files {
            if let Some(parent) = file.path.parent() {
                std::fs::create_dir_all(parent)
                    .with_context(|| format!("couldn't create {}", parent.display()))?;
            }
            std::fs::write(&file.path, &file.after)
                .with_context(|| format!("couldn't write {}", file.path.display()))?;
        }
        Ok(())
    }
}

/// Build the fix list — one entry per repairable doctor finding, no overlap.
fn collect() -> Vec<Fix> {
    let mut fixes = Vec::new();
    fixes.extend(claude_fix());
    fixes.extend(codex_fixes());
    fixes.extend(opencode_fix());
    fixes.extend(pi_fix());
    fixes.extend(alias_fix());
    fixes
}

pub(crate) fn opencode_fix() -> Option<Fix> {
    if !doctor::uses_opencode() {
        return None;
    }
    // Update a plugin that's already there (stale install), else create one
    // at the canonical path.
    let canonical = dirs::home_dir()?
        .join(".config")
        .join("opencode")
        .join("plugin")
        .join("sidekick.ts");
    let path = doctor::opencode_plugin_files()
        .into_iter()
        .next()
        .unwrap_or(canonical);
    let before = std::fs::read_to_string(&path).ok();
    if before.as_deref() == Some(OPENCODE_PLUGIN_SRC) {
        return None;
    }
    let title = if before.is_some() {
        "Update the opencode plugin"
    } else {
        "Install the opencode plugin"
    };
    Some(Fix::single(
        title,
        path,
        before,
        OPENCODE_PLUGIN_SRC.to_string(),
    ))
}

pub(crate) fn pi_fix() -> Option<Fix> {
    if !doctor::uses_pi() {
        return None;
    }
    // Update an extension that's already there (stale install), else create
    // one at the canonical path.
    let canonical = dirs::home_dir()?
        .join(".pi")
        .join("agent")
        .join("extensions")
        .join("sidekick.ts");
    let path = doctor::pi_extension_files()
        .into_iter()
        .next()
        .unwrap_or(canonical);
    let before = std::fs::read_to_string(&path).ok();
    if before.as_deref() == Some(PI_EXTENSION_SRC) {
        return None;
    }
    let title = if before.is_some() {
        "Update the pi extension"
    } else {
        "Install the pi extension"
    };
    Some(Fix::single(
        title,
        path,
        before,
        PI_EXTENSION_SRC.to_string(),
    ))
}

pub(crate) fn codex_fixes() -> Vec<Fix> {
    if !doctor::uses_codex() || doctor::codex_hook_is_configured() {
        return Vec::new();
    }

    codex_fixes_for(dirs::home_dir().as_deref(), &doctor::codex_home())
}

fn codex_fixes_for(home: Option<&Path>, codex_home: &Path) -> Vec<Fix> {
    let mut files = Vec::new();

    if let Some(home) = home {
        // Codex personal marketplace entries use `./plugins/<name>` to mean
        // `~/plugins/<name>`, not a path relative to ~/.agents/plugins.
        let source_root = home.join("plugins").join("sidekick");
        push_file_fix(
            &mut files,
            "Install the Codex plugin manifest",
            source_root.join(".codex-plugin").join("plugin.json"),
            CODEX_PLUGIN_SRC,
        );
        push_file_fix(
            &mut files,
            "Install the Codex hook config",
            source_root.join("hooks.json"),
            CODEX_HOOKS_SRC,
        );

        let marketplace_path = home
            .join(".agents")
            .join("plugins")
            .join("marketplace.json");
        let before = std::fs::read_to_string(&marketplace_path).ok();
        if let Ok(after) = codex_marketplace_after(before.as_deref())
            && before.as_deref() != Some(after.as_str())
        {
            files.push(FileFix {
                path: marketplace_path,
                before,
                after,
            });
        }
    }

    let cache_root = codex_home
        .join("plugins")
        .join("cache")
        .join("personal")
        .join("sidekick")
        .join(env!("CARGO_PKG_VERSION"));
    push_file_fix(
        &mut files,
        "Cache the Codex plugin manifest",
        cache_root.join(".codex-plugin").join("plugin.json"),
        CODEX_PLUGIN_SRC,
    );
    push_file_fix(
        &mut files,
        "Cache the Codex hook config",
        cache_root.join("hooks.json"),
        CODEX_HOOKS_SRC,
    );

    let config_path = codex_home.join("config.toml");
    let before = std::fs::read_to_string(&config_path).ok();
    if let Ok(after) = codex_config_after(before.as_deref())
        && before.as_deref() != Some(after.as_str())
    {
        files.push(FileFix {
            path: config_path,
            before,
            after,
        });
    }

    if files.is_empty() {
        Vec::new()
    } else {
        vec![Fix {
            title: "Install and enable the Codex plugin".into(),
            files,
        }]
    }
}

fn push_file_fix(files: &mut Vec<FileFix>, _title: &str, path: PathBuf, after: &str) {
    let before = std::fs::read_to_string(&path).ok();
    if before.as_deref() == Some(after) {
        return;
    }
    files.push(FileFix {
        path,
        before,
        after: after.to_string(),
    });
}

pub(crate) fn claude_fix() -> Option<Fix> {
    if !doctor::uses_claude_code() || !doctor::claude_hook_files().is_empty() {
        return None;
    }
    let path = dirs::home_dir()?.join(".claude").join("settings.json");
    let before = std::fs::read_to_string(&path).ok();
    let after = claude_settings_after(before.as_deref()).ok()?;
    Some(Fix::single(
        "Register the Claude Code hooks",
        path,
        before,
        after,
    ))
}

pub(crate) fn alias_fix() -> Option<Fix> {
    const ALIAS: &str = "alias nvim='sidekick neovim'";
    // Use the doctor's runtime verdict so we never re-offer a live alias,
    // even when it lives in a file other than the one we'd append to.
    if doctor::nvim_alias_status() != doctor::AliasStatus::Missing {
        return None;
    }
    let path = shell_rc_path()?;
    let before = std::fs::read_to_string(&path).ok();
    if before.as_deref().is_some_and(|c| c.contains(ALIAS)) {
        return None;
    }
    let mut after = before.clone().unwrap_or_default();
    if !after.is_empty() && !after.ends_with('\n') {
        after.push('\n');
    }
    after.push_str("\n# sidekick\n");
    after.push_str(ALIAS);
    after.push('\n');
    Some(Fix::single(
        "Add the nvim → sidekick alias",
        path,
        before,
        after,
    ))
}

/// Merge sidekick's three hooks into a Claude Code `settings.json`, leaving
/// every other key — and the user's key order — untouched.
fn claude_settings_after(before: Option<&str>) -> Result<String> {
    let mut root: serde_json::Value = match before {
        Some(s) if !s.trim().is_empty() => {
            serde_json::from_str(s).context("~/.claude/settings.json isn't valid JSON")?
        }
        _ => serde_json::json!({}),
    };
    {
        let obj = root
            .as_object_mut()
            .context("~/.claude/settings.json isn't a JSON object")?;
        let hooks = obj
            .entry("hooks")
            .or_insert_with(|| serde_json::json!({}))
            .as_object_mut()
            .context("`hooks` in settings.json isn't an object")?;
        for (event, matcher) in [
            ("PreToolUse", "Edit|Write|MultiEdit"),
            ("PostToolUse", "Edit|Write|MultiEdit"),
            ("UserPromptSubmit", ""),
        ] {
            let arr = hooks
                .entry(event)
                .or_insert_with(|| serde_json::json!([]))
                .as_array_mut()
                .with_context(|| format!("`hooks.{event}` in settings.json isn't an array"))?;
            arr.push(serde_json::json!({
                "matcher": matcher,
                "hooks": [{ "type": "command", "command": "sidekick hook" }],
            }));
        }
    }
    let mut s = serde_json::to_string_pretty(&root)?;
    s.push('\n');
    Ok(s)
}

fn codex_config_after(before: Option<&str>) -> Result<String> {
    let mut doc = match before {
        Some(s) if !s.trim().is_empty() => s
            .parse::<DocumentMut>()
            .context("~/.codex/config.toml isn't valid TOML")?,
        _ => DocumentMut::new(),
    };

    doc["features"].or_insert(table());
    doc["features"]["plugin_hooks"] = value(true);
    doc["plugins"].or_insert(table());
    doc["plugins"]["sidekick@personal"].or_insert(table());
    doc["plugins"]["sidekick@personal"]["enabled"] = value(true);

    // Codex silently drops untrusted plugin hooks at discovery time, so we
    // stamp the same `trusted_hash` Codex's interactive TUI would write. The
    // hashes are derived from a stable canonicalization of our hooks.json
    // entries — see `codex_trust`.
    doc["hooks"].or_insert(table());
    doc["hooks"]["state"].or_insert(table());
    let state = doc["hooks"]["state"]
        .as_table_mut()
        .context("`hooks.state` in ~/.codex/config.toml isn't a table")?;
    for entry in crate::codex_trust::expected_trust_entries() {
        state.entry(&entry.key).or_insert(table());
        let item = state
            .get_mut(&entry.key)
            .and_then(|item| item.as_table_mut())
            .with_context(|| {
                format!(
                    "`hooks.state.\"{}\"` in ~/.codex/config.toml isn't a table",
                    entry.key
                )
            })?;
        item["trusted_hash"] = value(entry.trusted_hash);
    }

    let mut out = doc.to_string();
    if !out.ends_with('\n') {
        out.push('\n');
    }
    Ok(out)
}

fn codex_marketplace_after(before: Option<&str>) -> Result<String> {
    let mut root: serde_json::Value = match before {
        Some(s) if !s.trim().is_empty() => serde_json::from_str(s)
            .context("~/.agents/plugins/marketplace.json isn't valid JSON")?,
        _ => serde_json::json!({
            "name": "personal",
            "interface": { "displayName": "Personal" },
            "plugins": []
        }),
    };

    let obj = root
        .as_object_mut()
        .context("~/.agents/plugins/marketplace.json isn't a JSON object")?;
    obj.entry("name")
        .or_insert_with(|| serde_json::json!("personal"));
    obj.entry("interface").or_insert_with(|| {
        serde_json::json!({
            "displayName": "Personal"
        })
    });
    let plugins = obj
        .entry("plugins")
        .or_insert_with(|| serde_json::json!([]))
        .as_array_mut()
        .context("`plugins` in marketplace.json isn't an array")?;

    let sidekick_entry = serde_json::json!({
        "name": "sidekick",
        "source": {
            "source": "local",
            "path": "./plugins/sidekick"
        },
        "policy": {
            "installation": "AVAILABLE",
            "authentication": "ON_INSTALL"
        },
        "category": "Productivity"
    });

    if let Some(existing) = plugins
        .iter_mut()
        .find(|p| p.get("name").and_then(|n| n.as_str()) == Some("sidekick"))
    {
        *existing = sidekick_entry;
    } else {
        plugins.push(sidekick_entry);
    }

    let mut s = serde_json::to_string_pretty(&root)?;
    s.push('\n');
    Ok(s)
}

/// The rc file the user's login shell sources, mirroring `scripts/install.sh`.
fn shell_rc_path() -> Option<PathBuf> {
    let shell = std::env::var("SHELL").ok()?;
    let name = Path::new(&shell).file_name()?.to_str()?;
    let home = dirs::home_dir()?;
    Some(match name {
        "zsh" => home.join(".zshrc"),
        "bash" => {
            let profile = home.join(".bash_profile");
            if cfg!(target_os = "macos") && profile.exists() {
                profile
            } else {
                home.join(".bashrc")
            }
        }
        "fish" => home.join(".config").join("fish").join("config.fish"),
        _ => home.join(".profile"),
    })
}

pub fn run(no_color: bool, any_failed: bool) -> Result<()> {
    let theme = Theme::new(!no_color);
    let fixes = collect();
    let mut out = io::stdout();

    if fixes.is_empty() {
        let msg = if any_failed {
            "Nothing here can be fixed automatically — see the report above."
        } else {
            "Nothing to fix — sidekick is fully wired up."
        };
        writeln!(out, "\n  {}\n", theme.dim(msg))?;
        return Ok(());
    }

    if !io::stdout().is_terminal() {
        return print_plan(&theme, &fixes);
    }

    writeln!(out, "\n  {}", theme.bold("sidekick · fix"))?;

    let total = fixes.len();
    let mut applied = 0usize;
    let mut skipped = 0usize;
    let mut reviewed = 0usize;

    for (i, fix) in fixes.iter().enumerate() {
        let card = card_lines(&theme, fix, i + 1, total);
        for line in &card {
            writeln!(out, "{line}")?;
        }
        write!(
            out,
            "  {}   {}   {} ",
            theme.bold("Apply?"),
            theme.dim("[y] yes    [n] skip    [q] quit"),
            theme.cyan(""),
        )?;
        out.flush()?;

        let (answer, prompt_lines) = ask(&theme)?;
        collapse(&mut out, card.len() + prompt_lines)?;
        reviewed += 1;

        let resolved = match answer {
            Answer::Yes => match fix.apply() {
                Ok(()) => {
                    applied += 1;
                    format!("  {} {}", theme.green(""), fix.title)
                }
                Err(e) => {
                    reviewed -= 1;
                    format!(
                        "  {} {} {}",
                        theme.red(""),
                        fix.title,
                        theme.dim(&format!("{e}")),
                    )
                }
            },
            Answer::No => {
                skipped += 1;
                format!("  {} {}", theme.dim("·"), theme.dim(&fix.title))
            }
            Answer::Quit => {
                reviewed -= 1;
                writeln!(out, "  {} {}", theme.dim(""), theme.dim(&fix.title))?;
                break;
            }
        };
        writeln!(out, "{resolved}")?;
    }

    write!(out, "\n  ")?;
    let mut parts = Vec::new();
    if applied > 0 {
        parts.push(format!("{applied} applied"));
    }
    if skipped > 0 {
        parts.push(format!("{skipped} skipped"));
    }
    if reviewed < total {
        parts.push(format!("{} left", total - reviewed));
    }
    writeln!(out, "{}", theme.dim(&parts.join(" · ")))?;
    if applied > 0 {
        writeln!(out, "  {}", theme.dim("Run `sidekick doctor` to confirm."))?;
    }
    writeln!(out)?;
    Ok(())
}

/// Non-interactive fallback: describe the fixes, apply nothing.
fn print_plan(theme: &Theme, fixes: &[Fix]) -> Result<()> {
    let mut out = io::stdout();
    writeln!(out, "\n  {}\n", theme.bold("sidekick · fix"))?;
    writeln!(
        out,
        "  {}",
        theme.dim("Run this in a terminal to review and apply:"),
    )?;
    for fix in fixes {
        writeln!(
            out,
            "    {} {}  {}",
            theme.dim("·"),
            fix.title,
            theme.dim(&fix.target_summary()),
        )?;
    }
    writeln!(out)?;
    Ok(())
}

enum Answer {
    Yes,
    No,
    Quit,
}

/// Read a y/n/q answer. Returns how many terminal lines the prompt occupied
/// (one per attempt) so the caller can erase the exact region on collapse.
fn ask(theme: &Theme) -> io::Result<(Answer, usize)> {
    let mut prompt_lines = 1usize;
    loop {
        let mut line = String::new();
        if io::stdin().read_line(&mut line)? == 0 {
            return Ok((Answer::Quit, prompt_lines));
        }
        match line.trim().to_ascii_lowercase().as_str() {
            "y" | "yes" => return Ok((Answer::Yes, prompt_lines)),
            "" | "n" | "no" => return Ok((Answer::No, prompt_lines)),
            "q" | "quit" => return Ok((Answer::Quit, prompt_lines)),
            _ => {
                print!("  {} ", theme.dim("answer y, n, or q  ›"));
                io::stdout().flush()?;
                prompt_lines += 1;
            }
        }
    }
}

/// Move the cursor to the top of the just-drawn region and clear it, so the
/// caller can replace a whole consent card with a one-line result.
fn collapse(out: &mut impl Write, lines: usize) -> io::Result<()> {
    if lines > 0 {
        write!(out, "\x1b[{lines}A")?;
    }
    write!(out, "\r\x1b[J")
}

fn card_lines(theme: &Theme, fix: &Fix, idx: usize, total: usize) -> Vec<String> {
    let mut out = Vec::new();
    out.push(String::new());

    let head = format!("──  fix {idx} of {total}  ");
    let pad = 60usize.saturating_sub(head.chars().count());
    out.push(format!(
        "  {}",
        theme.dim(&format!("{head}{}", "".repeat(pad)))
    ));
    out.push(String::new());

    out.push(format!("  {}", theme.bold(&fix.title)));
    if fix.files.len() == 1 {
        out.push(format!(
            "    {}   {}",
            theme.dim(fix.verb()),
            theme.dim(&display_path(&fix.files[0].path)),
        ));
    } else {
        out.push(format!(
            "    {}   {}",
            theme.dim(fix.verb()),
            theme.dim(&fix.target_summary()),
        ));
        for file in &fix.files {
            let verb = if file.before.is_some() {
                "update"
            } else {
                "create"
            };
            out.push(format!(
                "      {}   {}",
                theme.dim(verb),
                theme.dim(&display_path(&file.path)),
            ));
        }
    }
    out.push(String::new());

    out.extend(render_diff_lines(theme, fix));
    out.push(String::new());
    out
}

/// The diff body for a fix — context and add/remove rows, big diffs truncated.
/// Shared with `sidekick init`, which shows it on demand behind `[d]`.
pub(crate) fn render_diff_lines(theme: &Theme, fix: &Fix) -> Vec<String> {
    let mut out = Vec::new();
    for (idx, file) in fix.files.iter().enumerate() {
        if fix.files.len() > 1 {
            if idx > 0 {
                out.push(format!("    {} {}", theme.dim(""), theme.dim("")));
            }
            out.push(format!(
                "    {} {}",
                theme.dim(""),
                theme.dim(&display_path(&file.path))
            ));
        }
        out.extend(
            truncate_diff(diff_rows(file.before.as_deref().unwrap_or(""), &file.after))
                .iter()
                .map(|row| render_diff_row(theme, row)),
        );
    }
    out
}

enum DiffMark {
    Add,
    Del,
    Ctx,
    Gap,
}

struct DiffRow {
    mark: DiffMark,
    text: String,
}

/// Unified diff with three lines of context around each change.
fn diff_rows(before: &str, after: &str) -> Vec<DiffRow> {
    let diff = TextDiff::from_lines(before, after);
    let mut rows = Vec::new();
    for (group_idx, group) in diff.grouped_ops(3).iter().enumerate() {
        if group_idx > 0 {
            rows.push(DiffRow {
                mark: DiffMark::Gap,
                text: String::new(),
            });
        }
        for op in group {
            for change in diff.iter_changes(op) {
                let mark = match change.tag() {
                    ChangeTag::Insert => DiffMark::Add,
                    ChangeTag::Delete => DiffMark::Del,
                    ChangeTag::Equal => DiffMark::Ctx,
                };
                rows.push(DiffRow {
                    mark,
                    text: change.value().trim_end_matches(['\r', '\n']).to_string(),
                });
            }
        }
    }
    rows
}

/// Keep big diffs (a freshly created plugin file) readable: head, tail, and a
/// `⋮ N more lines` marker for everything in between.
fn truncate_diff(mut rows: Vec<DiffRow>) -> Vec<DiffRow> {
    const HEAD: usize = 16;
    const TAIL: usize = 3;
    if rows.len() <= HEAD + TAIL + 1 {
        return rows;
    }
    let hidden = rows.len() - HEAD - TAIL;
    let tail = rows.split_off(rows.len() - TAIL);
    rows.truncate(HEAD);
    rows.push(DiffRow {
        mark: DiffMark::Gap,
        text: format!("{hidden} more lines"),
    });
    rows.extend(tail);
    rows
}

fn render_diff_row(theme: &Theme, row: &DiffRow) -> String {
    let gutter = theme.dim("");
    match row.mark {
        DiffMark::Add => format!(
            "    {gutter} {}",
            theme.green(&format!("+ {}", truncate_text(&row.text))),
        ),
        DiffMark::Del => format!(
            "    {gutter} {}",
            theme.red(&format!("- {}", truncate_text(&row.text))),
        ),
        DiffMark::Ctx => format!(
            "    {gutter} {}",
            theme.dim(&format!("  {}", truncate_text(&row.text))),
        ),
        DiffMark::Gap => {
            let body = if row.text.is_empty() {
                "".to_string()
            } else {
                format!("{}", row.text)
            };
            format!("    {gutter} {}", theme.dim(&body))
        }
    }
}

fn truncate_text(s: &str) -> String {
    const MAX: usize = 84;
    if s.chars().count() > MAX {
        let kept: String = s.chars().take(MAX - 1).collect();
        format!("{kept}")
    } else {
        s.to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::{
        claude_settings_after, codex_config_after, codex_fixes_for, codex_marketplace_after,
    };

    #[test]
    fn merges_three_hooks_into_empty_settings() {
        let out = claude_settings_after(None).unwrap();
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        let hooks = &v["hooks"];
        for event in ["PreToolUse", "PostToolUse", "UserPromptSubmit"] {
            let arr = hooks[event].as_array().unwrap();
            assert_eq!(arr.len(), 1);
            assert_eq!(arr[0]["hooks"][0]["command"], "sidekick hook");
        }
        assert_eq!(hooks["PreToolUse"][0]["matcher"], "Edit|Write|MultiEdit");
        assert_eq!(hooks["UserPromptSubmit"][0]["matcher"], "");
    }

    #[test]
    fn keeps_existing_keys_order_and_hooks() {
        let before = r#"{"model":"opus","hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[]}]}}"#;
        let out = claude_settings_after(Some(before)).unwrap();
        // preserve_order keeps `model` ahead of `hooks` rather than sorting.
        assert!(out.find("\"model\"").unwrap() < out.find("\"hooks\"").unwrap());

        let v: serde_json::Value = serde_json::from_str(&out).unwrap();
        assert_eq!(v["model"], "opus");
        let pre = v["hooks"]["PreToolUse"].as_array().unwrap();
        assert_eq!(pre.len(), 2);
        assert_eq!(pre[0]["matcher"], "Bash");
        assert_eq!(pre[1]["hooks"][0]["command"], "sidekick hook");
    }

    #[test]
    fn rejects_invalid_json() {
        assert!(claude_settings_after(Some("{ not json")).is_err());
    }

    #[test]
    fn enables_codex_plugin_hooks_in_empty_config() {
        let out = codex_config_after(None).unwrap();

        assert!(out.contains("[features]"));
        assert!(out.contains("plugin_hooks = true"));
        assert!(out.contains("[plugins.\"sidekick@personal\"]"));
        assert!(out.contains("enabled = true"));

        // Codex drops untrusted plugin hooks at discovery; the fix has to
        // stamp the trust entries too, or the install is silently inert.
        for entry in crate::codex_trust::expected_trust_entries() {
            assert!(
                out.contains(&format!("[hooks.state.\"{}\"]", entry.key)),
                "missing [hooks.state.\"{}\"] in:\n{out}",
                entry.key,
            );
            assert!(
                out.contains(&format!("trusted_hash = \"{}\"", entry.trusted_hash)),
                "missing trusted_hash for {} in:\n{out}",
                entry.key,
            );
        }
    }

    #[test]
    fn preserves_existing_codex_config() {
        let before = r#"model = "gpt-5.5"

[features]
other = true
"#;
        let out = codex_config_after(Some(before)).unwrap();

        assert!(out.contains("model = \"gpt-5.5\""));
        assert!(out.contains("other = true"));
        assert!(out.contains("plugin_hooks = true"));
    }

    #[test]
    fn merges_codex_personal_marketplace_entry() {
        let before = r#"{"name":"personal","interface":{"displayName":"Mine"},"plugins":[]}"#;
        let out = codex_marketplace_after(Some(before)).unwrap();
        let v: serde_json::Value = serde_json::from_str(&out).unwrap();

        assert_eq!(v["interface"]["displayName"], "Mine");
        assert_eq!(v["plugins"][0]["name"], "sidekick");
        assert_eq!(v["plugins"][0]["source"]["path"], "./plugins/sidekick");
    }

    #[test]
    fn codex_fixes_plans_personal_plugin_paths() {
        let root =
            std::env::temp_dir().join(format!("sidekick-codex-fixes-{}", std::process::id()));
        let home = root.join("home");
        let codex_home = root.join("codex");

        let fixes = codex_fixes_for(Some(&home), &codex_home);
        assert_eq!(fixes.len(), 1);
        assert_eq!(fixes[0].title, "Install and enable the Codex plugin");
        let paths = fixes[0]
            .files
            .iter()
            .map(|f| f.path.clone())
            .collect::<Vec<_>>();

        assert!(paths.contains(&home.join("plugins/sidekick/.codex-plugin/plugin.json")));
        assert!(paths.contains(&home.join("plugins/sidekick/hooks.json")));
        assert!(paths.contains(&home.join(".agents/plugins/marketplace.json")));
        assert!(paths.contains(&codex_home.join("config.toml")));
        assert!(paths.contains(&codex_home.join(format!(
            "plugins/cache/personal/sidekick/{}/.codex-plugin/plugin.json",
            env!("CARGO_PKG_VERSION")
        ))));

        let _ = std::fs::remove_dir_all(root);
    }
}