car-inference 0.49.0

Local model inference for CAR — Candle backend with Qwen3 models
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
//! `car uninstall` — remove a CAR install's own state, safely.
//!
//! Removes the contents of `~/.car` (config, state, logs, the installed
//! binaries, and the *managed-model symlinks*) so a reinstall starts clean and
//! no debris from this version is left behind. Two hard boundaries make it safe
//! to run without fear:
//!
//!   * **Never touches the shared HuggingFace cache** (`HF_HOME` /
//!     `~/.cache/huggingface`). Other tools use it, and CAR's managed models are
//!     symlinks *into* it — so removing `~/.car/models` drops the links, not the
//!     multi-GB shared blobs. The plan surfaces the cache path so the CLI can
//!     tell the user how to clear it themselves if they really want to.
//!   * **Can preserve `~/.car/env`** (the dotenv secrets file) on request, so an
//!     uninstall/reinstall cycle doesn't force re-entering API keys.
//!
//! OS-level schedules (launchd/cron) live *outside* `~/.car`; the CLI reaps them
//! via `car-scheduler` before calling [`execute`].
//!
//! On macOS `~/.car` is only half of an install. CarHost.app owns user-level
//! state elsewhere — its preferences domain (which carries the onboarding
//! sentinel), `Library/Application Support`, `Library/Caches`, and the TCC
//! grants (Accessibility, Screen Recording, Automation, …) the setup wizard
//! walked the user through. TCC rows are keyed by *bundle identifier* and
//! survive deleting the app, so a purge that stops at `~/.car` leaves a
//! reinstall looking pre-configured: the wizard's live probes report every
//! scope as already granted and skip the permission steps
//! (Parslee-ai/car-releases#85). [`plan_macos_host`] / [`execute_macos_host`]
//! own that second half, cfg-target-gated to macOS.

use std::path::{Path, PathBuf};

/// What an uninstall would remove and what it would leave alone — computed
/// before any deletion so the CLI can show it and ask for confirmation.
#[derive(Debug, Clone)]
pub struct UninstallPlan {
    /// The `~/.car` directory being removed.
    pub home: PathBuf,
    /// Top-level entries under `home` that will be deleted.
    pub remove: Vec<PathBuf>,
    /// Names deliberately kept (e.g. `env` under `--keep-secrets`).
    pub preserved: Vec<String>,
    /// The shared HuggingFace cache, left intact. `Some` only when it exists —
    /// surfaced purely so the CLI can print a "left alone; remove manually with…"
    /// note. Never deleted by [`execute`].
    pub shared_hf_cache: Option<PathBuf>,
}

impl UninstallPlan {
    /// True when there's nothing to remove (no install, or already clean).
    pub fn is_empty(&self) -> bool {
        self.remove.is_empty()
    }
}

/// Build the removal plan for `home`. Pure (reads the directory listing, deletes
/// nothing), so the CLI can render it for a dry-run or a confirmation prompt.
pub fn plan_uninstall(home: &Path, keep_secrets: bool) -> UninstallPlan {
    let mut remove = Vec::new();
    let mut preserved = Vec::new();

    if let Ok(entries) = std::fs::read_dir(home) {
        for entry in entries.filter_map(Result::ok) {
            let name = entry.file_name().to_string_lossy().to_string();
            // The dotenv secrets file is the one thing we optionally keep.
            if keep_secrets && name == "env" {
                preserved.push(name);
                continue;
            }
            remove.push(entry.path());
        }
    }
    remove.sort();
    preserved.sort();

    UninstallPlan {
        home: home.to_path_buf(),
        remove,
        preserved,
        shared_hf_cache: existing_hf_cache(),
    }
}

/// Execute a plan: remove each listed entry. Returns a per-entry result so the
/// CLI can report partial failures (e.g. a permission error) without aborting
/// the rest. Files and directories are both handled. Never touches anything not
/// in `plan.remove` — in particular never the shared HF cache.
pub fn execute(plan: &UninstallPlan) -> Vec<(PathBuf, Result<(), String>)> {
    plan.remove
        .iter()
        .map(|path| {
            let result = remove_path(path).map_err(|e| e.to_string());
            (path.clone(), result)
        })
        .collect()
}

fn remove_path(path: &Path) -> std::io::Result<()> {
    // `symlink_metadata` does NOT follow links: a managed-model symlink (or a
    // symlink to the HF cache) is removed as a *link*, never recursing into or
    // deleting its target. Real directories are removed recursively.
    let meta = std::fs::symlink_metadata(path)?;
    if meta.is_dir() {
        std::fs::remove_dir_all(path)
    } else {
        std::fs::remove_file(path)
    }
}

/// The shared HuggingFace cache root, but only if it exists on disk. Same
/// resolution the rest of CAR uses (`HF_HOME` else `~/.cache/huggingface`),
/// joined with `hub`. Returned for the informational note only.
fn existing_hf_cache() -> Option<PathBuf> {
    let root = std::env::var("HF_HOME")
        .map(PathBuf::from)
        .unwrap_or_else(|_| {
            let home = std::env::var_os("HOME")
                .or_else(|| std::env::var_os("USERPROFILE"))
                .map(PathBuf::from)
                .unwrap_or_else(|| PathBuf::from("."));
            home.join(".cache").join("huggingface")
        })
        .join("hub");
    root.exists().then_some(root)
}

// ---------------------------------------------------------------------------
// macOS host-app state
// ---------------------------------------------------------------------------
//
// macOS-only by cfg-target gating, not a cargo feature (project convention #1).

/// Bundle identifier of the macOS host app. Simultaneously the TCC subject,
/// the `defaults` preferences domain, and the directory name CarHost.app uses
/// under `~/Library/*`.
#[cfg(target_os = "macos")]
pub const HOST_BUNDLE_ID: &str = "ai.parslee.car";

/// Label prefix of CAR's *scheduled-task* launch agents. `car-scheduler` reaps
/// those (with a `launchctl bootout`) before this plan executes, so the plan
/// skips them rather than racing to unlink a plist that is already gone.
/// Mirrors `car_scheduler::os_schedule::LABEL_PREFIX`, duplicated as a literal
/// because `car-inference` does not depend on `car-scheduler`.
#[cfg(target_os = "macos")]
const SCHEDULE_LABEL_PREFIX: &str = "ai.parslee.car.task.";

/// What clearing the macOS host app's state would do — computed before any
/// deletion or process spawn, so the CLI can render it for a dry run or a
/// confirmation prompt.
#[cfg(target_os = "macos")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MacHostPlan {
    /// Preferences domain to clear with `defaults delete` before the plist is
    /// unlinked. `Some` only when that plist exists on disk.
    pub prefs_domain: Option<String>,
    /// launchd labels of the legacy CAR launch agents whose plists this plan
    /// unlinks, carried as *data* — the planner spawns nothing. Booting these
    /// out has to happen BEFORE the plist is removed: unlinking a plist does
    /// not unload the job, so a still-bootstrapped `ai.parslee.car-server`
    /// (KeepAlive) would keep respawning — recreating `~/.car` mid-purge —
    /// with no plist path left for the operator to unload by. Same order
    /// CarHost.app's legacy cleanup and `car_scheduler::os_schedule::uninstall`
    /// use.
    pub bootout: Vec<String>,
    /// Host-state paths to delete. Only paths that exist are listed.
    pub remove: Vec<PathBuf>,
    /// The `tccutil` argv, carried as *data* — the planner spawns nothing.
    /// `None` under `keep_permissions`, and also when nothing on this machine
    /// looks like a CAR host install: resetting grants for a bundle that was
    /// never here is not a purge, it is a guaranteed `-10814`.
    pub tcc_reset: Option<Vec<String>>,
}

#[cfg(target_os = "macos")]
impl MacHostPlan {
    /// True when there is no host state to clear and no grants to reset.
    pub fn is_empty(&self) -> bool {
        self.remove.is_empty()
            && self.bootout.is_empty()
            && self.prefs_domain.is_none()
            && self.tcc_reset.is_none()
    }

    /// The plan that does nothing — what a relocated state root gets.
    fn empty() -> Self {
        Self {
            prefs_domain: None,
            bootout: Vec::new(),
            remove: Vec::new(),
            tcc_reset: None,
        }
    }
}

/// Why a `tccutil reset` did not complete. Split out from a plain string
/// because the CLI renders [`TccResetError::BundleMissing`] as *guidance* (the
/// app is already gone, so macOS can no longer resolve its grants by
/// identifier) rather than as an opaque failure.
#[cfg(target_os = "macos")]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TccResetError {
    /// macOS could not resolve the bundle identifier. `tccutil` reports this
    /// as exit 64 with `OSStatus error -10814` (`kLSApplicationNotFoundErr`).
    BundleMissing,
    /// Anything else — `tccutil` missing, spawn failure, other non-zero exit.
    Failed(String),
}

/// Outcome of [`execute_macos_host`].
#[cfg(target_os = "macos")]
#[derive(Debug)]
pub struct MacHostOutcome {
    /// Result of each `launchctl bootout`, label-keyed and in plan order.
    /// Best-effort: an agent that was never loaded reports `Ok`, and the CLI
    /// warns rather than failing on anything else — launchd's "is it loaded"
    /// states are racy and the purge itself still succeeded.
    pub bootout: Vec<(String, Result<(), String>)>,
    /// One labelled entry per step, in execution order, so the CLI can report
    /// partial failures without aborting the rest.
    pub steps: Vec<(String, Result<(), String>)>,
    /// Result of the `tccutil` step; `None` when the plan carried no reset.
    pub tcc: Option<Result<(), TccResetError>>,
}

/// Build the host-state plan. Pure (stats the filesystem, deletes nothing and
/// spawns nothing), so the CLI can render it for a dry run. `home_dir` is the
/// `$HOME` root and `app_bundle` the installed `CarHost.app`; both are
/// parameters so tests can drive a `TempDir` — same shape as [`plan_uninstall`].
///
/// `state_root_relocated` is `car_home::override_root().is_some()` at the call
/// site — i.e. the operator set `CAR_HOME` and is purging a *relocated* install.
/// That install is by definition not this machine's `CarHost.app`: everything
/// below lives at fixed `$HOME/Library` paths and the TCC grants are keyed to a
/// bundle identifier, so clearing them would delete the DEFAULT install's
/// onboarding sentinel, auth tokens and privacy grants — exactly the
/// cross-install clobber `car-home` exists to prevent (Parslee-ai/car#629).
/// A relocated root therefore gets the empty plan; its own token dir lives at
/// `<root>/ai.parslee.car` and is already covered by [`plan_uninstall`], which
/// lists every top-level entry of the root.
#[cfg(target_os = "macos")]
pub fn plan_macos_host(
    home_dir: &Path,
    app_bundle: &Path,
    keep_permissions: bool,
    state_root_relocated: bool,
) -> MacHostPlan {
    if state_root_relocated {
        return MacHostPlan::empty();
    }

    let lib = home_dir.join("Library");
    let prefs_plist = lib
        .join("Preferences")
        .join(format!("{HOST_BUNDLE_ID}.plist"));

    // Artifacts only CarHost.app itself creates. This is the `tccutil` signal
    // (below) and NOT simply "anything we are about to delete", because
    // `Application Support/ai.parslee.car` is the daemon auth-token dir
    // (`car_daemon_client::auth_token`, macOS branch) — written by any
    // `car`/`car-server` install, `npm i -g car-runtime` included, on machines
    // that have never seen the host app. Treating it as evidence planned a
    // reset macOS can only answer with -10814, which turned a CLI-only
    // `car purge` into a non-zero exit carrying a false "your grants are still
    // recorded" message. A CLI has no bundle identifier, so it never writes
    // `Preferences/<id>.plist`, `Caches/<id>` or a `<id>.savedState`.
    let app_evidence = [
        prefs_plist.clone(),
        lib.join("Caches").join(HOST_BUNDLE_ID),
        lib.join("Saved Application State")
            .join(format!("{HOST_BUNDLE_ID}.savedState")),
    ];
    let host_present = exists(app_bundle) || app_evidence.iter().any(|p| exists(p));

    let mut remove: Vec<PathBuf> = app_evidence
        .into_iter()
        .chain([lib.join("Application Support").join(HOST_BUNDLE_ID)])
        .filter(|p| exists(p))
        .collect();

    // Prefix matches, not exact names: HTTPStorages splits the domain across
    // `<id>` and `<id>.binarycookies`, and the legacy launch agents are
    // `<id>-host.plist` / `<id>-server.plist`.
    remove.extend(entries_with_prefix(&lib.join("HTTPStorages"), |_| true));

    let launch_agents = entries_with_prefix(&lib.join("LaunchAgents"), |name| {
        !name.starts_with(SCHEDULE_LABEL_PREFIX)
    });
    // The launchd label is the plist's file stem. Derived rather than hardcoded
    // so a plist this scan finds is always booted out before it is unlinked,
    // including any legacy name not in today's `-host` / `-server` pair.
    let mut bootout: Vec<String> = launch_agents
        .iter()
        .filter_map(|p| p.file_stem().map(|s| s.to_string_lossy().into_owned()))
        .collect();
    bootout.sort();
    bootout.dedup();
    remove.extend(launch_agents);

    remove.sort();
    remove.dedup();

    let prefs_domain = exists(&prefs_plist).then(|| HOST_BUNDLE_ID.to_string());
    let tcc_reset = (!keep_permissions && host_present).then(|| {
        vec![
            "/usr/bin/tccutil".to_string(),
            "reset".to_string(),
            "All".to_string(),
            HOST_BUNDLE_ID.to_string(),
        ]
    });

    MacHostPlan {
        prefs_domain,
        bootout,
        remove,
        tcc_reset,
    }
}

/// Boot out the plan's legacy launch agents, best-effort. Idempotent — a job
/// that is not loaded reports `Ok` — so a caller may run this early (before the
/// `~/.car` removal, to stop a `KeepAlive` `ai.parslee.car-server` respawning
/// into the state being deleted) and [`execute_macos_host`] will still re-run
/// it harmlessly before unlinking the plists.
#[cfg(target_os = "macos")]
pub fn stop_legacy_agents(plan: &MacHostPlan) -> Vec<(String, Result<(), String>)> {
    plan.bootout
        .iter()
        .map(|label| (label.clone(), launchctl_bootout(label)))
        .collect()
}

/// `launchctl bootout gui/<uid>/<label>`. "Not loaded" is the goal state, not a
/// failure: launchd answers `3` / `No such process` for a job that was never
/// bootstrapped, which is the common case on a machine that only ever used
/// SMAppService. A missing `gui/<uid>` domain counts the same way — no GUI
/// session (a purge over SSH, or a headless CI runner) means there is no domain
/// the agent could be loaded into.
#[cfg(target_os = "macos")]
fn launchctl_bootout(label: &str) -> Result<(), String> {
    // SAFETY: `getuid` is always-succeeds, takes no arguments and touches no
    // memory the caller owns.
    let uid = unsafe { libc::getuid() };
    let out = std::process::Command::new("/bin/launchctl")
        .args(["bootout", &format!("gui/{uid}/{label}")])
        .output()
        .map_err(|e| format!("could not run launchctl: {e}"))?;
    if out.status.success() || out.status.code() == Some(3) {
        return Ok(());
    }
    let stderr = String::from_utf8_lossy(&out.stderr);
    if stderr.contains("No such process") || stderr.contains("Could not find domain") {
        return Ok(());
    }
    let detail = stderr.trim();
    Err(if detail.is_empty() {
        format!("launchctl bootout exited with {}", out.status)
    } else {
        detail.to_string()
    })
}

/// Execute a host-state plan: boot out the legacy launch agents, clear the
/// preferences domain, remove the listed paths, then reset the TCC grants.
/// Never touches anything not in the plan.
#[cfg(target_os = "macos")]
pub fn execute_macos_host(plan: &MacHostPlan) -> MacHostOutcome {
    let mut steps = Vec::new();

    // Bootout BEFORE the plists are unlinked (they are in `plan.remove`).
    // Unlinking a plist does not unload the job; doing it in the other order
    // leaves a live launchd job with no plist path left to unload it by.
    let bootout = stop_legacy_agents(plan);

    // `defaults delete` FIRST. cfprefsd keeps the domain cached in memory and
    // rewrites the plist on its own schedule, so unlinking the file alone can
    // be silently undone — the onboarding sentinel comes back and the wizard
    // still believes setup is finished.
    if let Some(domain) = &plan.prefs_domain {
        steps.push((
            format!("defaults delete {domain}"),
            delete_prefs_domain(domain),
        ));
    }

    for path in &plan.remove {
        steps.push((
            path.display().to_string(),
            remove_path(path).map_err(|e| e.to_string()),
        ));
    }

    let tcc = plan.tcc_reset.as_deref().map(run_tccutil);
    MacHostOutcome {
        bootout,
        steps,
        tcc,
    }
}

/// `symlink_metadata`, so a dangling symlink still counts as present and gets
/// unlinked — same non-following rule [`remove_path`] applies.
#[cfg(target_os = "macos")]
fn exists(path: &Path) -> bool {
    std::fs::symlink_metadata(path).is_ok()
}

/// Entries of `dir` whose file name starts with [`HOST_BUNDLE_ID`] and that
/// `keep` accepts. A missing directory yields nothing.
#[cfg(target_os = "macos")]
fn entries_with_prefix(dir: &Path, keep: impl Fn(&str) -> bool) -> Vec<PathBuf> {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return Vec::new();
    };
    entries
        .filter_map(Result::ok)
        .filter_map(|entry| {
            let name = entry.file_name().to_string_lossy().into_owned();
            (name.starts_with(HOST_BUNDLE_ID) && keep(&name)).then(|| entry.path())
        })
        .collect()
}

#[cfg(target_os = "macos")]
fn delete_prefs_domain(domain: &str) -> Result<(), String> {
    let out = std::process::Command::new("/usr/bin/defaults")
        .args(["delete", domain])
        .output()
        .map_err(|e| format!("could not run defaults: {e}"))?;
    if out.status.success() {
        return Ok(());
    }
    let stderr = String::from_utf8_lossy(&out.stderr);
    // An absent domain is the goal state, not a failure. Measured wording on
    // macOS 15: `Domain (<id>) not found.` / `Defaults have not been changed.`
    // Older releases print `does not exist`; accept both.
    if stderr.contains("not found") || stderr.contains("does not exist") {
        return Ok(());
    }
    Err(stderr.trim().to_string())
}

#[cfg(target_os = "macos")]
fn run_tccutil(argv: &[String]) -> Result<(), TccResetError> {
    let Some((bin, args)) = argv.split_first() else {
        return Err(TccResetError::Failed("empty tccutil argv".to_string()));
    };
    let out = std::process::Command::new(bin)
        .args(args)
        .output()
        .map_err(|e| TccResetError::Failed(format!("could not run {bin}: {e}")))?;
    if out.status.success() {
        return Ok(());
    }
    let stderr = String::from_utf8_lossy(&out.stderr);
    // Measured on macOS 15: `tccutil reset All <unknown-bundle>` exits 64 with
    // `No such bundle identifier … (OSStatus error -10814.)`.
    if out.status.code() == Some(64) || stderr.contains("-10814") {
        return Err(TccResetError::BundleMissing);
    }
    let detail = stderr.trim();
    Err(TccResetError::Failed(if detail.is_empty() {
        format!("tccutil exited with {}", out.status)
    } else {
        detail.to_string()
    }))
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    fn touch(p: &Path) {
        std::fs::write(p, b"x").unwrap();
    }

    #[test]
    fn plan_lists_all_top_level_entries() {
        let tmp = TempDir::new().unwrap();
        touch(&tmp.path().join("models.json"));
        std::fs::create_dir_all(tmp.path().join("models")).unwrap();
        std::fs::create_dir_all(tmp.path().join("logs")).unwrap();

        let plan = plan_uninstall(tmp.path(), false);
        assert_eq!(plan.remove.len(), 3);
        assert!(plan.preserved.is_empty());
        assert!(!plan.is_empty());
    }

    #[test]
    fn keep_secrets_preserves_env() {
        let tmp = TempDir::new().unwrap();
        touch(&tmp.path().join("env"));
        touch(&tmp.path().join("models.json"));

        let plan = plan_uninstall(tmp.path(), true);
        assert_eq!(plan.preserved, vec!["env".to_string()]);
        assert!(plan.remove.iter().all(|p| p.file_name().unwrap() != "env"));

        // Without --keep-secrets, env is removed like anything else.
        let plan = plan_uninstall(tmp.path(), false);
        assert!(plan.preserved.is_empty());
        assert!(plan.remove.iter().any(|p| p.file_name().unwrap() == "env"));
    }

    #[test]
    fn execute_removes_files_and_dirs_and_reports() {
        let tmp = TempDir::new().unwrap();
        touch(&tmp.path().join("models.json"));
        std::fs::create_dir_all(tmp.path().join("logs").join("sub")).unwrap();
        touch(&tmp.path().join("logs").join("sub").join("a.log"));

        let plan = plan_uninstall(tmp.path(), false);
        let results = execute(&plan);
        assert!(results.iter().all(|(_, r)| r.is_ok()), "{results:?}");
        assert!(!tmp.path().join("models.json").exists());
        assert!(!tmp.path().join("logs").exists());
    }

    #[cfg(unix)]
    #[test]
    fn removing_a_model_symlink_does_not_touch_its_target() {
        // A managed-model symlink into a "shared cache" must be removed as a
        // link; its target (the shared blob) must survive.
        let tmp = TempDir::new().unwrap();
        let home = tmp.path().join(".car");
        let cache = tmp.path().join("cache");
        std::fs::create_dir_all(home.join("models")).unwrap();
        std::fs::create_dir_all(&cache).unwrap();
        let blob = cache.join("blob");
        touch(&blob);
        std::os::unix::fs::symlink(&blob, home.join("models").join("weights.safetensors")).unwrap();

        let plan = plan_uninstall(&home, false);
        let results = execute(&plan);
        assert!(results.iter().all(|(_, r)| r.is_ok()));
        assert!(!home.join("models").exists(), "managed model dir removed");
        assert!(blob.exists(), "shared blob behind the symlink must survive");
    }

    #[test]
    fn missing_home_yields_empty_plan() {
        let tmp = TempDir::new().unwrap();
        let plan = plan_uninstall(&tmp.path().join("nonexistent"), false);
        assert!(plan.is_empty());
        // Executing an empty plan is a harmless no-op.
        assert!(execute(&plan).is_empty());
    }
}

#[cfg(all(test, target_os = "macos"))]
mod macos_host_tests {
    use super::*;
    use tempfile::TempDir;

    /// Lay down a `$HOME` holding the host-state paths named in `names`,
    /// relative to `$HOME/Library`. A trailing `/` makes a directory.
    fn home_with(names: &[&str]) -> TempDir {
        let tmp = TempDir::new().unwrap();
        for name in names {
            let path = tmp.path().join("Library").join(name);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            if name.ends_with('/') {
                std::fs::create_dir_all(&path).unwrap();
            } else {
                std::fs::write(&path, b"x").unwrap();
            }
        }
        tmp
    }

    fn missing_bundle() -> PathBuf {
        PathBuf::from("/Applications/definitely-not-installed-CarHost.app")
    }

    #[test]
    fn plan_lists_only_host_paths_that_exist() {
        let home = home_with(&[
            "Preferences/ai.parslee.car.plist",
            "Application Support/ai.parslee.car/auth-token",
            "Caches/ai.parslee.car/blob",
            "HTTPStorages/ai.parslee.car",
            "HTTPStorages/ai.parslee.car.binarycookies",
            "Saved Application State/ai.parslee.car.savedState/window.plist",
            "LaunchAgents/ai.parslee.car-server.plist",
            // Neighbours that must survive.
            "Preferences/com.apple.finder.plist",
            "Caches/ai.parslee.other/blob",
        ]);
        let lib = home.path().join("Library");

        let plan = plan_macos_host(home.path(), &missing_bundle(), false, false);
        let names: Vec<String> = plan
            .remove
            .iter()
            .map(|p| p.strip_prefix(&lib).unwrap().display().to_string())
            .collect();
        assert_eq!(
            names,
            vec![
                "Application Support/ai.parslee.car".to_string(),
                "Caches/ai.parslee.car".to_string(),
                "HTTPStorages/ai.parslee.car".to_string(),
                "HTTPStorages/ai.parslee.car.binarycookies".to_string(),
                "LaunchAgents/ai.parslee.car-server.plist".to_string(),
                "Preferences/ai.parslee.car.plist".to_string(),
                "Saved Application State/ai.parslee.car.savedState".to_string(),
            ],
            "{plan:#?}"
        );
        assert_eq!(plan.prefs_domain.as_deref(), Some("ai.parslee.car"));
        assert!(!plan.is_empty());
    }

    #[test]
    fn scheduled_task_agents_are_left_to_the_scheduler() {
        // `car-scheduler` boots these out and unlinks them before the host
        // plan executes; listing them here would race it and report a bogus
        // failure for a plist that is already gone.
        let home = home_with(&[
            "LaunchAgents/ai.parslee.car.task.abc123.plist",
            "LaunchAgents/ai.parslee.car-host.plist",
        ]);
        let plan = plan_macos_host(home.path(), &missing_bundle(), false, false);
        let names: Vec<String> = plan
            .remove
            .iter()
            .map(|p| p.file_name().unwrap().to_string_lossy().into_owned())
            .collect();
        assert_eq!(names, vec!["ai.parslee.car-host.plist".to_string()]);
    }

    #[test]
    fn tcc_reset_renders_the_exact_argv() {
        let home = home_with(&["Preferences/ai.parslee.car.plist"]);
        let plan = plan_macos_host(home.path(), &missing_bundle(), false, false);
        assert_eq!(
            plan.tcc_reset.as_deref(),
            Some(
                [
                    "/usr/bin/tccutil".to_string(),
                    "reset".to_string(),
                    "All".to_string(),
                    "ai.parslee.car".to_string(),
                ]
                .as_slice()
            )
        );
    }

    #[test]
    fn keep_permissions_omits_the_tccutil_argv() {
        let home = home_with(&["Preferences/ai.parslee.car.plist"]);
        let plan = plan_macos_host(home.path(), &missing_bundle(), true, false);
        assert!(plan.tcc_reset.is_none());
        // Only the grants are spared — the state removal is unaffected.
        assert_eq!(plan.remove.len(), 1);
        assert!(!plan.is_empty());
    }

    #[test]
    fn no_host_install_plans_nothing_at_all() {
        // A machine that never had CarHost.app must not get a `tccutil reset`
        // that macOS can only answer with -10814.
        let home = TempDir::new().unwrap();
        let plan = plan_macos_host(home.path(), &missing_bundle(), false, false);
        assert!(plan.is_empty(), "{plan:#?}");
        assert!(plan.tcc_reset.is_none());
        assert!(plan.prefs_domain.is_none());
    }

    #[test]
    fn a_cli_only_mac_earns_no_tcc_reset() {
        // The realistic "daemon has run, no host app" home: `npm i -g
        // car-runtime` writes `Application Support/ai.parslee.car/auth-token`
        // (car_daemon_client::auth_token's macOS branch) with CarHost.app
        // nowhere on the machine. That directory must still be REMOVED, but it
        // is not evidence of a host install — treating it as evidence planned a
        // `tccutil reset` that exits 64 / -10814, so `car purge` reported a
        // false "grants are still recorded" failure and exited 1 on a Mac with
        // no grants at all.
        let home = home_with(&["Application Support/ai.parslee.car/auth-token"]);
        let plan = plan_macos_host(home.path(), &missing_bundle(), false, false);
        assert!(plan.tcc_reset.is_none(), "{plan:#?}");
        assert_eq!(plan.remove.len(), 1);
        assert!(plan.remove[0].ends_with("Application Support/ai.parslee.car"));
        assert!(plan.prefs_domain.is_none());
        assert!(!plan.is_empty(), "the token dir is still purged");
    }

    #[test]
    fn a_relocated_state_root_never_touches_the_default_install() {
        // `CAR_HOME=/tmp/car-alt car purge` purges the RELOCATED root. Every
        // path below is at a fixed `$HOME/Library` location and TCC is keyed to
        // a bundle id, so clearing them would wipe the DEFAULT install's
        // onboarding sentinel, auth tokens and privacy grants — the exact
        // cross-install clobber car-home exists to prevent (car#629). The
        // relocated root's own token dir is `<root>/ai.parslee.car`, already
        // covered by `plan_uninstall`.
        let home = home_with(&[
            "Preferences/ai.parslee.car.plist",
            "Application Support/ai.parslee.car/auth-token",
            "Caches/ai.parslee.car/blob",
            "LaunchAgents/ai.parslee.car-server.plist",
        ]);
        let bundle = TempDir::new().unwrap();
        let plan = plan_macos_host(home.path(), bundle.path(), false, true);
        assert!(plan.is_empty(), "{plan:#?}");
        assert!(plan.remove.is_empty(), "no $HOME/Library entries");
        assert!(plan.bootout.is_empty());
        assert!(plan.tcc_reset.is_none(), "no tccutil reset");
        assert!(plan.prefs_domain.is_none());
    }

    #[test]
    fn legacy_agents_are_booted_out_before_their_plists_are_unlinked() {
        // Unlinking a plist does not unload the job. `ai.parslee.car-server` is
        // the KeepAlive daemon agent: raw-unlink it and launchd respawns
        // car-server, which recreates `~/.car` mid-purge, and the plist path the
        // operator would unload by is gone. Same bootout-then-unlink order as
        // CarHost.app's legacy cleanup and car-scheduler's uninstall.
        let home = home_with(&[
            "LaunchAgents/ai.parslee.car-server.plist",
            "LaunchAgents/ai.parslee.car-host.plist",
            // Scheduled tasks stay with car-scheduler, bootout included.
            "LaunchAgents/ai.parslee.car.task.abc123.plist",
        ]);
        let plan = plan_macos_host(home.path(), &missing_bundle(), true, false);
        assert_eq!(
            plan.bootout,
            vec![
                "ai.parslee.car-host".to_string(),
                "ai.parslee.car-server".to_string()
            ],
            "{plan:#?}"
        );
        // Every label the plan boots out corresponds to a plist it unlinks.
        for label in &plan.bootout {
            assert!(
                plan.remove
                    .iter()
                    .any(|p| p.file_stem().map(|s| s == label.as_str()) == Some(true)),
                "{label} booted out but its plist is not in remove"
            );
        }
    }

    #[test]
    fn booting_out_an_unloaded_agent_is_a_no_op_success() {
        // launchd answers `3` / `No such process` for a job that was never
        // bootstrapped — the common case on an SMAppService-only machine, and
        // not a purge failure. Uses a throwaway label so this Mac's real agents
        // are untouched.
        assert_eq!(
            launchctl_bootout("ai.parslee.car.uninstall-test-not-a-real-agent"),
            Ok(())
        );
    }

    #[test]
    fn an_installed_app_alone_still_earns_a_reset() {
        // The bundle is present but its user state is already gone — the
        // grants are exactly what is left to clear.
        let home = TempDir::new().unwrap();
        let bundle = TempDir::new().unwrap();
        let plan = plan_macos_host(home.path(), bundle.path(), false, false);
        assert!(plan.remove.is_empty());
        assert!(plan.tcc_reset.is_some());
        assert!(!plan.is_empty());
    }

    #[test]
    fn execute_removes_host_state_and_reports_each_step() {
        let home = home_with(&[
            "Application Support/ai.parslee.car/auth-token",
            "Caches/ai.parslee.car/blob",
        ]);
        // No prefs domain and no tcc argv, so this test spawns nothing.
        let plan = MacHostPlan {
            prefs_domain: None,
            tcc_reset: None,
            ..plan_macos_host(home.path(), &missing_bundle(), true, false)
        };
        let outcome = execute_macos_host(&plan);
        assert_eq!(outcome.steps.len(), 2);
        assert!(outcome.steps.iter().all(|(_, r)| r.is_ok()), "{outcome:?}");
        assert!(outcome.tcc.is_none());
        assert!(!home
            .path()
            .join("Library/Application Support/ai.parslee.car")
            .exists());
        assert!(!home.path().join("Library/Caches/ai.parslee.car").exists());
    }

    #[test]
    fn an_unresolvable_bundle_is_reported_as_bundle_missing() {
        // The measured failure mode: CarHost.app trashed before `car purge`
        // ran, so macOS can no longer resolve its grants by identifier.
        // `tccutil` answers exit 64 / OSStatus -10814 for ANY unknown bundle,
        // so a throwaway identifier exercises the real binary without
        // disturbing this machine's actual grants.
        let argv = [
            "/usr/bin/tccutil".to_string(),
            "reset".to_string(),
            "All".to_string(),
            "ai.parslee.car.uninstall-test-not-a-real-bundle".to_string(),
        ];
        assert_eq!(run_tccutil(&argv), Err(TccResetError::BundleMissing));
    }

    #[test]
    fn a_missing_tccutil_binary_is_a_plain_failure() {
        let argv = [
            "/usr/bin/tccutil-does-not-exist".to_string(),
            "reset".to_string(),
        ];
        assert!(matches!(
            run_tccutil(&argv),
            Err(TccResetError::Failed(msg)) if msg.contains("could not run")
        ));
    }

    #[test]
    fn deleting_an_absent_prefs_domain_is_a_no_op_success() {
        assert_eq!(
            delete_prefs_domain("ai.parslee.car.uninstall-test-not-a-real-domain"),
            Ok(())
        );
    }
}