car-inference 0.47.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
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
//! `car doctor` — an offline health check + repair for a CAR install.
//!
//! Built to run *when things are broken*. It touches only the local filesystem
//! (`~/.car` and the shared HuggingFace model cache), never the daemon, so it
//! still works after a half-finished reinstall or when `car-server` won't even
//! start. It surfaces — and, in `--repair` mode, fixes what's safe to fix — the
//! failure modes that successive installs and a shared, externally-mutated cache
//! produce:
//!
//!   * **Corrupt model weights** — truncated/byte-rotted/externally-deleted files
//!     in the model cache (reuses the Task-1/2 integrity primitives in
//!     [`crate::download`]).
//!   * **Incomplete installs** — a managed model dir whose manifest was symlinked
//!     into the HuggingFace snapshot but whose weights never arrived, i.e. what
//!     an interrupted `car models pull` leaves behind (Parslee-ai/car#616).
//!   * **Unparseable state files** — a `~/.car/*.json` an older version wrote in a
//!     shape this binary can't read, or a partially-written file.
//!   * **Version skew** — state last written by a different CAR version than the
//!     binary now running (read from the `version.json` stamp).
//!   * **Abandoned partial downloads** — `*.sync.part` blobs stranded in the
//!     HuggingFace cache. Reported with sizes, never deleted (see
//!     [`find_leftovers`]).
//!   * **Empty event journals** — a zero-byte journal per session that never
//!     executed anything; reaped under `--repair` (see [`find_empty_journals`]).
//!   * **Leftovers** — top-level `~/.car` entries this version doesn't recognize,
//!     which may be debris from a previous install.
//!
//! Repair is deliberately conservative: it purges *provably* corrupt cache files
//! (so the next daemon run re-downloads them), backs up unparseable state files
//! to `<name>.corrupt.bak` rather than deleting them, removes provably-empty
//! journals, and refreshes the version stamp (reporting that only when the stamp
//! actually moved). It never deletes unrecognized entries, partial downloads in
//! the shared HuggingFace cache, or anything else it can't prove is bad —
//! diagnosis names them and leaves the decision to the operator.

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

use serde::{Deserialize, Serialize};

use crate::download::{
    cache_file_usable, purge_corrupt_cache_files, verify_cache_file, CacheIntegrity,
};

/// JSON state files CAR writes directly under `~/.car/`. Used both to validate
/// each (does it parse? what schema version?) and to tell recognized files from
/// possible leftovers. Owned across several crates, but the check is generic
/// (parse as JSON), so no cross-crate type dependency is needed.
const KNOWN_STATE_FILES: &[&str] = &[
    "messaging.json",
    "models.json",
    "connectors.json",
    "car-connectors.json",
    "agents.json",
    "routing.json",
    "declagents.json",
    "lane-defaults.json",
    "update-prefs.json",
    "upgrade-cache.json",
    "catalog-cache.json",
    "discovered_models.json",
    "a2a-peers.json",
    "external-agents.jsonl",
    "nudge-state.json",
    "benchmark_priors.json",
    "key_pool_stats.json",
    "model_profiles.json",
    "agent-permissions.json",
    "version.json",
    // Names-only index for the OS-keychain secret store (car-ffi-common's
    // `INDEX_FILE`), written on every platform whenever a secret is stored —
    // and load-bearing on Windows/Linux, whose keychains have no portable
    // enumeration. Absent on a fresh install with no stored secrets, which is
    // why its omission here only surfaced once `car auth login` / `car keys`
    // had run (e.g. validating on Windows): doctor wrongly flagged the live
    // file as a possible older-install leftover and invited its removal.
    "secret_index.json",
];

/// Recognized files that are deliberately NOT JSON and must never be parsed or
/// moved aside. `env` is a dotenv `KEY=VALUE` file (loaded by `env_loader`,
/// holds API keys) — JSON-validating it would flag a healthy install and, under
/// `--repair`, rename the user's secrets file to `env.corrupt.bak`.
const KNOWN_NON_JSON_FILES: &[&str] = &["env"];

/// Subdirectories CAR creates under `~/.car/`. Anything else at the top level is
/// reported as unrecognized (a possible leftover), never auto-removed.
const KNOWN_DIRS: &[&str] = &[
    "models",
    "journals",
    "logs",
    "agents",
    "runs",
    "run",
    "workflow-runs",
    "workflows",
    "tasks",
    "trajectories",
    "registry",
    "meetings",
    "speech-runtime",
    "visual-runtime",
    "coder",
    "projects",
    "memory",
    "doctor",
    "bin",
    "voiceprints",
    "sync",
];

/// File-name suffixes for volatile/runtime artifacts that are never "leftovers":
/// lockfiles, temp/backup files, binary caches, and append-only logs.
const TOLERATED_SUFFIXES: &[&str] = &[".lock", ".tmp", ".bak", ".bin", ".jsonl"];

/// The on-disk version stamp (`~/.car/version.json`). Written by the daemon on
/// boot and refreshed by `doctor --repair`; read by `doctor` to detect skew
/// between the binary and the state it's operating on.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VersionStamp {
    /// The CAR package version (`CARGO_PKG_VERSION`) that last wrote state.
    pub car_version: String,
    /// The state-schema generation. Bumped only on a breaking change to the
    /// on-disk layout, independent of the package version. A reader newer than
    /// this can migrate; older than this should refuse rather than corrupt.
    pub state_schema_version: u32,
}

/// The current state-schema generation this binary writes/expects. Start at 1;
/// bump when a `~/.car` layout change requires migration.
pub const STATE_SCHEMA_VERSION: u32 = 1;

impl VersionStamp {
    /// The stamp this binary would write right now.
    pub fn current() -> Self {
        VersionStamp {
            car_version: env!("CARGO_PKG_VERSION").to_string(),
            state_schema_version: STATE_SCHEMA_VERSION,
        }
    }
}

/// Canonical `~/.car` base directory. Mirrors the resolution every other part of
/// CAR uses (`$HOME`, or `$USERPROFILE` on Windows, else cwd-relative `./.car`)
/// so `car doctor` always inspects the *same* directory the daemon and registry
/// write to. Deliberately has NO `$CAR_HOME`-style override: nothing else in CAR
/// honors one, and a doctor that diagnoses a different dir than the real install
/// could report a corrupt install as healthy.
pub fn car_home() -> PathBuf {
    std::env::var_os("HOME")
        .or_else(|| std::env::var_os("USERPROFILE"))
        .map(PathBuf::from)
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".car")
}

/// Write/refresh the `version.json` stamp under `car_home`. Called on daemon
/// boot and by `doctor --repair`. Best-effort: a failure to stamp must never
/// block startup, so the caller logs and continues.
pub fn write_version_stamp(car_home: &Path) -> std::io::Result<()> {
    std::fs::create_dir_all(car_home)?;
    let stamp = VersionStamp::current();
    let json = serde_json::to_string_pretty(&stamp)
        .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
    // Atomic-ish: write a per-process temp file in the same dir, then rename
    // over. The pid-scoped name keeps two concurrent boots (or boot + repair)
    // from interleaving writes to one shared temp and tearing version.json.
    let tmp = car_home.join(format!("version.json.{}.tmp", std::process::id()));
    std::fs::write(&tmp, json)?;
    std::fs::rename(&tmp, car_home.join("version.json"))
}

/// Options controlling a diagnosis run.
#[derive(Debug, Clone, Default)]
pub struct DoctorOptions {
    /// Deep-verify model weights (recompute sha256 vs etag) instead of the cheap
    /// resolves-and-non-empty check. Slow (hashes every weight) but catches
    /// truncated-but-non-empty corruption.
    pub deep: bool,
    /// Apply safe repairs: purge corrupt cache files, back up unparseable state,
    /// refresh the version stamp.
    pub repair: bool,
}

/// Verdict for a single `~/.car` JSON state file.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status")]
pub enum StateFileStatus {
    /// Not present — fine; most state files are created on first use.
    Absent,
    /// Present and parses as JSON.
    Ok { schema_version: Option<u32> },
    /// Present but does not parse — corrupt or written by an incompatible
    /// version. `backed_up_to` is set when `--repair` moved it aside.
    Unparseable {
        error: String,
        backed_up_to: Option<String>,
    },
}

/// One state-file check.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateFileCheck {
    pub name: String,
    #[serde(flatten)]
    pub status: StateFileStatus,
}

/// Verdict for one installed model directory.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case", tag = "status")]
pub enum ModelStatus {
    /// Weight files present and (for `--deep`) hash-verified.
    Healthy,
    /// At least one weight file is corrupt/missing. `purged` is how many were
    /// removed in `--repair` mode (so the next pull re-downloads them).
    Corrupt {
        bad_files: Vec<String>,
        purged: usize,
    },
    /// The directory looks like a model install — it has `config.json` /
    /// tokenizer stubs — but carries no resolvable weights at all. This is what
    /// an interrupted `car models pull` leaves behind, and it used to be
    /// invisible: `check_one_model` returned `None` for any dir with no weight
    /// files, so the report dropped it and `car doctor` said "none installed /
    /// Healthy" over a broken install (Parslee-ai/car#616).
    ///
    /// Note the loader already knew: `registry::ensure_local` gates reuse on
    /// `mlx_dir_has_weights` and re-downloads a config-only stub
    /// (car-releases#391). The diagnostic just disagreed with the runtime.
    Incomplete { detail: String },
}

/// A file left behind by an interrupted download.
///
/// Reported, never deleted — see [`find_leftovers`] for why.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Leftover {
    pub path: String,
    pub bytes: u64,
}

/// One model check.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelCheck {
    pub name: String,
    #[serde(flatten)]
    pub status: ModelStatus,
}

/// The full diagnosis.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DoctorReport {
    pub car_home: String,
    /// The version of the binary that produced this report.
    pub binary_version: String,
    /// The version stamp found on disk, if any (None ⇒ never stamped).
    pub on_disk_stamp: Option<VersionStamp>,
    /// True when the on-disk stamp's version differs from the binary.
    pub version_skew: bool,
    pub state_files: Vec<StateFileCheck>,
    pub models: Vec<ModelCheck>,
    /// Partial downloads abandoned in the HuggingFace cache. Informational —
    /// they waste disk but nothing is broken, so they don't affect
    /// [`DoctorReport::is_healthy`].
    #[serde(default)]
    pub leftovers: Vec<Leftover>,
    /// Top-level `~/.car` entries this version doesn't recognize.
    pub unrecognized: Vec<String>,
    /// Human-readable actions taken in `--repair` mode (empty otherwise).
    pub repairs: Vec<String>,
}

impl DoctorReport {
    /// True when nothing actionable was found (modulo unrecognized entries,
    /// which are informational).
    pub fn is_healthy(&self) -> bool {
        !self.version_skew
            && self
                .state_files
                .iter()
                .all(|f| !matches!(f.status, StateFileStatus::Unparseable { .. }))
            && self
                .models
                .iter()
                .all(|m| matches!(m.status, ModelStatus::Healthy))
    }
}

/// Run a diagnosis (and, if `opts.repair`, repairs) against the real `~/.car`.
pub fn diagnose(opts: &DoctorOptions) -> DoctorReport {
    diagnose_in(&car_home(), opts)
}

/// Diagnosis against an explicit base dir — the testable core.
pub fn diagnose_in(home: &Path, opts: &DoctorOptions) -> DoctorReport {
    let mut repairs = Vec::new();

    // --- version stamp / skew ------------------------------------------------
    let on_disk_stamp = read_version_stamp(home);
    let binary = VersionStamp::current();
    let version_skew = on_disk_stamp
        .as_ref()
        .map(|s| {
            s.car_version != binary.car_version
                || s.state_schema_version != binary.state_schema_version
        })
        .unwrap_or(false);

    // --- state files ---------------------------------------------------------
    let mut state_files = Vec::new();
    for name in KNOWN_STATE_FILES {
        state_files.push(check_state_file(home, name, opts, &mut repairs));
    }

    // --- models --------------------------------------------------------------
    let models = check_models(&home.join("models"), opts, &mut repairs);

    // --- leftovers -----------------------------------------------------------
    let leftovers = find_leftovers();
    let unrecognized = find_unrecognized(home);

    // --- refresh stamp on repair --------------------------------------------
    if opts.repair {
        // Only *report* a stamp refresh when the stamp actually moved. It was
        // rewritten and announced unconditionally, so `car doctor --repair` on
        // a perfectly healthy install always printed a line under "Repairs:",
        // implying something had been wrong (Parslee-ai/car#626). The write
        // still happens either way — it's cheap and makes a missing stamp
        // appear — but a no-op write is not a repair.
        let already_current = on_disk_stamp
            .as_ref()
            .map(|s| {
                s.car_version == binary.car_version
                    && s.state_schema_version == binary.state_schema_version
            })
            .unwrap_or(false);
        match write_version_stamp(home) {
            Ok(()) if !already_current => repairs.push(format!(
                "refreshed version stamp to {} (schema v{})",
                binary.car_version, binary.state_schema_version
            )),
            Ok(()) => {}
            Err(e) => repairs.push(format!("failed to refresh version stamp: {e}")),
        }
    }

    // --- reap empty journals on repair ---------------------------------------
    let empty_journals = find_empty_journals(home);
    if opts.repair && !empty_journals.is_empty() {
        let mut removed = 0usize;
        for p in &empty_journals {
            if std::fs::remove_file(p).is_ok() {
                removed += 1;
            }
        }
        if removed > 0 {
            repairs.push(format!(
                "removed {removed} empty event journal(s) from journals/"
            ));
        }
    }

    DoctorReport {
        car_home: home.display().to_string(),
        binary_version: binary.car_version,
        on_disk_stamp,
        version_skew,
        state_files,
        models,
        leftovers,
        unrecognized,
        repairs,
    }
}

fn read_version_stamp(home: &Path) -> Option<VersionStamp> {
    let text = std::fs::read_to_string(home.join("version.json")).ok()?;
    serde_json::from_str(&text).ok()
}

fn check_state_file(
    home: &Path,
    name: &str,
    opts: &DoctorOptions,
    repairs: &mut Vec<String>,
) -> StateFileCheck {
    let path = home.join(name);
    let is_jsonl = name.ends_with(".jsonl");
    let status = match std::fs::read_to_string(&path) {
        Err(_) => StateFileStatus::Absent,
        Ok(text) if text.trim().is_empty() => StateFileStatus::Ok {
            schema_version: None,
        },
        // JSONL (one JSON value per line) must be validated line-by-line — the
        // whole file is not a single JSON document.
        Ok(text) if is_jsonl => match jsonl_first_bad_line(&text) {
            None => StateFileStatus::Ok {
                schema_version: None,
            },
            Some(e) => unparseable(&path, name, e, opts, repairs),
        },
        Ok(text) => match serde_json::from_str::<serde_json::Value>(&text) {
            Ok(value) => StateFileStatus::Ok {
                schema_version: value
                    .get("schema_version")
                    .and_then(serde_json::Value::as_u64)
                    .map(|v| v as u32),
            },
            Err(e) => unparseable(&path, name, e.to_string(), opts, repairs),
        },
    };
    StateFileCheck {
        name: name.to_string(),
        status,
    }
}

/// Validate each non-empty line of a JSONL file; return the first parse error
/// (with its line number) or `None` if all lines are valid JSON.
fn jsonl_first_bad_line(text: &str) -> Option<String> {
    for (i, line) in text.lines().enumerate() {
        if line.trim().is_empty() {
            continue;
        }
        if let Err(e) = serde_json::from_str::<serde_json::Value>(line) {
            return Some(format!("line {}: {e}", i + 1));
        }
    }
    None
}

/// Shared handling for an unparseable state file: in repair mode, move it aside
/// to `<name>.corrupt.bak` (never delete) so the owning crate writes a fresh
/// default on next run; otherwise just record the error.
fn unparseable(
    path: &Path,
    name: &str,
    error: String,
    opts: &DoctorOptions,
    repairs: &mut Vec<String>,
) -> StateFileStatus {
    let backed_up_to = if opts.repair {
        // Don't clobber a previous backup — keeps the "never delete" promise
        // honest if the same file goes corrupt twice. First backup gets the
        // plain name; a collision falls back to an epoch-suffixed one.
        let plain = path.with_file_name(format!("{name}.corrupt.bak"));
        let bak = if plain.exists() {
            let epoch = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map(|d| d.as_secs())
                .unwrap_or(0);
            path.with_file_name(format!("{name}.corrupt.{epoch}.bak"))
        } else {
            plain
        };
        match std::fs::rename(path, &bak) {
            Ok(()) => {
                repairs.push(format!("backed up unparseable {name}{}", bak.display()));
                Some(bak.display().to_string())
            }
            Err(err) => {
                repairs.push(format!("failed to back up {name}: {err}"));
                None
            }
        }
    } else {
        None
    };
    StateFileStatus::Unparseable {
        error,
        backed_up_to,
    }
}

fn check_models(
    models_dir: &Path,
    opts: &DoctorOptions,
    repairs: &mut Vec<String>,
) -> Vec<ModelCheck> {
    let Ok(entries) = std::fs::read_dir(models_dir) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for entry in entries.filter_map(Result::ok) {
        let dir = entry.path();
        if !dir.is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        // Skip dirs with no weight files of their own: a managed MLX dir is
        // often just a config stub whose weights live in the HF snapshot cache,
        // and flagging that as broken would be a false positive. We only assess
        // weights that are actually present here.
        if let Some(status) = check_one_model(&dir, opts, &name, repairs) {
            out.push(ModelCheck { name, status });
        }
    }
    out.sort_by(|a, b| a.name.cmp(&b.name));
    out
}

fn check_one_model(
    dir: &Path,
    opts: &DoctorOptions,
    name: &str,
    repairs: &mut Vec<String>,
) -> Option<ModelStatus> {
    let weights = weight_files(dir);
    if weights.is_empty() {
        // No weight file of any kind — not even a dangling symlink (those DO
        // show up in `weight_files` and are caught as Corrupt below). Two very
        // different situations share this shape:
        //
        //   1. the dir isn't a model install at all — none of our business, and
        //      flagging it would be the false positive the old blanket `None`
        //      was protecting against;
        //   2. an install that got interrupted before its weights landed:
        //      `config.json` and the tokenizer stubs are there, the
        //      `*.safetensors` never arrived.
        //
        // Case 2 is exactly what a Ctrl-C'd `car models pull` leaves, and
        // returning `None` for it is what made a broken install read as
        // "Healthy" (Parslee-ai/car#616). Tell them apart on whether the dir
        // carries a model manifest.
        if is_interrupted_install(dir) {
            return Some(ModelStatus::Incomplete {
                detail: format!(
                    "manifest linked into the HuggingFace cache but no weights resolve — \
                     re-pull with `car models pull {name}`"
                ),
            });
        }
        return None;
    }
    let mut bad_files = Vec::new();
    for w in &weights {
        let corrupt = if opts.deep {
            verify_cache_file(w) == CacheIntegrity::Corrupt
        } else {
            !cache_file_usable(w)
        };
        if corrupt {
            bad_files.push(
                w.file_name()
                    .unwrap_or_default()
                    .to_string_lossy()
                    .to_string(),
            );
        }
    }
    if bad_files.is_empty() {
        return Some(ModelStatus::Healthy);
    }
    let purged = if opts.repair {
        let n = purge_corrupt_cache_files(dir);
        if n > 0 {
            repairs.push(format!(
                "purged {n} corrupt file(s) from model '{name}' — re-pull with `car models pull {name}`"
            ));
        }
        n
    } else {
        0
    };
    Some(ModelStatus::Corrupt { bad_files, purged })
}

/// Weight files (`.safetensors` / `.gguf`) anywhere under a model dir. Recurses
/// to full depth so detection matches `purge_corrupt_cache_files`' recursion —
/// a corrupt weight nested ≥2 levels down (uncommon but possible) is still seen.
/// Cheap: no hashing here, just extension matching.
/// Is this a managed dir left half-built by an interrupted pull?
///
/// Called only for dirs with no weight file of any kind. Distinguishing an
/// interrupted install from a directory that was never a model needs care,
/// because over-eager flagging here is a known past false positive — see
/// `config_only_stub_is_skipped_not_flagged`, which pins a hand-made
/// config-only dir as *not* broken.
///
/// The discriminator is **how the manifest got there**. `car models pull`
/// populates a managed dir by symlinking into the HuggingFace snapshot cache
/// (`registry.rs`, "try symlink first"), writing the small config/tokenizer
/// files before the multi-gigabyte weights. So a dir that holds symlinked
/// manifest files but no resolvable weights is one CAR built and did not
/// finish — the exact residue of a Ctrl-C'd pull. A hand-made stub, or one
/// created by the copy fallback, has real files and no symlinks, and is left
/// alone.
///
/// Deliberately conservative: it under-reports (a stub whose links were later
/// cleaned up reads as "not a model") rather than resurrecting the false
/// positive. Weight *presence* uses the same `mlx_dir_has_weights` predicate
/// the loader gates on, so the diagnosis and the runtime agree — the whole
/// point of Parslee-ai/car#616, where `ensure_local` re-downloaded a stub the
/// doctor was calling healthy.
fn is_interrupted_install(dir: &Path) -> bool {
    const MANIFESTS: &[&str] = &[
        "config.json",
        "model_index.json",
        "tokenizer.json",
        "tokenizer_config.json",
        "model.safetensors.index.json",
    ];
    let has_symlinked_manifest = MANIFESTS.iter().any(|m| {
        let p = dir.join(m);
        std::fs::symlink_metadata(&p)
            .map(|meta| meta.file_type().is_symlink())
            .unwrap_or(false)
    });
    has_symlinked_manifest && !crate::registry::mlx_dir_has_weights(dir)
}

/// Zero-byte `*.jsonl` files under `~/.car/journals/`.
///
/// The daemon opens a journal per session; one that never executes a proposal
/// leaves an empty file behind and nothing reaps it, so they accumulate
/// indefinitely — 35 of 43 on the install that prompted this
/// (Parslee-ai/car#626).
///
/// Unlike the HuggingFace partials, these ARE safe for `--repair` to delete:
/// they live in CAR's own directory, a zero-length journal provably holds no
/// events, and `EventLog::load` on a missing file behaves the same as on an
/// empty one. Only exactly-zero-length files qualify — anything with a byte in
/// it is left alone.
fn find_empty_journals(home: &Path) -> Vec<PathBuf> {
    let dir = home.join("journals");
    let Ok(entries) = std::fs::read_dir(&dir) else {
        return Vec::new();
    };
    let mut out: Vec<PathBuf> = entries
        .filter_map(Result::ok)
        .filter(|e| {
            e.path().extension().and_then(|x| x.to_str()) == Some("jsonl")
                && e.metadata()
                    .map(|m| m.is_file() && m.len() == 0)
                    .unwrap_or(false)
        })
        .map(|e| e.path())
        .collect();
    out.sort();
    out
}

/// Partial downloads abandoned in the HuggingFace cache (`*.sync.part`).
///
/// Reported, **never deleted**, for two reasons. The shared HF cache belongs to
/// every tool on the machine, not just CAR (managed model dirs are only
/// symlinks into it), and a `.sync.part` may belong to a download that is
/// running *right now* — removing it would corrupt a live transfer. That also
/// keeps faith with `--repair`'s documented promise to never delete "anything
/// not provably corrupt": an in-flight partial is not corrupt, it is unfinished.
/// Surfacing the path and the size is the part that was missing
/// (Parslee-ai/car#616) — the operator decides.
///
/// Scans only `<cache>/hub/*/blobs/`, where hf-hub puts them, so this stays
/// cheap on a large cache rather than walking the whole tree.
fn find_leftovers() -> Vec<Leftover> {
    let hub = crate::registry::huggingface_cache_root();
    let mut out = Vec::new();
    let Ok(repos) = std::fs::read_dir(&hub) else {
        return out;
    };
    for repo in repos.filter_map(Result::ok) {
        let blobs = repo.path().join("blobs");
        let Ok(entries) = std::fs::read_dir(&blobs) else {
            continue;
        };
        for e in entries.filter_map(Result::ok) {
            let p = e.path();
            let is_partial = p
                .file_name()
                .and_then(|n| n.to_str())
                .map(|n| n.ends_with(".sync.part") || n.ends_with(".incomplete"))
                .unwrap_or(false);
            if !is_partial {
                continue;
            }
            // Apparent size can far exceed blocks actually allocated (these are
            // written sparsely); `len()` is what the operator sees in `ls -lh`.
            let bytes = e.metadata().map(|m| m.len()).unwrap_or(0);
            out.push(Leftover {
                path: p.display().to_string(),
                bytes,
            });
        }
    }
    out.sort_by(|a, b| b.bytes.cmp(&a.bytes).then_with(|| a.path.cmp(&b.path)));
    out
}

fn weight_files(dir: &Path) -> Vec<PathBuf> {
    fn is_weight(p: &Path) -> bool {
        matches!(
            p.extension().and_then(|e| e.to_str()),
            Some("safetensors") | Some("gguf")
        )
    }
    let mut out = Vec::new();
    let Ok(entries) = std::fs::read_dir(dir) else {
        return out;
    };
    for entry in entries.filter_map(Result::ok) {
        let p = entry.path();
        // `file_type` doesn't follow symlinks, so weight *symlinks* (the normal
        // case) are seen as files, not recursed into — only real subdirs recurse.
        if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
            out.extend(weight_files(&p));
        } else if is_weight(&p) {
            out.push(p);
        }
    }
    out
}

fn find_unrecognized(home: &Path) -> Vec<String> {
    let Ok(entries) = std::fs::read_dir(home) else {
        return Vec::new();
    };
    let mut out: Vec<String> = entries
        .filter_map(Result::ok)
        .filter_map(|e| {
            let name = e.file_name().to_string_lossy().to_string();
            let is_dir = e.file_type().map(|t| t.is_dir()).unwrap_or(false);
            let known = if is_dir {
                KNOWN_DIRS.contains(&name.as_str())
            } else {
                KNOWN_STATE_FILES.contains(&name.as_str())
                    || KNOWN_NON_JSON_FILES.contains(&name.as_str())
                    // Volatile runtime artifacts (locks, temps, backups, binary
                    // caches, append-only logs) are not "leftovers".
                    || TOLERATED_SUFFIXES.iter().any(|s| name.ends_with(s))
                    // Hidden dotfiles are config/runtime, not leftovers.
                    || name.starts_with('.')
            };
            if known {
                None
            } else {
                Some(name)
            }
        })
        .collect();
    out.sort();
    out
}

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

    fn opts(deep: bool, repair: bool) -> DoctorOptions {
        DoctorOptions { deep, repair }
    }

    #[test]
    fn clean_home_is_healthy() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("models.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join("models")).unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(r.is_healthy(), "clean home should be healthy: {r:?}");
        assert!(r.unrecognized.is_empty());
    }

    #[test]
    fn secret_index_is_recognized_not_a_leftover() {
        // The names-only secret index is a live current-version file (written by
        // the OS-keychain store on every platform). doctor once flagged it as a
        // possible older-install leftover and told the user to remove it — only
        // visible once a secret had been stored, e.g. after `car auth login` on
        // Windows. It must be recognized state, and it must parse as JSON.
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("models.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join("models")).unwrap();
        std::fs::write(tmp.path().join("secret_index.json"), r#"{"entries":[]}"#).unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(
            !r.unrecognized.contains(&"secret_index.json".to_string()),
            "secret_index.json must not be flagged as unrecognized: {:?}",
            r.unrecognized
        );
        assert!(
            r.is_healthy(),
            "home with a secret index should be healthy: {r:?}"
        );
    }

    #[test]
    fn unparseable_state_file_is_flagged_and_backed_up_on_repair() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("connectors.json"), "{not json").unwrap();

        // Read-only: flagged, not moved.
        let r = diagnose_in(tmp.path(), &opts(false, false));
        let c = r
            .state_files
            .iter()
            .find(|f| f.name == "connectors.json")
            .unwrap();
        assert!(matches!(
            c.status,
            StateFileStatus::Unparseable {
                backed_up_to: None,
                ..
            }
        ));
        assert!(!r.is_healthy());
        assert!(
            tmp.path().join("connectors.json").exists(),
            "untouched without --repair"
        );

        // Repair: moved to .corrupt.bak, original gone.
        let r = diagnose_in(tmp.path(), &opts(false, true));
        let c = r
            .state_files
            .iter()
            .find(|f| f.name == "connectors.json")
            .unwrap();
        assert!(matches!(
            c.status,
            StateFileStatus::Unparseable {
                backed_up_to: Some(_),
                ..
            }
        ));
        assert!(!tmp.path().join("connectors.json").exists());
        assert!(tmp.path().join("connectors.json.corrupt.bak").exists());
    }

    #[test]
    fn dotenv_env_file_is_never_parsed_or_moved() {
        // ~/.car/env is dotenv (KEY=VALUE), not JSON. It must be recognized
        // (not a leftover), never flagged Unparseable, and never moved aside by
        // --repair (it holds secrets).
        let tmp = TempDir::new().unwrap();
        std::fs::write(
            tmp.path().join("env"),
            "ANTHROPIC_API_KEY=sk-secret\nFOO=bar\n",
        )
        .unwrap();

        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            r.is_healthy(),
            "dotenv env must not make the install unhealthy"
        );
        assert!(
            !r.unrecognized.contains(&"env".to_string()),
            "env is recognized"
        );
        assert!(
            r.state_files.iter().all(|f| f.name != "env"),
            "env is never JSON-checked"
        );
        assert!(
            tmp.path().join("env").exists(),
            "repair must not move the secrets file"
        );
        assert!(!tmp.path().join("env.corrupt.bak").exists());
    }

    #[test]
    fn empty_state_file_is_ok() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("messaging.json"), "").unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        let c = r
            .state_files
            .iter()
            .find(|f| f.name == "messaging.json")
            .unwrap();
        assert!(matches!(c.status, StateFileStatus::Ok { .. }));
    }

    /// Parslee-ai/car#616 — the residue of an interrupted `car models pull`:
    /// the small manifest files got symlinked into the HF snapshot, the weights
    /// never arrived. Observed live as `~/.car/models/Qwen3-4B-MLX/` holding
    /// three symlinks and nothing else, while `car doctor --deep --repair`
    /// reported "none installed / ✓ Healthy".
    #[test]
    #[cfg(unix)]
    fn interrupted_pull_is_reported_not_skipped() {
        let tmp = TempDir::new().unwrap();
        // Stand in for the HF snapshot the manifests link into.
        let snap = tmp.path().join("hfsnap");
        std::fs::create_dir_all(&snap).unwrap();
        std::fs::write(snap.join("config.json"), "{}").unwrap();
        std::fs::write(snap.join("tokenizer.json"), "{}").unwrap();

        let m = tmp.path().join("models").join("Qwen3-4B-MLX");
        std::fs::create_dir_all(&m).unwrap();
        std::os::unix::fs::symlink(snap.join("config.json"), m.join("config.json")).unwrap();
        std::os::unix::fs::symlink(snap.join("tokenizer.json"), m.join("tokenizer.json")).unwrap();
        // No *.safetensors anywhere — the pull died before the weights.

        let r = diagnose_in(tmp.path(), &opts(false, false));
        let check = r
            .models
            .iter()
            .find(|c| c.name == "Qwen3-4B-MLX")
            .expect("an interrupted install must appear in the report, not be dropped");
        assert!(
            matches!(check.status, ModelStatus::Incomplete { .. }),
            "expected Incomplete, got {:?}",
            check.status
        );
        assert!(
            !r.is_healthy(),
            "a half-installed model must not read as healthy"
        );
    }

    /// The other half of #616: abandoned partial downloads were invisible.
    /// Reported with sizes, and deliberately never deleted — the HF cache is
    /// shared, and a `.sync.part` may belong to a live transfer.
    #[test]
    fn abandoned_partial_downloads_are_reported_never_deleted() {
        let hf = TempDir::new().unwrap();
        let blobs = hf.path().join("hub").join("models--x--y").join("blobs");
        std::fs::create_dir_all(&blobs).unwrap();
        let part = blobs.join("deadbeef.sync.part");
        std::fs::write(&part, vec![0u8; 4096]).unwrap();
        std::fs::write(blobs.join("finished"), b"whole").unwrap();

        let home = TempDir::new().unwrap();
        // `find_leftovers` reads HF_HOME through the registry's cache resolver.
        let prev = std::env::var_os("HF_HOME");
        std::env::set_var("HF_HOME", hf.path());
        let r = diagnose_in(home.path(), &opts(false, true));
        match prev {
            Some(v) => std::env::set_var("HF_HOME", v),
            None => std::env::remove_var("HF_HOME"),
        }

        assert_eq!(
            r.leftovers.len(),
            1,
            "expected one partial: {:?}",
            r.leftovers
        );
        assert_eq!(r.leftovers[0].bytes, 4096);
        assert!(r.leftovers[0].path.ends_with("deadbeef.sync.part"));
        assert!(
            part.exists(),
            "--repair must NOT delete a partial: the HF cache is shared and the \
             transfer may still be running"
        );
        // Wasted disk is informational, not breakage.
        assert!(r.is_healthy());
    }

    /// Parslee-ai/car#626 — `--repair` on a healthy install listed "refreshed
    /// version stamp" every time, implying it had fixed something.
    #[test]
    fn repair_does_not_report_an_unchanged_version_stamp() {
        let tmp = TempDir::new().unwrap();
        // First repair on an unstamped home: the stamp genuinely appears.
        let first = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            first.repairs.iter().any(|r| r.contains("version stamp")),
            "writing a missing stamp IS a repair: {:?}",
            first.repairs
        );
        // Second repair, nothing changed: silence.
        let second = diagnose_in(tmp.path(), &opts(false, true));
        assert!(
            !second.repairs.iter().any(|r| r.contains("version stamp")),
            "an unchanged stamp is not a repair: {:?}",
            second.repairs
        );
    }

    /// Parslee-ai/car#626 — a journal per session that never executed anything
    /// left an empty file nobody reaped (35 of 43 on the reporting install).
    /// Safe for `--repair`: zero length provably means zero events.
    #[test]
    fn empty_journals_are_reaped_on_repair_only() {
        let tmp = TempDir::new().unwrap();
        let journals = tmp.path().join("journals");
        std::fs::create_dir_all(&journals).unwrap();
        let empty = journals.join("aaaaaaaaaaaa.jsonl");
        let full = journals.join("bbbbbbbbbbbb.jsonl");
        let other = journals.join("notes.txt");
        std::fs::write(&empty, b"").unwrap();
        std::fs::write(&full, b"{\"kind\":\"proposal_received\"}\n").unwrap();
        std::fs::write(&other, b"").unwrap();

        // Read-only: nothing removed.
        let _ = diagnose_in(tmp.path(), &opts(false, false));
        assert!(empty.exists(), "no --repair, no deletion");

        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(!empty.exists(), "empty journal should be reaped");
        assert!(full.exists(), "a journal with events must be kept");
        assert!(other.exists(), "non-.jsonl files are not ours to remove");
        assert!(
            r.repairs.iter().any(|x| x.contains("empty event journal")),
            "the reap should be reported: {:?}",
            r.repairs
        );
    }

    #[test]
    fn config_only_stub_is_skipped_not_flagged() {
        // A managed dir with only a config (weights live in the HF cache) must
        // NOT be reported as broken — that was a false positive.
        let tmp = TempDir::new().unwrap();
        let m = tmp.path().join("models").join("Stub");
        std::fs::create_dir_all(&m).unwrap();
        std::fs::write(m.join("config.json"), "{}").unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(
            r.models.iter().all(|m| m.name != "Stub"),
            "stub should be skipped"
        );
        assert!(r.is_healthy());
    }

    #[cfg(unix)]
    #[test]
    fn corrupt_model_weight_is_purged_on_repair() {
        let tmp = TempDir::new().unwrap();
        let m = tmp.path().join("models").join("Qwen3-Test");
        std::fs::create_dir_all(&m).unwrap();
        // A dangling weight symlink reads as corrupt under the cheap check.
        std::os::unix::fs::symlink(m.join("gone"), m.join("model.safetensors")).unwrap();

        let r = diagnose_in(tmp.path(), &opts(false, false));
        let mc = r.models.iter().find(|m| m.name == "Qwen3-Test").unwrap();
        assert!(matches!(mc.status, ModelStatus::Corrupt { purged: 0, .. }));

        let r = diagnose_in(tmp.path(), &opts(false, true));
        let mc = r.models.iter().find(|m| m.name == "Qwen3-Test").unwrap();
        match &mc.status {
            ModelStatus::Corrupt { purged, .. } => assert_eq!(*purged, 1),
            other => panic!("expected Corrupt, got {other:?}"),
        }
        assert!(std::fs::symlink_metadata(m.join("model.safetensors")).is_err());
    }

    #[test]
    fn unrecognized_entries_are_reported_not_removed() {
        let tmp = TempDir::new().unwrap();
        std::fs::write(tmp.path().join("mystery-leftover.json"), "{}").unwrap();
        std::fs::create_dir_all(tmp.path().join("old_install_dir")).unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, true));
        assert!(r
            .unrecognized
            .contains(&"mystery-leftover.json".to_string()));
        assert!(r.unrecognized.contains(&"old_install_dir".to_string()));
        // Repair must NOT delete unrecognized entries.
        assert!(tmp.path().join("mystery-leftover.json").exists());
        assert!(tmp.path().join("old_install_dir").exists());
    }

    #[test]
    fn version_skew_detected() {
        let tmp = TempDir::new().unwrap();
        let stale = VersionStamp {
            car_version: "0.0.1-ancient".to_string(),
            state_schema_version: 1,
        };
        std::fs::write(
            tmp.path().join("version.json"),
            serde_json::to_string(&stale).unwrap(),
        )
        .unwrap();
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(r.version_skew);
        assert!(!r.is_healthy());

        // Repair refreshes the stamp to the current binary, clearing skew next run.
        let _ = diagnose_in(tmp.path(), &opts(false, true));
        let r = diagnose_in(tmp.path(), &opts(false, false));
        assert!(!r.version_skew, "stamp refreshed, skew cleared");
    }
}