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
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
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
//! `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",
    // Durable "this Parslee environment has no OpenRouter upstream" observation
    // (car#786). Written by whichever process first gets that gateway answer, so
    // it is absent until one does — same shape as secret_index.json above, and
    // the same reason it belongs here: an unrecognized live state file gets
    // reported as possible debris from an older install and the user is invited
    // to delete it.
    "gateway-state.json",
    // Durable "the Parslee server rejected this credential" observation
    // (car#887), the sibling of gateway-state.json above and here for exactly
    // the same reason: written only once some process has actually been
    // rejected, so it is absent on a healthy install and would otherwise be
    // reported as older-install debris on precisely the machines where it is
    // doing its job.
    "parslee-credential-state.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",
    // `car reason` state — created by car-cli, holds model_profiles.json. CAR
    // makes it on the in-process path, so it exists on any machine that has run
    // `car reason` once, and doctor was reporting a live directory as possible
    // leftover debris from an older install.
    "reason",
    "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 version that wrote the state THIS stamp replaced — the predecessor
    /// carried across the most recent upgrade.
    ///
    /// Without it, skew detection was dead on arrival (car#881): the daemon
    /// stamps on every boot and CarHost is a login item, so by the time anyone
    /// runs `car doctor` the stamp already reads as the running binary and the
    /// evidence that older state exists is gone. Observed directly — a stamp
    /// saying `0.47.0` beside an `agents.json` last written in the v0.39 era.
    ///
    /// Only updated when the version actually CHANGES. Rewriting it on every
    /// boot would collapse it to the current version and lose the real
    /// predecessor after one restart, which is the same bug one level down.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_car_version: Option<String>,
    /// The schema generation of the state this stamp replaced. Same update rule.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub previous_state_schema_version: Option<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 on a machine with no prior state.
    pub fn current() -> Self {
        VersionStamp {
            car_version: env!("CARGO_PKG_VERSION").to_string(),
            state_schema_version: STATE_SCHEMA_VERSION,
            previous_car_version: None,
            previous_state_schema_version: None,
        }
    }

    /// The stamp to write now, given what is already on disk.
    ///
    /// Carries the predecessor forward rather than overwriting it: an upgrade
    /// records what it replaced, and every later boot on the same version keeps
    /// that record instead of collapsing it to itself.
    pub fn succeeding(existing: Option<&VersionStamp>) -> Self {
        let mut next = VersionStamp::current();
        if let Some(prior) = existing {
            if prior.car_version != next.car_version
                || prior.state_schema_version != next.state_schema_version
            {
                next.previous_car_version = Some(prior.car_version.clone());
                next.previous_state_schema_version = Some(prior.state_schema_version);
            } else {
                next.previous_car_version = prior.previous_car_version.clone();
                next.previous_state_schema_version = prior.previous_state_schema_version;
            }
        }
        next
    }
}

/// What stamping observed. Returned so the daemon can act on an upgrade instead
/// of silently erasing the evidence of one.
#[derive(Debug, Clone)]
pub struct StampTransition {
    /// The stamp found on disk, if any. `None` on a fresh install — or when the
    /// file was unreadable, which is deliberately not distinguished here: both
    /// mean "no usable predecessor", and doctor reports an unparseable stamp
    /// separately.
    pub previous: Option<VersionStamp>,
    /// What was written.
    pub current: VersionStamp,
}

impl StampTransition {
    /// The package version changed since state was last written.
    pub fn upgraded(&self) -> bool {
        self.previous
            .as_ref()
            .is_some_and(|p| p.car_version != self.current.car_version)
    }

    /// On-disk state uses a schema generation NEWER than this binary
    /// understands — i.e. a downgrade.
    ///
    /// This is the case `STATE_SCHEMA_VERSION`'s own contract calls out ("older
    /// than this should refuse rather than corrupt") and that nothing acted on.
    /// A user reverting to an older CAR would silently operate on state written
    /// to a layout it does not know.
    pub fn schema_from_the_future(&self) -> bool {
        self.previous
            .as_ref()
            .is_some_and(|p| p.state_schema_version > self.current.state_schema_version)
    }
}

/// Canonical CAR **state** directory. Mirrors the resolution every other part
/// of CAR uses so `car doctor` always inspects the *same* directory the daemon
/// and registry write to.
///
/// That invariant is the whole point, and it is why this now honors `CAR_HOME`.
/// It used to refuse one, on the reasoning that "nothing else in CAR honors an
/// override, and a doctor that diagnoses a different dir than the real install
/// could report a corrupt install as healthy". The premise stopped being true
/// when `CAR_HOME` shipped: for a relocated daemon, `$CAR_HOME` *is* the real
/// install, and it is a doctor still reading `~/.car` that would grade the
/// wrong directory. The conclusion is unchanged — diagnose the install that is
/// actually running — so the resolution follows [`car_home::root_or_relative`]
/// wherever it goes.
///
/// State only, though. The same "diagnose what is running" argument cuts the
/// other way for model **weights**, which stay in the machine-shared
/// `~/.car/models` no matter where the state root points: following the
/// override there would make `car doctor` stop looking at the very cache the
/// relocated daemon loads from. [`diagnose`] therefore pairs this with
/// [`crate::default_models_dir`] instead of joining `models` onto it.
pub fn car_home() -> PathBuf {
    // `::` — this function shares its name with the crate it calls.
    ::car_home::root_or_relative()
}

/// 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<()> {
    stamp_version(car_home).map(|_| ())
}

/// Read the existing stamp, write the succeeding one, and return both.
///
/// Read-before-write is the whole point (car#881). The old `write_version_stamp`
/// overwrote unconditionally, so the daemon destroyed the record of what wrote
/// the state before anything could look at it — and `car doctor`, the only
/// reader, runs solely when a human asks. Callers that care about an upgrade
/// call this and inspect [`StampTransition`].
pub fn stamp_version(car_home: &Path) -> std::io::Result<StampTransition> {
    std::fs::create_dir_all(car_home)?;
    let previous = read_version_stamp(car_home);
    let stamp = VersionStamp::succeeding(previous.as_ref());
    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"))?;
    Ok(StampTransition {
        previous,
        current: stamp,
    })
}

/// 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,
}

/// Health of one CAR-managed Python runtime venv (`speech-runtime`,
/// `visual-runtime`).
///
/// These venvs are how CAR runs every model architecture its in-process Rust
/// MLX backend does not implement, so a broken one silently removes the entire
/// external-runtime shelf — vision, speech, and every newer LLM family — while
/// the directory still looks fully populated on disk. A venv's `bin/python` is
/// an absolute symlink into the interpreter that built it, so an ordinary
/// Homebrew upgrade (`python@3.13` rotated away) is enough to do it.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RuntimeCheck {
    /// Directory name under `CAR_HOME` (e.g. `visual-runtime`).
    pub name: String,
    pub root: String,
    /// The venv directory exists. A runtime that was never provisioned is not
    /// unhealthy — it is simply absent, and provisions on first use.
    pub present: bool,
    /// The venv's interpreter actually runs. Only meaningful when `present`.
    pub interpreter_ok: bool,
}

impl RuntimeCheck {
    /// A runtime is broken when it exists but cannot run anything. Absent is
    /// fine (lazy-provisioned); present-and-working is fine.
    pub fn is_broken(&self) -> bool {
        self.present && !self.interpreter_ok
    }
}

/// 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.
    ///
    /// Near-useless on a machine that runs the daemon: it stamps at boot, so
    /// this reads false from then on. [`DoctorReport::carried_from_version`] is
    /// the field that survives (car#881).
    pub version_skew: bool,
    /// The version that wrote the state this install carried across its most
    /// recent upgrade, when the stamp recorded one.
    ///
    /// Unlike `version_skew` this outlives the daemon's boot stamp, so "state
    /// here predates the running binary" stays answerable rather than being
    /// erased seconds after it became true.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub carried_from_version: Option<String>,
    /// On-disk state uses a schema generation NEWER than this binary knows —
    /// a downgrade. `STATE_SCHEMA_VERSION` documents that a reader older than
    /// the state "should refuse rather than corrupt"; nothing enforced it.
    #[serde(default)]
    pub schema_from_the_future: 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>,
    /// Health of the CAR-managed Python runtime venvs. Absent runtimes are
    /// omitted; only ones that exist are reported.
    #[serde(default)]
    pub runtimes: Vec<RuntimeCheck>,
    /// 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 {
        // `carried_from_version` is deliberately NOT a health signal — carrying
        // state across an upgrade is the normal case, and flagging it would make
        // every upgraded install permanently "unhealthy". Running against state
        // from a schema this binary does not know IS a problem.
        !self.schema_from_the_future
            && !self.version_skew
            && self
                .state_files
                .iter()
                .all(|f| !matches!(f.status, StateFileStatus::Unparseable { .. }))
            && self
                .models
                .iter()
                .all(|m| matches!(m.status, ModelStatus::Healthy))
            && self.runtimes.iter().all(|r| !r.is_broken())
    }
}

/// Run a diagnosis (and, if `opts.repair`, repairs) against the install that is
/// actually running: state under [`car_home`], weights under the shared cache.
///
/// The two are the same tree by default and separate under `CAR_HOME`, which is
/// why they are passed separately. A relocated daemon still loads its weights
/// from `~/.car/models` — that cache is machine-global on purpose — so a doctor
/// that only looked under the state root would silently stop checking the
/// weights, which is the failure mode `car doctor` mainly exists to catch.
pub fn diagnose(opts: &DoctorOptions) -> DoctorReport {
    diagnose_at(&car_home(), &crate::default_models_dir(), opts)
}

/// Diagnosis against an explicit base dir, weights assumed at `<home>/models` —
/// the testable core, and the shape every caller wanted before `CAR_HOME` could
/// separate the two.
pub fn diagnose_in(home: &Path, opts: &DoctorOptions) -> DoctorReport {
    diagnose_at(home, &home.join("models"), opts)
}

/// Diagnosis with the state root and the weights cache named independently.
pub fn diagnose_at(home: &Path, models_dir: &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);
    // Survives the daemon's boot stamp; `version_skew` does not.
    let carried_from_version = on_disk_stamp
        .as_ref()
        .and_then(|s| s.previous_car_version.clone());
    let schema_from_the_future = on_disk_stamp
        .as_ref()
        .is_some_and(|s| s.state_schema_version > binary.state_schema_version);

    // --- 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(models_dir, 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/"
            ));
        }
    }

    // --- managed Python runtimes --------------------------------------------
    let runtimes = check_runtimes(home);

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

/// Directory names under `CAR_HOME` that hold a CAR-managed `uv` venv.
const MANAGED_RUNTIMES: &[&str] = &["speech-runtime", "visual-runtime"];

/// Check each managed Python runtime that has actually been provisioned.
///
/// Absent runtimes are skipped rather than reported unhealthy: they provision
/// on first use, so "not there yet" is the normal state on a fresh install and
/// flagging it would make every new machine read as broken.
fn check_runtimes(home: &Path) -> Vec<RuntimeCheck> {
    MANAGED_RUNTIMES
        .iter()
        .filter_map(|name| {
            let root = home.join(name);
            if !root.exists() {
                return None;
            }
            Some(RuntimeCheck {
                name: (*name).to_string(),
                root: root.display().to_string(),
                present: true,
                interpreter_ok: crate::managed_venv::interpreter_healthy(&root),
            })
        })
        .collect()
}

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,
            previous_car_version: None,
            previous_state_schema_version: None,
        };
        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");
    }
}

#[cfg(test)]
mod version_stamp_continuity_tests {
    use super::*;

    fn write(home: &Path, stamp: &VersionStamp) {
        std::fs::create_dir_all(home).unwrap();
        std::fs::write(
            home.join("version.json"),
            serde_json::to_string_pretty(stamp).unwrap(),
        )
        .unwrap();
    }

    fn stamp(version: &str, schema: u32) -> VersionStamp {
        VersionStamp {
            car_version: version.to_string(),
            state_schema_version: schema,
            previous_car_version: None,
            previous_state_schema_version: None,
        }
    }

    /// The car#881 bug, as a test. A daemon boot used to overwrite the stamp
    /// unconditionally, so the fact that an older CAR wrote this state was gone
    /// before `car doctor` — the only reader — could ever be run.
    #[test]
    fn stamping_after_an_upgrade_preserves_what_it_replaced() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("0.39.0", 1));

        let t = stamp_version(dir.path()).unwrap();
        assert!(t.upgraded(), "0.39.0 -> current is an upgrade");
        assert_eq!(
            t.current.previous_car_version.as_deref(),
            Some("0.39.0"),
            "the predecessor must survive the stamp that replaced it"
        );

        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert_eq!(
            report.carried_from_version.as_deref(),
            Some("0.39.0"),
            "doctor must still see it AFTER the daemon stamped"
        );
    }

    /// The subtler half. Rewriting `previous` on every boot would collapse it to
    /// the current version after one restart — the same erasure, one level down.
    #[test]
    fn rebooting_on_the_same_version_keeps_the_original_predecessor() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("0.39.0", 1));

        stamp_version(dir.path()).unwrap(); // the upgrade
        for _ in 0..5 {
            stamp_version(dir.path()).unwrap(); // ordinary reboots
        }

        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert_eq!(
            report.carried_from_version.as_deref(),
            Some("0.39.0"),
            "five reboots must not rewrite the predecessor to the current version"
        );
    }

    #[test]
    fn a_fresh_install_records_no_predecessor() {
        let dir = tempfile::tempdir().unwrap();
        let t = stamp_version(dir.path()).unwrap();
        assert!(t.previous.is_none());
        assert!(!t.upgraded());
        assert!(t.current.previous_car_version.is_none());
        assert!(!diagnose_in(dir.path(), &DoctorOptions::default()).schema_from_the_future);
    }

    /// A downgrade. STATE_SCHEMA_VERSION's contract says a reader older than the
    /// state should refuse rather than corrupt; nothing acted on it before.
    #[test]
    fn state_from_a_newer_schema_is_flagged() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("99.0.0", STATE_SCHEMA_VERSION + 7));

        let t = stamp_version(dir.path()).unwrap();
        assert!(
            t.schema_from_the_future(),
            "newer on-disk schema must be flagged"
        );

        // And it must be visible to doctor as unhealthy, not merely noted.
        write(dir.path(), &stamp("99.0.0", STATE_SCHEMA_VERSION + 7));
        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert!(report.schema_from_the_future);
        assert!(!report.is_healthy());
    }

    /// Carrying state across an upgrade is the NORMAL case. Treating it as a
    /// health problem would make every upgraded install permanently unhealthy,
    /// which is how a warning gets ignored.
    #[test]
    fn carrying_state_across_an_upgrade_is_not_unhealthy() {
        let dir = tempfile::tempdir().unwrap();
        write(dir.path(), &stamp("0.39.0", STATE_SCHEMA_VERSION));
        stamp_version(dir.path()).unwrap();

        let report = diagnose_in(dir.path(), &DoctorOptions::default());
        assert!(report.carried_from_version.is_some());
        assert!(report.is_healthy(), "an ordinary upgrade is not a defect");
    }

    /// An older stamp has no `previous_*` keys at all. It must deserialize, not
    /// blow up the boot path.
    #[test]
    fn a_pre_existing_stamp_without_the_new_fields_still_loads() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path()).unwrap();
        std::fs::write(
            dir.path().join("version.json"),
            r#"{"car_version":"0.39.0","state_schema_version":1}"#,
        )
        .unwrap();

        let t = stamp_version(dir.path()).unwrap();
        assert_eq!(
            t.previous.as_ref().map(|p| p.car_version.as_str()),
            Some("0.39.0")
        );
        assert_eq!(t.current.previous_car_version.as_deref(), Some("0.39.0"));
    }

    /// A corrupt stamp must not stop the daemon stamping — it is best-effort by
    /// contract, and refusing to boot over an unreadable version file would be a
    /// far worse failure than the one it guards.
    #[test]
    fn a_corrupt_stamp_is_treated_as_absent_and_replaced() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path()).unwrap();
        std::fs::write(dir.path().join("version.json"), "{ not json").unwrap();

        let t = stamp_version(dir.path()).unwrap();
        assert!(t.previous.is_none(), "unreadable == no usable predecessor");
        assert_eq!(t.current.car_version, VersionStamp::current().car_version);
    }
}

#[cfg(test)]
mod runtime_check_tests {
    use super::*;

    /// A never-provisioned runtime is absent, not broken — a fresh install must
    /// not read as unhealthy.
    #[test]
    fn absent_runtimes_are_not_reported() {
        let dir = tempfile::tempdir().unwrap();
        assert!(check_runtimes(dir.path()).is_empty());
    }

    /// The failure this check exists for: the venv directory is fully populated
    /// but its interpreter symlink points at a Homebrew formula that is gone.
    // Unix-only because the *setup* needs a POSIX symlink, not because the
    // behaviour is. Same shape as `interrupted_pull_is_reported_not_skipped`.
    #[cfg(unix)]
    #[test]
    fn rotated_away_interpreter_is_reported_broken() {
        let dir = tempfile::tempdir().unwrap();
        let bin = dir.path().join("visual-runtime").join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::os::unix::fs::symlink(
            "/opt/homebrew/opt/python@0.0/bin/python0.0",
            bin.join("python"),
        )
        .unwrap();

        let checks = check_runtimes(dir.path());
        assert_eq!(checks.len(), 1);
        assert_eq!(checks[0].name, "visual-runtime");
        assert!(checks[0].present);
        assert!(!checks[0].interpreter_ok);
        assert!(checks[0].is_broken());
    }

    /// A broken runtime must sink `is_healthy` — the whole point is that this
    /// stops being silent.
    #[test]
    fn broken_runtime_makes_report_unhealthy() {
        let mut report = DoctorReport {
            car_home: "/tmp/x".into(),
            binary_version: VersionStamp::current().car_version,
            on_disk_stamp: None,
            version_skew: false,
            carried_from_version: None,
            schema_from_the_future: false,
            state_files: Vec::new(),
            models: Vec::new(),
            leftovers: Vec::new(),
            runtimes: Vec::new(),
            unrecognized: Vec::new(),
            repairs: Vec::new(),
        };
        assert!(report.is_healthy());

        report.runtimes.push(RuntimeCheck {
            name: "speech-runtime".into(),
            root: "/tmp/x/speech-runtime".into(),
            present: true,
            interpreter_ok: false,
        });
        assert!(!report.is_healthy());
    }
}