paddington 0.6.0

A fast status line and cost tracker for Claude Code and Pi
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
//! `paddington setup` — configure Claude Code and Pi to use paddington.
//!
//! Embeds the Pi extension at compile time, manages symlinks into Pi agent
//! profiles, and merges statusLine config into Claude Code's settings.json.

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

use crate::config::{GREEN, RED, RESET, YELLOW};

/// The Pi extension source, embedded at compile time.
const EMBEDDED_EXTENSION: &str = include_str!("../contrib/pi/paddington.ts");

/// Version stamp prepended to the managed extension file.
const VERSION_HEADER: &str = concat!(
    "// paddington v",
    env!("CARGO_PKG_VERSION"),
    " — managed by `paddington setup`, do not edit\n"
);

// ── Path helpers ──────────────────────────────────────────────────────

fn home_dir() -> Option<PathBuf> {
    std::env::var("HOME")
        .ok()
        .map(PathBuf::from)
}

/// Replace a leading `$HOME` prefix with `~` for portability.
fn tildefy(path: &Path) -> String {
    if let Some(home) = home_dir()
        && let Ok(rest) = path.strip_prefix(&home) {
            return format!("~/{}", rest.display());
        }
    path.display().to_string()
}

/// Resolve the paddington binary path for the statusLine command.
/// Uses `current_exe()` and replaces `$HOME` with `~`.
fn resolve_binary_path() -> String {
    std::env::current_exe()
        .ok()
        .and_then(|p| fs::canonicalize(p).ok())
        .map(|p| tildefy(&p))
        .unwrap_or_else(|| "~/.cargo/bin/paddington".into())
}

fn claude_settings_path() -> Option<PathBuf> {
    home_dir().map(|h| h.join(".claude").join("settings.json"))
}

fn pi_base_dir() -> Option<PathBuf> {
    home_dir().map(|h| h.join(".pi"))
}

fn managed_extension_dir() -> Option<PathBuf> {
    let data_dir = std::env::var("XDG_DATA_HOME")
        .ok()
        .map(PathBuf::from)
        .or_else(|| home_dir().map(|h| h.join(".local").join("share")));
    data_dir.map(|d| d.join("paddington").join("extensions"))
}

fn config_toml_path() -> PathBuf {
    PathBuf::from(crate::config::config_path())
}

// ── Prompt helpers ────────────────────────────────────────────────────

fn confirm(prompt: &str, force: bool) -> bool {
    if force {
        return true;
    }
    if !io::stdin().is_terminal() {
        // Non-interactive — default to no, require --force
        return false;
    }
    eprint!("{prompt} [y/N] ");
    io::stderr().flush().ok();
    let mut answer = String::new();
    if io::stdin().read_line(&mut answer).is_err() {
        return false;
    }
    matches!(answer.trim(), "y" | "Y" | "yes" | "YES")
}

// ── Claude Code setup ─────────────────────────────────────────────────

fn setup_claude(force: bool, uninstall: bool) {
    let Some(path) = claude_settings_path() else {
        println!("Claude Code: {RED}{RESET} could not determine home directory");
        return;
    };

    if !path.parent().is_some_and(|p| p.exists()) {
        println!("Claude Code: {RED}{RESET} ~/.claude/ not found, skipping");
        return;
    }

    if uninstall {
        uninstall_claude(&path);
        return;
    }

    // Read existing settings or start fresh
    let mut settings: serde_json::Value = if path.exists() {
        match fs::read_to_string(&path) {
            Ok(content) => match serde_json::from_str(&content) {
                Ok(v) => v,
                Err(e) => {
                    println!(
                        "Claude Code: {RED}{RESET} malformed settings.json: {e}"
                    );
                    return;
                }
            },
            Err(e) => {
                println!("Claude Code: {RED}{RESET} could not read settings.json: {e}");
                return;
            }
        }
    } else {
        serde_json::json!({})
    };

    // Check for existing statusLine
    if settings.get("statusLine").is_some() && !force {
        let existing = serde_json::to_string_pretty(settings.get("statusLine").unwrap())
            .unwrap_or_default();
        eprintln!("Claude Code: existing statusLine:\n{existing}");
        if !confirm("Overwrite?", false) {
            println!(
                "Claude Code: · already configured (use --force to overwrite)"
            );
            return;
        }
    }

    let binary_path = resolve_binary_path();
    settings["statusLine"] = serde_json::json!({
        "type": "command",
        "command": binary_path,
        "padding": 3
    });

    match write_json_file(&path, &settings) {
        Ok(()) => println!(
            "Claude Code: {GREEN}{RESET} configured ({})",
            tildefy(&path)
        ),
        Err(e) => println!("Claude Code: {RED}{RESET} failed to write: {e}"),
    }
}

fn uninstall_claude(path: &Path) {
    if !path.exists() {
        println!("Claude Code: · nothing to remove");
        return;
    }

    let content = match fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            println!("Claude Code: {RED}{RESET} could not read settings.json: {e}");
            return;
        }
    };

    let mut settings: serde_json::Value = match serde_json::from_str(&content) {
        Ok(v) => v,
        Err(e) => {
            println!("Claude Code: {RED}{RESET} malformed settings.json: {e}");
            return;
        }
    };

    if let Some(obj) = settings.as_object_mut() {
        if obj.remove("statusLine").is_some() {
            match write_json_file(path, &settings) {
                Ok(()) => println!(
                    "Claude Code: {GREEN}{RESET} statusLine removed from {}",
                    tildefy(path)
                ),
                Err(e) => println!("Claude Code: {RED}{RESET} failed to write: {e}"),
            }
        } else {
            println!("Claude Code: · no statusLine key found, nothing to remove");
        }
    }
}

fn write_json_file(path: &Path, value: &serde_json::Value) -> io::Result<()> {
    let json = serde_json::to_string_pretty(value)
        .map_err(io::Error::other)?;
    // Ensure trailing newline
    let json = if json.ends_with('\n') {
        json
    } else {
        format!("{json}\n")
    };
    fs::write(path, json)
}

// ── Pi setup ──────────────────────────────────────────────────────────

/// Discover Pi agent profiles by scanning `~/.pi/*/` for directories
/// that contain an `extensions/` subdirectory or other Pi markers
/// (e.g. `npm/`, `sessions/`).
fn discover_pi_profiles(pi_dir: &Path) -> Vec<String> {
    let mut profiles = Vec::new();
    let entries = match fs::read_dir(pi_dir) {
        Ok(e) => e,
        Err(_) => return profiles,
    };

    let markers = ["extensions", "npm", "sessions"];
    for entry in entries.flatten() {
        if !entry.file_type().is_ok_and(|ft| ft.is_dir()) {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        // Skip hidden dirs and non-agent dirs
        if name.starts_with('.') {
            continue;
        }
        let dir = entry.path();
        let has_marker = markers.iter().any(|m| dir.join(m).is_dir());
        if has_marker {
            profiles.push(name);
        }
    }

    profiles.sort();
    profiles
}

fn setup_pi(profile: Option<&str>, force: bool, uninstall: bool) {
    let Some(pi_dir) = pi_base_dir() else {
        println!("Pi:          {RED}{RESET} could not determine home directory");
        return;
    };

    if !pi_dir.exists() {
        println!("Pi:          {RED}{RESET} ~/.pi/ not found, skipping");
        return;
    }

    // Determine which profiles to configure
    let profiles: Vec<String> = if let Some(name) = profile {
        let profile_dir = pi_dir.join(name);
        if !profile_dir.exists() {
            println!(
                "Pi:          {RED}{RESET} profile '{name}' not found at {}",
                tildefy(&profile_dir)
            );
            return;
        }
        vec![name.to_string()]
    } else {
        let discovered = discover_pi_profiles(&pi_dir);
        if discovered.is_empty() {
            println!("Pi:          {YELLOW}·{RESET} no agent profiles found in ~/.pi/");
            return;
        }
        discovered
    };

    if uninstall {
        uninstall_pi(&pi_dir, &profiles);
        return;
    }

    // Write the managed extension file
    let Some(managed_dir) = managed_extension_dir() else {
        println!("Pi:          {RED}{RESET} could not determine data directory");
        return;
    };

    if let Err(e) = fs::create_dir_all(&managed_dir) {
        println!("Pi:          {RED}{RESET} could not create {}: {e}", tildefy(&managed_dir));
        return;
    }

    let managed_file = managed_dir.join("paddington.ts");
    let content = format!("{VERSION_HEADER}{EMBEDDED_EXTENSION}");
    if let Err(e) = fs::write(&managed_file, &content) {
        println!("Pi:          {RED}{RESET} could not write {}: {e}", tildefy(&managed_file));
        return;
    }

    // Create symlinks for each profile
    let mut any_installed = false;
    for profile_name in &profiles {
        let ext_dir = pi_dir.join(profile_name).join("extensions");
        if let Err(e) = fs::create_dir_all(&ext_dir) {
            println!(
                "Pi ({profile_name}): {RED}{RESET} could not create extensions dir: {e}"
            );
            continue;
        }

        let symlink_path = ext_dir.join("paddington.ts");
        let result = install_symlink(&symlink_path, &managed_file, profile_name, force);
        match result {
            SymlinkResult::Created | SymlinkResult::Replaced => {
                println!(
                    "Pi ({profile_name}): {GREEN}{RESET} extension installed (symlink → {})",
                    tildefy(&managed_file)
                );
                any_installed = true;
            }
            SymlinkResult::AlreadyCurrent => {
                println!(
                    "Pi ({profile_name}): {YELLOW}·{RESET} already configured"
                );
                any_installed = true;
            }
            SymlinkResult::Skipped => {
                println!(
                    "Pi ({profile_name}): {YELLOW}·{RESET} skipped (use --force to overwrite)"
                );
            }
            SymlinkResult::Error(e) => {
                println!("Pi ({profile_name}): {RED}{RESET} {e}");
            }
        }
    }

    if !any_installed && profiles.len() == 1 {
        // Single profile was skipped — don't print extra noise
    }
}

enum SymlinkResult {
    Created,
    Replaced,
    AlreadyCurrent,
    Skipped,
    Error(String),
}

fn install_symlink(
    symlink_path: &Path,
    managed_file: &Path,
    profile_name: &str,
    force: bool,
) -> SymlinkResult {
    // Check existing symlink state
    match fs::read_link(symlink_path) {
        Ok(target) => {
            // Symlink exists — check where it points
            if target == managed_file {
                return SymlinkResult::AlreadyCurrent;
            }

            // Dangling symlink (target deleted) — remove and recreate
            if !target.exists() {
                let _ = fs::remove_file(symlink_path);
                return match std::os::unix::fs::symlink(managed_file, symlink_path) {
                    Ok(()) => SymlinkResult::Created,
                    Err(e) => SymlinkResult::Error(format!("could not create symlink: {e}")),
                };
            }

            // Points elsewhere (dotfiles, old install, etc.)
            let target_display = tildefy(&target);
            eprintln!(
                "Pi ({profile_name}): paddington.ts → {target_display}"
            );
            if !confirm(
                "                    Overwrite with managed symlink?",
                force,
            ) {
                return SymlinkResult::Skipped;
            }

            // Remove old symlink and create new one
            if let Err(e) = fs::remove_file(symlink_path) {
                return SymlinkResult::Error(format!("could not remove old symlink: {e}"));
            }
            match std::os::unix::fs::symlink(managed_file, symlink_path) {
                Ok(()) => SymlinkResult::Replaced,
                Err(e) => SymlinkResult::Error(format!("could not create symlink: {e}")),
            }
        }
        Err(e) if e.kind() == io::ErrorKind::NotFound => {
            // No symlink — but check for a regular file
            if symlink_path.exists() {
                eprintln!(
                    "Pi ({profile_name}): paddington.ts exists as a regular file"
                );
                if !confirm(
                    "                    Replace with managed symlink?",
                    force,
                ) {
                    return SymlinkResult::Skipped;
                }
                if let Err(e) = fs::remove_file(symlink_path) {
                    return SymlinkResult::Error(format!("could not remove file: {e}"));
                }
            }
            match std::os::unix::fs::symlink(managed_file, symlink_path) {
                Ok(()) => SymlinkResult::Created,
                Err(e) => SymlinkResult::Error(format!("could not create symlink: {e}")),
            }
        }
        Err(_) => {
            // Dangling symlink or other error — remove and recreate
            let _ = fs::remove_file(symlink_path);
            match std::os::unix::fs::symlink(managed_file, symlink_path) {
                Ok(()) => SymlinkResult::Created,
                Err(e) => SymlinkResult::Error(format!("could not create symlink: {e}")),
            }
        }
    }
}

fn uninstall_pi(pi_dir: &Path, profiles: &[String]) {
    let mut removed_any = false;

    for profile_name in profiles {
        let symlink_path = pi_dir
            .join(profile_name)
            .join("extensions")
            .join("paddington.ts");

        // Use read_link to detect symlinks (including dangling)
        match fs::read_link(&symlink_path) {
            Ok(_) => {
                if let Err(e) = fs::remove_file(&symlink_path) {
                    println!(
                        "Pi ({profile_name}): {RED}{RESET} could not remove symlink: {e}"
                    );
                } else {
                    println!(
                        "Pi ({profile_name}): {GREEN}{RESET} extension removed"
                    );
                    removed_any = true;
                }
            }
            Err(_) => {
                // Check if it's a regular file (manually copied)
                if symlink_path.exists() {
                    if let Err(e) = fs::remove_file(&symlink_path) {
                        println!(
                            "Pi ({profile_name}): {RED}{RESET} could not remove file: {e}"
                        );
                    } else {
                        println!(
                            "Pi ({profile_name}): {GREEN}{RESET} extension removed"
                        );
                        removed_any = true;
                    }
                } else {
                    println!(
                        "Pi ({profile_name}): {YELLOW}·{RESET} no extension found"
                    );
                }
            }
        }
    }

    // Remove managed file only if all symlinks are gone
    if removed_any
        && let Some(managed_dir) = managed_extension_dir() {
            let managed_file = managed_dir.join("paddington.ts");
            if managed_file.exists() {
                let _ = fs::remove_file(&managed_file);
            }
        }
}

// ── Config setup ──────────────────────────────────────────────────────

fn setup_config() {
    let path = config_toml_path();

    if path.exists() {
        println!(
            "Config:      {YELLOW}·{RESET} already exists, not modified ({})",
            tildefy(&path)
        );
        return;
    }

    // Create parent directory
    if let Some(parent) = path.parent()
        && let Err(e) = fs::create_dir_all(parent) {
            println!("Config:      {RED}{RESET} could not create directory: {e}");
            return;
        }

    let default_config = "\
# Paddington status line configuration
# See: https://github.com/cebarks/paddington

# [budget]
# monthly_limit = 200.0

# [format]
# template = \"...\"   # Uses built-in default template when omitted
";

    match fs::write(&path, default_config) {
        Ok(()) => println!(
            "Config:      {GREEN}{RESET} created ({})",
            tildefy(&path)
        ),
        Err(e) => println!("Config:      {RED}{RESET} could not write: {e}"),
    }
}

// ── Public entry point ────────────────────────────────────────────────

pub fn run_setup(
    claude: bool,
    pi: bool,
    profile: Option<String>,
    force: bool,
    uninstall: bool,
) {
    let do_claude = !pi || claude;  // both when neither flag is set
    let do_pi = !claude || pi;

    if do_claude {
        if uninstall {
            setup_claude(force, true);
        } else {
            setup_claude(force, false);
        }
    }

    if do_pi {
        setup_pi(profile.as_deref(), force, uninstall);
    }

    // Config is only created on install (not uninstall)
    if !uninstall {
        setup_config();
    }

    if !uninstall {
        println!();
        println!("Restart your coding agent to activate.");
    }
}

// ── Tests ─────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use std::os::unix::fs::symlink;

    fn make_tmpdir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir()
            .join("paddington-setup-test")
            .join(name);
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    #[test]
    fn tildefy_replaces_home() {
        if let Some(home) = home_dir() {
            let path = home.join("foo").join("bar");
            assert_eq!(tildefy(&path), "~/foo/bar");
        }
    }

    #[test]
    fn tildefy_leaves_non_home_paths() {
        let path = PathBuf::from("/usr/bin/paddington");
        assert_eq!(tildefy(&path), "/usr/bin/paddington");
    }

    #[test]
    fn version_header_contains_version() {
        assert!(VERSION_HEADER.contains(env!("CARGO_PKG_VERSION")));
        assert!(VERSION_HEADER.starts_with("// paddington v"));
    }

    #[test]
    fn embedded_extension_is_nonempty() {
        assert!(!EMBEDDED_EXTENSION.is_empty());
        assert!(EMBEDDED_EXTENSION.contains("ExtensionContext"));
    }

    #[test]
    fn discover_profiles_finds_agent_dirs() {
        let dir = make_tmpdir("discover-profiles");

        // Create profiles with markers
        fs::create_dir_all(dir.join("agent").join("extensions")).unwrap();
        fs::create_dir_all(dir.join("agent-prodsec").join("npm")).unwrap();
        // Hidden dir should be skipped
        fs::create_dir_all(dir.join(".internal").join("extensions")).unwrap();
        // Dir without markers should be skipped
        fs::create_dir_all(dir.join("random-dir")).unwrap();

        let profiles = discover_pi_profiles(&dir);
        assert_eq!(profiles, vec!["agent", "agent-prodsec"]);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn discover_profiles_empty_dir() {
        let dir = make_tmpdir("discover-empty");
        let profiles = discover_pi_profiles(&dir);
        assert!(profiles.is_empty());
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_symlink_creates_new() {
        let dir = make_tmpdir("symlink-create");
        let target = dir.join("managed.ts");
        fs::write(&target, "content").unwrap();
        let link = dir.join("paddington.ts");

        let result = install_symlink(&link, &target, "test", false);
        assert!(matches!(result, SymlinkResult::Created));
        assert_eq!(fs::read_link(&link).unwrap(), target);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_symlink_already_current() {
        let dir = make_tmpdir("symlink-current");
        let target = dir.join("managed.ts");
        fs::write(&target, "content").unwrap();
        let link = dir.join("paddington.ts");
        symlink(&target, &link).unwrap();

        let result = install_symlink(&link, &target, "test", false);
        assert!(matches!(result, SymlinkResult::AlreadyCurrent));

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_symlink_dangling_recreates() {
        let dir = make_tmpdir("symlink-dangling");
        let target = dir.join("managed.ts");
        fs::write(&target, "content").unwrap();
        let old_target = dir.join("deleted.ts");
        let link = dir.join("paddington.ts");
        symlink(&old_target, &link).unwrap(); // dangling

        let result = install_symlink(&link, &target, "test", false);
        assert!(matches!(result, SymlinkResult::Created));
        assert_eq!(fs::read_link(&link).unwrap(), target);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_symlink_force_replaces() {
        let dir = make_tmpdir("symlink-force");
        let target = dir.join("managed.ts");
        fs::write(&target, "content").unwrap();
        let old_target = dir.join("dotfiles.ts");
        fs::write(&old_target, "old").unwrap();
        let link = dir.join("paddington.ts");
        symlink(&old_target, &link).unwrap();

        let result = install_symlink(&link, &target, "test", true);
        assert!(matches!(result, SymlinkResult::Replaced));
        assert_eq!(fs::read_link(&link).unwrap(), target);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn install_symlink_regular_file_force_replaces() {
        let dir = make_tmpdir("symlink-file-force");
        let target = dir.join("managed.ts");
        fs::write(&target, "content").unwrap();
        let link = dir.join("paddington.ts");
        fs::write(&link, "manual copy").unwrap(); // regular file, not symlink

        let result = install_symlink(&link, &target, "test", true);
        assert!(matches!(result, SymlinkResult::Created));
        assert_eq!(fs::read_link(&link).unwrap(), target);

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn write_json_preserves_order() {
        let json = r#"{"zebra": 1, "alpha": 2, "middle": 3}"#;
        let value: serde_json::Value = serde_json::from_str(json).unwrap();

        let output = serde_json::to_string_pretty(&value).unwrap();
        // With preserve_order, zebra should still come first
        let zebra_pos = output.find("zebra").unwrap();
        let alpha_pos = output.find("alpha").unwrap();
        assert!(zebra_pos < alpha_pos, "preserve_order should maintain insertion order");
    }

    #[test]
    fn claude_settings_merge_preserves_keys() {
        let dir = make_tmpdir("claude-merge");
        let settings_path = dir.join("settings.json");
        let original = serde_json::json!({
            "env": {"key": "val"},
            "model": "claude-sonnet-4-20250514"
        });
        write_json_file(&settings_path, &original).unwrap();

        // Re-read and add statusLine
        let content = fs::read_to_string(&settings_path).unwrap();
        let mut settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        settings["statusLine"] = serde_json::json!({
            "type": "command",
            "command": "~/.cargo/bin/paddington",
            "padding": 3
        });
        write_json_file(&settings_path, &settings).unwrap();

        // Verify all keys present
        let result: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        assert!(result.get("env").is_some());
        assert!(result.get("model").is_some());
        assert!(result.get("statusLine").is_some());

        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn claude_settings_uninstall_removes_key() {
        let dir = make_tmpdir("claude-uninstall");
        let settings_path = dir.join("settings.json");
        let original = serde_json::json!({
            "model": "claude-sonnet-4-20250514",
            "statusLine": {"type": "command", "command": "paddington"}
        });
        write_json_file(&settings_path, &original).unwrap();

        // Simulate uninstall
        let content = fs::read_to_string(&settings_path).unwrap();
        let mut settings: serde_json::Value = serde_json::from_str(&content).unwrap();
        if let Some(obj) = settings.as_object_mut() {
            obj.remove("statusLine");
        }
        write_json_file(&settings_path, &settings).unwrap();

        let result: serde_json::Value =
            serde_json::from_str(&fs::read_to_string(&settings_path).unwrap()).unwrap();
        assert!(result.get("model").is_some());
        assert!(result.get("statusLine").is_none());

        let _ = fs::remove_dir_all(&dir);
    }
}