vct-core 2.4.1

Vibe Coding Tracker core library - parse local AI coding assistant session data into CodeAnalysis results
Documentation
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
//! Persistent user settings (`~/.vct/config.toml`).
//!
//! A small typed [`Config`] read with serde and written back with `toml_edit`
//! so hand-added comments and any unknown keys survive programmatic edits (the
//! same "preserve what we don't own" idea as the credential write-back in
//! `quota::refresh`). Reads are infallible: a missing or malformed file falls
//! back to defaults.
//!
//! The typed structs are the single source of truth: their `#[serde(default)]`
//! values and `///` doc-comments feed both the JSON schema (via `schemars`) and
//! the commented default `config.toml` (generated by [`default_document`]), so
//! there is no hand-maintained template to drift. On the first run the generated
//! file is materialized with a `#:schema` directive pointing at the published
//! schema so schema-aware editors validate it.
//!
//! Files written by an older vct are upgraded through two layers. On load,
//! [`migrate_document`] rewrites a standard-`[header]`-table file in place —
//! adding the `#:schema` directive, renaming `refresh_interval_secs` to
//! `refresh_interval`, and moving `[usage].quota_panels` into the nested
//! `[usage.quota]` table — so an existing user actually gets the new layout
//! (`vct config migrate` forces the same pass). A read-time [`migrate_legacy`]
//! shim then backstops any residual legacy form the structural pass leaves alone
//! (e.g. a hand-edited inline `usage = { ... }` table), so the returned [`Config`]
//! is always correct even when the file was not rewritten.

use crate::models::TimeRange;
use crate::utils::{get_cache_dir, write_string_atomic};
use anyhow::Result;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::path::Path;
use toml_edit::{Array, DocumentMut, Item, Table, TableLike, value};

/// URL of the published JSON schema, referenced via a `#:schema` directive on
/// the first line of the generated `config.toml` so schema-aware TOML editors
/// (taplo / VS Code "Even Better TOML") offer autocomplete and validation.
const SCHEMA_URL: &str =
    "https://raw.githubusercontent.com/Mai0313/VibeCodingTracker/main/vct.schema.json";

/// Current layout version of `config.toml`, stamped into `[general].version`.
///
/// It exists so an upgrade can add a setting to an existing file exactly once.
/// Version 1 is any file written before the key existed.
const CONFIG_VERSION: u32 = 2;

/// Quota panels introduced after version 1, back-filled once into a file older
/// than the version that shipped them.
///
/// Only the panel a given version *added* is back-filled, so a panel the user
/// removed on purpose earlier is never resurrected. Extend this list (and bump
/// [`CONFIG_VERSION`]) when a new provider gains a panel.
const PANELS_ADDED_BY_VERSION: &[(u32, &str)] = &[(2, "grok")];

/// The full settings document.
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema)]
pub struct Config {
    #[serde(default)]
    pub general: GeneralConfig,
    #[serde(default)]
    pub usage: UsageConfig,
    #[serde(default)]
    pub analysis: AnalysisConfig,
    #[serde(default)]
    pub performance: PerformanceConfig,
    #[serde(default)]
    pub providers: ProvidersConfig,
    #[serde(default)]
    pub logging: LoggingConfig,
}

/// `[performance]` - controls for CPU-bound local scans.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
pub struct PerformanceConfig {
    /// Rayon workers used by CLI session scans. `0` selects the measured auto
    /// default; a positive value is capped at the machine's available parallelism.
    #[serde(default)]
    pub scan_threads: usize,
}

impl PerformanceConfig {
    /// Resolves the CLI scan worker count.
    ///
    /// A positive config value wins, followed by a positive
    /// `RAYON_NUM_THREADS`; otherwise auto mode uses at most two workers. Every
    /// result is capped at the available parallelism and is at least one.
    pub fn resolved_scan_threads(&self) -> usize {
        let available = std::thread::available_parallelism()
            .map(std::num::NonZeroUsize::get)
            .unwrap_or(1);
        self.resolved_scan_threads_with(
            available,
            std::env::var("RAYON_NUM_THREADS").ok().as_deref(),
        )
    }

    fn resolved_scan_threads_with(&self, available: usize, rayon_env: Option<&str>) -> usize {
        let available = available.max(1);
        let requested = if self.scan_threads > 0 {
            self.scan_threads
        } else {
            rayon_env
                .and_then(|value| value.parse::<usize>().ok())
                .filter(|value| *value > 0)
                .unwrap_or_else(|| available.min(2))
        };
        requested.clamp(1, available)
    }
}

/// `[general]` — settings shared across subcommands.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct GeneralConfig {
    /// Default time range when no --daily/--weekly/--monthly/--all flag is given.
    /// One of: "daily" | "weekly" | "monthly" | "all".
    #[serde(default)]
    pub default_time_range: TimeRange,
    /// Layout version of this file, stamped by vct. Only the upgrade pass reads
    /// it; leave it alone unless you want a past upgrade to run again.
    #[serde(
        default = "legacy_config_version",
        deserialize_with = "de_config_version"
    )]
    pub version: u32,
}

impl Default for GeneralConfig {
    fn default() -> Self {
        Self {
            default_time_range: TimeRange::default(),
            // A file this tool writes is current by construction; only a file
            // read from disk without the key is legacy (see the serde default).
            version: CONFIG_VERSION,
        }
    }
}

/// `[usage]` — usage dashboard preferences.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct UsageConfig {
    /// Start the usage dashboard with models merged across provider prefixes.
    /// Toggled live with `m`; the last state is saved back here.
    #[serde(default)]
    pub merge_models: bool,
    /// Seconds between automatic redraws of the usage TUI (minimum 1).
    #[serde(default = "default_refresh_secs")]
    pub refresh_interval: u64,
    /// Live quota-panel preferences.
    #[serde(default)]
    pub quota: QuotaConfig,
}

impl Default for UsageConfig {
    fn default() -> Self {
        Self {
            merge_models: false,
            refresh_interval: default_refresh_secs(),
            quota: QuotaConfig::default(),
        }
    }
}

impl UsageConfig {
    /// The usage TUI redraw cadence, clamped to a sane minimum so a `0` cannot
    /// busy-loop.
    pub fn refresh_secs(&self) -> u64 {
        self.refresh_interval.max(1)
    }

    /// The live quota-panel poll cadence, clamped to a sane minimum.
    pub fn quota_refresh_secs(&self) -> u64 {
        self.quota.refresh_interval.max(1)
    }

    /// Whether the quota panel for `provider` is enabled (case-insensitive).
    pub fn shows_quota_panel(&self, provider: &str) -> bool {
        quota_panel_selected(&self.quota.panels, provider)
    }
}

/// `[usage.quota]` — live quota-panel preferences.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct QuotaConfig {
    /// Which live quota panels to show in the usage TUI (by provider name:
    /// `claude` / `codex` / `copilot` / `cursor` / `grok`). An empty list hides
    /// every quota card; the Provider Usage pane has its own `p` toggle.
    #[serde(default = "default_quota_panels")]
    pub panels: Vec<String>,
    /// Seconds between live quota-panel polls, shared by every provider
    /// (minimum 1). Higher is safer against a provider's rate limits.
    #[serde(default = "default_quota_refresh_secs")]
    pub refresh_interval: u64,
}

impl Default for QuotaConfig {
    fn default() -> Self {
        Self {
            panels: default_quota_panels(),
            refresh_interval: default_quota_refresh_secs(),
        }
    }
}

/// Whether `name` is one of the selected quota-panel names (case-insensitive).
///
/// The single home for the panel-selection rule, shared by
/// [`UsageConfig::shows_quota_panel`] and the usage TUI's panel masking.
pub fn quota_panel_selected(panels: &[String], name: &str) -> bool {
    panels.iter().any(|p| p.eq_ignore_ascii_case(name))
}

/// `[analysis]` — analysis dashboard preferences.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct AnalysisConfig {
    /// Seconds between automatic redraws of the analysis TUI (minimum 1).
    #[serde(default = "default_refresh_secs")]
    pub refresh_interval: u64,
}

impl Default for AnalysisConfig {
    fn default() -> Self {
        Self {
            refresh_interval: default_refresh_secs(),
        }
    }
}

impl AnalysisConfig {
    /// The refresh cadence, clamped to a sane minimum so a `0` cannot busy-loop.
    pub fn refresh_secs(&self) -> u64 {
        self.refresh_interval.max(1)
    }
}

/// `[providers]` — per-provider include toggles.
///
/// Each provider defaults to `true`; setting one to `false` skips it entirely
/// (no directory scan, no API) in both the usage and analysis roll-ups.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
pub struct ProvidersConfig {
    #[serde(default = "default_true")]
    pub claude: bool,
    #[serde(default = "default_true")]
    pub codex: bool,
    #[serde(default = "default_true")]
    pub copilot: bool,
    #[serde(default = "default_true")]
    pub gemini: bool,
    #[serde(default = "default_true")]
    pub opencode: bool,
    #[serde(default = "default_true")]
    pub cursor: bool,
    #[serde(default = "default_true")]
    pub hermes: bool,
    #[serde(default = "default_true")]
    pub grok: bool,
}

impl Default for ProvidersConfig {
    fn default() -> Self {
        Self {
            claude: true,
            codex: true,
            copilot: true,
            gemini: true,
            opencode: true,
            cursor: true,
            hermes: true,
            grok: true,
        }
    }
}

/// `[logging]` — file logging preferences.
///
/// Diagnostics are written to `~/.vct/logs/vct-YYYY-MM-DD.log` (plain text, one
/// line per record). Nothing is ever printed to the terminal, so the TUI is
/// never disturbed. The log file is created lazily on the first record, so a
/// command that logs nothing never touches `~/.vct`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, JsonSchema)]
pub struct LoggingConfig {
    /// Minimum level written to the log file.
    /// One of: "off" | "error" | "warn" | "info" | "debug" | "trace".
    #[serde(default)]
    pub level: LogLevel,
    /// Days of daily log files to keep; older `vct-*.log` files are pruned on
    /// startup. `0` keeps every file.
    #[serde(default = "default_log_retention_days")]
    pub retention_days: u32,
}

impl Default for LoggingConfig {
    fn default() -> Self {
        Self {
            level: LogLevel::default(),
            retention_days: default_log_retention_days(),
        }
    }
}

/// Minimum severity written to the log file.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    /// Disable file logging entirely.
    Off,
    /// Only errors.
    Error,
    /// Errors and warnings (the default — quiet when healthy, records problems).
    #[default]
    Warn,
    /// Adds high-level informational breadcrumbs.
    Info,
    /// Adds verbose diagnostics (per-file parse skips, quota poll detail).
    Debug,
    /// Everything, including cache-hit traces.
    Trace,
}

fn default_true() -> bool {
    true
}

fn default_log_retention_days() -> u32 {
    7
}

fn default_refresh_secs() -> u64 {
    10
}

fn default_quota_refresh_secs() -> u64 {
    60
}

/// The version a file carrying no `[general].version` key predates.
fn legacy_config_version() -> u32 {
    1
}

/// Reads the version marker, mapping a hand-edited non-integer (`version = "2"`)
/// onto the legacy value instead of rejecting it.
///
/// Rejection would fail the whole document, and the infallible read then turns
/// that into a silent reset of every setting — the same trap
/// [`rename_refresh_key`] drops malformed values to avoid. Reading it as legacy
/// makes the upgrade pass rewrite the key with a real integer.
fn de_config_version<'de, D>(deserializer: D) -> Result<u32, D::Error>
where
    D: serde::Deserializer<'de>,
{
    Ok(Value::deserialize(deserializer)
        .ok()
        .and_then(|v| v.as_u64())
        .and_then(|n| u32::try_from(n).ok())
        .unwrap_or_else(legacy_config_version))
}

fn default_quota_panels() -> Vec<String> {
    ["claude", "codex", "copilot", "cursor", "grok"]
        .iter()
        .map(|s| s.to_string())
        .collect()
}

/// Loads settings from `~/.vct/config.toml`, creating it with defaults on first
/// run.
///
/// Infallible: any error resolving, reading, or parsing degrades to
/// [`Config::default`].
pub fn load() -> Config {
    match get_cache_dir() {
        Ok(dir) => load_in(&dir),
        Err(_) => Config::default(),
    }
}

/// [`load`] rooted at an explicit directory (test seam).
pub fn load_in(dir: &Path) -> Config {
    let path = dir.join("config.toml");
    if path.exists() {
        let Ok(text) = std::fs::read_to_string(&path) else {
            return Config::default();
        };
        // Auto-migrate a legacy-format file in place so existing users pick up the
        // renamed keys, the `[usage.quota]` nesting, and the `#:schema` directive.
        // Best-effort: a failed write (e.g. a read-only home) still yields a
        // correct in-memory Config below. Malformed TOML is never overwritten.
        let effective = match migrate_text(&text) {
            Ok(Some(migrated)) => {
                let _ = write_string_atomic(&path, &migrated);
                migrated
            }
            Ok(None) => text,
            Err(_) => return Config::default(),
        };
        let mut config: Config = toml_edit::de::from_str(&effective).unwrap_or_default();
        // Backstop for any residual legacy form the structural migration leaves
        // alone (e.g. an inline `usage = { ... }` table).
        migrate_legacy(&mut config, &effective);
        return config;
    }
    // First run: materialize the generated commented template.
    let text = default_document().to_string();
    let _ = write_string_atomic(&path, &text);
    toml_edit::de::from_str(&text).unwrap_or_default()
}

/// Outcome of an explicit [`migrate_config_file`] run, surfaced by
/// `vct config migrate`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MigrationStatus {
    /// No file existed, so a fresh commented default was written.
    Created,
    /// A legacy-format file was rewritten to the current on-disk format.
    Migrated,
    /// The file was already current; nothing was written.
    AlreadyCurrent,
}

/// Migrates the `config.toml` at `path` to the current on-disk format in place,
/// creating the commented default when the file is absent. Shared by
/// `vct config migrate` and the auto-migration in [`load_in`].
pub fn migrate_config_file(path: &Path) -> Result<MigrationStatus> {
    if !path.exists() {
        write_string_atomic(path, &default_document().to_string())?;
        return Ok(MigrationStatus::Created);
    }
    let text = std::fs::read_to_string(path)?;
    match migrate_text(&text)? {
        Some(migrated) => {
            write_string_atomic(path, &migrated)?;
            Ok(MigrationStatus::Migrated)
        }
        None => Ok(MigrationStatus::AlreadyCurrent),
    }
}

/// Applies the structural migration to raw config text: `Ok(Some(new))` when it
/// changed, `Ok(None)` when already current, `Err` when the text is not valid
/// TOML (so a caller never overwrites an unparseable file with defaults).
pub fn migrate_text(text: &str) -> Result<Option<String>> {
    let mut doc: DocumentMut = text.parse()?;
    Ok(migrate_document(&mut doc).then(|| doc.to_string()))
}

/// Read-time backstop for config files written before quota settings moved into
/// `[usage.quota]`: an old `[usage].quota_panels` key is honored when the new
/// `[usage.quota].panels` key is absent, and a legacy `refresh_interval_secs` is
/// mapped onto `refresh_interval`. The on-disk file is normally rewritten by
/// [`migrate_document`] first; this shim only has to cover the forms that pass
/// leaves alone (e.g. an inline `usage = { ... }` table), keeping the in-memory
/// [`Config`] correct even when the file itself was not upgraded.
fn migrate_legacy(config: &mut Config, raw: &str) {
    let Ok(doc) = raw.parse::<DocumentMut>() else {
        return;
    };
    if let Some(usage) = doc.get("usage").and_then(Item::as_table_like) {
        // [usage].quota_panels -> [usage.quota].panels. A present new key (even
        // `panels = []`) always wins over the legacy one.
        let has_new_panels = usage
            .get("quota")
            .and_then(Item::as_table_like)
            .is_some_and(|q| q.contains_key("panels"));
        if !has_new_panels && let Some(legacy) = usage.get("quota_panels").and_then(Item::as_array)
        {
            config.usage.quota.panels = legacy
                .iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect();
        }
        migrate_refresh_secs(usage, &mut config.usage.refresh_interval);
    }
    if let Some(analysis) = doc.get("analysis").and_then(Item::as_table_like) {
        migrate_refresh_secs(analysis, &mut config.analysis.refresh_interval);
    }
}

/// Honors a legacy `refresh_interval_secs` when the new `refresh_interval` key
/// is absent from the section. This replaces a serde `alias`, which would make
/// serde reject a mid-upgrade file carrying *both* names as a duplicate field
/// and (via the infallible read) silently reset the whole config to defaults.
fn migrate_refresh_secs(section: &dyn TableLike, target: &mut u64) {
    if !section.contains_key("refresh_interval")
        && let Some(secs) = section
            .get("refresh_interval_secs")
            .and_then(Item::as_integer)
        && let Ok(v) = u64::try_from(secs)
    {
        *target = v;
    }
}

/// Structural on-disk migration for a `config.toml` written by an older vct.
///
/// Operates on standard `[header]` tables only — an inline `usage = { ... }`
/// table is left to the read-time [`migrate_legacy`] shim, so this never has to
/// synthesize a header table inside an inline one. Returns whether anything
/// changed, so the caller rewrites the file at most once. Idempotent:
/// re-running on an already-migrated document returns `false`.
fn migrate_document(doc: &mut DocumentMut) -> bool {
    let schema = json_schema();
    let mut changed = false;

    // `[usage]`: rename the refresh key, then move quota_panels into the nested
    // `[usage.quota]`. Quota goes last so its `[usage.quota]` header renders
    // after every leaf key of `[usage]` (a leaf after a sub-table would be
    // invalid TOML).
    if doc.get("usage").is_some_and(Item::is_table) {
        if let Some(usage) = doc.get_mut("usage").and_then(Item::as_table_mut) {
            changed |= rename_refresh_key(usage, &schema, &["usage", "refresh_interval"]);
        }
        changed |= migrate_quota_panels(doc, &schema);
    }

    // `[analysis]`: rename the refresh key.
    if let Some(analysis) = doc.get_mut("analysis").and_then(Item::as_table_mut) {
        changed |= rename_refresh_key(analysis, &schema, &["analysis", "refresh_interval"]);
    }

    // Runs after the moves above so it sees the panel list they may have just
    // relocated into `[usage.quota]`.
    changed |= backfill_new_quota_panels(doc, &schema);

    // The `#:schema` directive on the first line drives editor autocomplete. It
    // attaches to the document's first element, so it goes last: on an empty
    // file the back-fill above is what creates that first element, and running
    // earlier would leave the directive to a second pass.
    if !has_schema_directive(doc) {
        changed |= prepend_schema_directive(doc);
    }

    changed
}

/// Adds quota panels that shipped after this file was written, exactly once.
///
/// The one-shot guarantee is `[general].version`: a file predating a panel is
/// missing it because the panel did not exist yet, not because the user removed
/// it — but only until the marker is stamped, after which a removal sticks.
/// Only the panels a version *added* are considered, so a panel the user
/// dropped before this upgrade is never resurrected either.
///
/// Two cases are deliberately left alone: an empty `panels` list (the band was
/// turned off on purpose) and a file whose `[general]` is an inline table (the
/// marker could not be written, so back-filling could not stay one-shot).
fn backfill_new_quota_panels(doc: &mut DocumentMut, schema: &Value) -> bool {
    let from_version = match doc.get("general") {
        Some(item) => {
            let Some(general) = item.as_table() else {
                // Inline `general = { ... }`: no place to stamp the marker.
                return false;
            };
            general
                .get("version")
                .and_then(Item::as_integer)
                .and_then(|v| u32::try_from(v).ok())
                .unwrap_or_else(legacy_config_version)
        }
        None => legacy_config_version(),
    };
    if from_version >= CONFIG_VERSION {
        return false;
    }

    // The list lives inside an inline table this pass never rewrites, so it
    // cannot be back-filled — and stamping the marker anyway would retire the
    // upgrade without having run it.
    if panels_out_of_reach(doc) {
        return false;
    }

    if let Some(panels) = doc
        .get_mut("usage")
        .and_then(Item::as_table_mut)
        .and_then(|usage| usage.get_mut("quota"))
        .and_then(Item::as_table_mut)
        .and_then(|quota| quota.get_mut("panels"))
        .and_then(Item::as_array_mut)
        // An empty list hides the whole band; adding to it would undo that.
        .filter(|panels| !panels.is_empty())
    {
        let missing: Vec<&str> = PANELS_ADDED_BY_VERSION
            .iter()
            .filter(|(version, _)| from_version < *version)
            .map(|(_, name)| *name)
            .filter(|name| {
                !panels
                    .iter()
                    .filter_map(|p| p.as_str())
                    .any(|p| p.eq_ignore_ascii_case(name))
            })
            .collect();
        for name in missing {
            panels.push(name);
        }
    }

    stamp_config_version(doc, schema);
    true
}

/// Whether the effective panel list sits inside an inline table.
///
/// [`migrate_document`] deliberately leaves inline tables alone, so such a list
/// can be neither read nor extended here — the read-time [`migrate_legacy`] shim
/// is what keeps it working. A file without a panel list at all is *not* out of
/// reach: it simply picks up the current default, new names included.
fn panels_out_of_reach(doc: &DocumentMut) -> bool {
    let Some(usage) = doc.get("usage") else {
        return false;
    };
    let holds_panels = |table: &dyn TableLike| {
        table.contains_key("quota_panels")
            || table
                .get("quota")
                .and_then(Item::as_table_like)
                .is_some_and(|quota| quota.contains_key("panels"))
    };
    match usage.as_table() {
        // `usage = { ... }`: nothing under it can be rewritten.
        None => usage.as_table_like().is_some_and(holds_panels),
        Some(usage) => {
            // A standard `[usage]` whose `quota` child is inline.
            let inline_quota = usage
                .get("quota")
                .filter(|quota| !quota.is_table())
                .and_then(Item::as_table_like)
                .is_some_and(|quota| quota.contains_key("panels"));
            // Or a legacy `quota_panels` that `migrate_quota_panels` declined to
            // move (it also refuses an inline `quota` sibling), which leaves the
            // effective list somewhere this pass cannot extend.
            inline_quota || usage.contains_key("quota_panels")
        }
    }
}

/// Writes `[general].version` (creating the table when a hand-written file has
/// no `[general]` section at all).
fn stamp_config_version(doc: &mut DocumentMut, schema: &Value) {
    if doc.get("general").is_none() {
        let mut table = Table::new();
        table.set_implicit(false);
        if let Some(desc) = schema_description(schema, &["general"]) {
            table
                .decor_mut()
                .set_prefix(format!("\n{}", comment_block(&desc)));
        }
        doc.insert("general", Item::Table(table));
    }
    let Some(general) = doc.get_mut("general").and_then(Item::as_table_mut) else {
        return;
    };
    let had_key = general.contains_key("version");
    general.insert("version", value(i64::from(CONFIG_VERSION)));
    if !had_key {
        apply_comment(general, "version", "", schema, &["general", "version"]);
    }
}

/// Whether the document already carries a `#:schema` directive line.
fn has_schema_directive(doc: &DocumentMut) -> bool {
    // Only the first non-blank line can be a real directive; scanning every line
    // would false-positive on a `#:schema`-prefixed line buried inside a
    // multi-line string value or a later comment, wrongly skipping the prepend.
    doc.to_string()
        .lines()
        .find(|line| !line.trim().is_empty())
        .is_some_and(|line| line.trim_start().starts_with("#:schema"))
}

/// Prepends the `#:schema` directive to the document's leading trivia (the
/// prefix decor of its first element). Returns whether it was added.
fn prepend_schema_directive(doc: &mut DocumentMut) -> bool {
    let directive = format!("#:schema {SCHEMA_URL}\n");
    let root = doc.as_table_mut();
    let Some(first_key) = root.iter().next().map(|(k, _)| k.to_string()) else {
        return false;
    };
    if let Some(item) = root.get_mut(&first_key)
        && let Some(table) = item.as_table_mut()
    {
        let existing = decor_prefix(table.decor());
        table
            .decor_mut()
            .set_prefix(format!("{directive}{existing}"));
        return true;
    }
    if let Some(mut km) = root.key_mut(&first_key) {
        let existing = decor_prefix(km.leaf_decor());
        km.leaf_decor_mut()
            .set_prefix(format!("{directive}{existing}"));
        return true;
    }
    false
}

/// The existing prefix text of a decor, or an empty string.
fn decor_prefix(decor: &toml_edit::Decor) -> String {
    decor
        .prefix()
        .and_then(|p| p.as_str())
        .unwrap_or("")
        .to_string()
}

/// Within `table`, migrate a legacy `refresh_interval_secs` to the current
/// `refresh_interval`: rename when only the old key is present, or drop the old
/// key when both coexist (a mid-upgrade file where the new key already wins).
///
/// A malformed legacy value (negative, float, string) is **dropped**, not
/// promoted: writing it into the typed `refresh_interval` field would make serde
/// reject the whole migrated file and silently reset every setting to defaults.
/// Dropping it lets the typed default apply, matching the pre-migration read.
fn rename_refresh_key(table: &mut Table, schema: &Value, comment_path: &[&str]) -> bool {
    if !table.contains_key("refresh_interval_secs") {
        return false;
    }
    // Both present: the new key already wins on read, so just drop the stale one.
    if table.contains_key("refresh_interval") {
        table.remove("refresh_interval_secs");
        return true;
    }
    let Some((old_key, item)) = table.remove_entry("refresh_interval_secs") else {
        return false;
    };
    if let Some(secs) = item.as_integer().and_then(|n| u64::try_from(n).ok()) {
        table.insert("refresh_interval", value(secs as i64));
        // Keep a hand-added comment; otherwise apply the current schema comment.
        let existing = decor_prefix(old_key.leaf_decor());
        apply_comment(table, "refresh_interval", &existing, schema, comment_path);
    }
    true
}

/// Moves a legacy top-level `[usage].quota_panels` array into the nested
/// `[usage.quota].panels`, creating the `[usage.quota]` table (with the current
/// default `refresh_interval`) when needed. A present `[usage.quota].panels`
/// wins; the legacy key is removed once handled. An inline `quota = { ... }`
/// child is left untouched (legacy key preserved) so no data is lost trying to
/// merge into an inline table.
fn migrate_quota_panels(doc: &mut DocumentMut, schema: &Value) -> bool {
    let Some(usage) = doc.get("usage").and_then(Item::as_table) else {
        return false;
    };
    if !usage.contains_key("quota_panels") {
        return false;
    }
    if usage.get("quota").is_some_and(Item::is_inline_table) {
        return false;
    }
    let has_new_panels = usage
        .get("quota")
        .and_then(Item::as_table_like)
        .is_some_and(|q| q.contains_key("panels"));

    let usage = doc
        .get_mut("usage")
        .and_then(Item::as_table_mut)
        .expect("usage table present");
    let Some((old_key, old_item)) = usage.remove_entry("quota_panels") else {
        return false;
    };
    if has_new_panels {
        // The new `[usage.quota].panels` already wins; drop the legacy key only.
        return true;
    }
    let legacy_panels: Vec<String> = old_item
        .as_array()
        .map(|a| {
            a.iter()
                .filter_map(|v| v.as_str().map(str::to_string))
                .collect()
        })
        .unwrap_or_default();
    // Carry the legacy key's comment onto the new `panels` key.
    let comment = decor_prefix(old_key.leaf_decor());

    if usage.get("quota").and_then(Item::as_table).is_some() {
        // Existing `[usage.quota]` without a panels key: just add it.
        let quota = usage
            .get_mut("quota")
            .and_then(Item::as_table_mut)
            .expect("quota table present");
        quota.insert("panels", value(panels_array(&legacy_panels)));
        apply_comment(
            quota,
            "panels",
            &comment,
            schema,
            &["usage", "quota", "panels"],
        );
    } else {
        usage.insert(
            "quota",
            Item::Table(build_quota_table(&legacy_panels, &comment, schema)),
        );
    }
    true
}

/// A TOML array from a list of panel names.
fn panels_array(panels: &[String]) -> Array {
    panels.iter().map(String::as_str).collect()
}

/// Builds a fresh `[usage.quota]` table from the migrated panels (carrying the
/// legacy key's comment when it had one) and the current default
/// `refresh_interval`, which is brand-new so it gets the schema comment.
fn build_quota_table(panels: &[String], panels_comment: &str, schema: &Value) -> Table {
    let mut table = Table::new();
    table.set_implicit(false);
    if let Some(desc) = schema_description(schema, &["usage", "quota"]) {
        table
            .decor_mut()
            .set_prefix(format!("\n{}", comment_block(&desc)));
    }
    table.insert("panels", value(panels_array(panels)));
    apply_comment(
        &mut table,
        "panels",
        panels_comment,
        schema,
        &["usage", "quota", "panels"],
    );
    table.insert(
        "refresh_interval",
        value(default_quota_refresh_secs() as i64),
    );
    apply_comment(
        &mut table,
        "refresh_interval",
        "",
        schema,
        &["usage", "quota", "refresh_interval"],
    );
    table
}

/// Attaches a leading `#` comment to `key`, mirroring the leaf styling in
/// [`annotate_table`]: keeps a non-empty `existing` comment (a hand-added or
/// carried-over one), otherwise falls back to the field's schema `description`.
fn apply_comment(table: &mut Table, key: &str, existing: &str, schema: &Value, path: &[&str]) {
    let prefix = if existing.trim().is_empty() {
        schema_description(schema, path).map(|desc| format!("\n{}", comment_block(&desc)))
    } else {
        Some(existing.to_string())
    };
    if let Some(prefix) = prefix
        && let Some(mut km) = table.key_mut(key)
    {
        km.leaf_decor_mut().set_prefix(prefix);
    }
}

/// Walks the (inlined) JSON schema to a nested field's `description`.
fn schema_description(schema: &Value, path: &[&str]) -> Option<String> {
    let mut cur = schema;
    for key in path {
        cur = cur.get("properties")?.get(key)?;
    }
    cur.get("description")
        .and_then(Value::as_str)
        .map(str::to_string)
}

/// Persists the usage dashboard's merge toggle back to the config.
pub fn save_merge_models(enabled: bool) -> Result<()> {
    save_merge_models_in(&get_cache_dir()?, enabled)
}

/// [`save_merge_models`] rooted at an explicit directory (test seam).
pub fn save_merge_models_in(dir: &Path, enabled: bool) -> Result<()> {
    edit_in(dir, |doc| {
        // A hand-edited file could make `usage` a scalar (`usage = "bad"`);
        // replace any non-table-like value with an empty table so indexing into
        // it below cannot panic. `is_table_like` accepts both the `[usage]`
        // header form AND an inline table (`usage = { ... }`), so a valid config
        // in either form is left intact (its keys/comments preserved) — only a
        // genuine scalar is repaired.
        if !doc["usage"].is_table_like() {
            doc["usage"] = Item::Table(Table::new());
        }
        doc["usage"]["merge_models"] = value(enabled);
    })
}

/// Reads the current document (or the template when absent/malformed), applies
/// `mutate`, and writes it back atomically — preserving formatting and comments.
fn edit_in(dir: &Path, mutate: impl FnOnce(&mut DocumentMut)) -> Result<()> {
    let path = dir.join("config.toml");
    let mut doc = std::fs::read_to_string(&path)
        .ok()
        .and_then(|text| text.parse::<DocumentMut>().ok())
        .unwrap_or_else(default_document);
    mutate(&mut doc);
    write_string_atomic(&path, &doc.to_string())
}

/// The JSON schema for the settings file, used both by `vct config schema` and
/// to derive the commented default template. Subschemas are inlined so the
/// document is self-contained and each field's `description` is easy to walk.
pub fn json_schema() -> Value {
    let settings =
        schemars::generate::SchemaSettings::draft2020_12().with(|s| s.inline_subschemas = true);
    let schema = settings.into_generator().into_root_schema_for::<Config>();
    serde_json::to_value(&schema).expect("config schema serializes to JSON")
}

/// The pretty-printed JSON schema (the committed `vct.schema.json` body, also
/// what `vct config schema` prints). Ends with a trailing newline.
pub fn schema_json() -> String {
    let mut s = serde_json::to_string_pretty(&json_schema()).expect("schema serializes");
    s.push('\n');
    s
}

/// Builds the commented default `config.toml` document from the typed
/// [`Config`]: values come from [`Config::default`] (serialized via `toml_edit`),
/// per-key and per-section comments come from the schema `description`s, and the
/// `#:schema` directive is placed on the first line.
fn default_document() -> DocumentMut {
    let mut doc: DocumentMut = toml_edit::ser::to_string(&Config::default())
        .expect("default config serializes to TOML")
        .parse()
        .expect("serialized default config is valid TOML");
    let schema = json_schema();
    annotate_table(doc.as_table_mut(), &schema, true);
    doc
}

/// Recursively attaches each field's schema `description` as a leading `#`
/// comment to the matching key or sub-table of `table`. On the root table the
/// `#:schema` directive is prepended to the first section.
fn annotate_table(table: &mut Table, schema: &Value, is_root: bool) {
    let props = schema
        .get("properties")
        .and_then(Value::as_object)
        .cloned()
        .unwrap_or_default();
    let keys: Vec<String> = table.iter().map(|(k, _)| k.to_string()).collect();
    for (idx, key) in keys.iter().enumerate() {
        let field_schema = props.get(key);
        let desc = field_schema
            .and_then(|s| s.get("description"))
            .and_then(Value::as_str);
        let is_table = table
            .get(key)
            .is_some_and(|i| i.is_table() || i.is_inline_table());
        if is_table {
            let field_schema = field_schema.cloned();
            // The serializer suffixes every key with a space (right for a leaf's
            // `k = v`, but it renders a table header as `[usage ]`); trim it.
            if let Some(mut km) = table.key_mut(key) {
                km.leaf_decor_mut().set_suffix("");
            }
            if let Some(item) = table.get_mut(key)
                && let Some(sub) = as_standard_table(item)
            {
                let mut prefix = String::new();
                if is_root && idx == 0 {
                    prefix.push_str(&format!("#:schema {SCHEMA_URL}\n\n"));
                } else {
                    prefix.push('\n');
                }
                if let Some(d) = desc {
                    prefix.push_str(&comment_block(d));
                }
                sub.decor_mut().set_prefix(prefix);
                if let Some(fs) = field_schema {
                    annotate_table(sub, &fs, false);
                }
            }
        } else if let Some(d) = desc
            && let Some(mut km) = table.key_mut(key)
        {
            km.leaf_decor_mut()
                .set_prefix(format!("\n{}", comment_block(d)));
        }
    }
}

/// Coerces `item` to a standard `[header]` table, converting an inline table
/// (`{ ... }`) in place so a leading comment can be attached to its header.
fn as_standard_table(item: &mut Item) -> Option<&mut Table> {
    if item.is_inline_table()
        && let Some(inline) = item.as_inline_table().cloned()
    {
        *item = Item::Table(inline.into_table());
    }
    item.as_table_mut()
}

/// Renders a schema description as one or more `# ` comment lines (each ending
/// in a newline), so a multi-line description becomes multi-line comments.
fn comment_block(desc: &str) -> String {
    desc.lines()
        .map(|line| {
            if line.is_empty() {
                "#\n".to_string()
            } else {
                format!("# {line}\n")
            }
        })
        .collect()
}

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

    #[test]
    fn generated_template_parses_to_expected_defaults() {
        let text = default_document().to_string();
        let cfg: Config = toml_edit::de::from_str(&text).unwrap();
        assert_eq!(cfg, Config::default());
        assert!(text.starts_with(&format!("#:schema {SCHEMA_URL}")));
        assert_eq!(cfg.general.default_time_range, TimeRange::All);
        assert_eq!(cfg.usage.quota.panels, default_quota_panels());
        assert!(cfg.usage.shows_quota_panel("cursor"));
        assert!(!cfg.usage.merge_models);
        assert_eq!(cfg.usage.refresh_interval, 10);
        assert_eq!(cfg.usage.quota.refresh_interval, 60);
        assert_eq!(cfg.analysis.refresh_interval, 10);
        assert_eq!(cfg.performance.scan_threads, 0);
        assert_eq!(cfg.providers, ProvidersConfig::default());
        assert!(cfg.providers.cursor);
        assert!(cfg.providers.grok);
        assert_eq!(cfg.logging.level, LogLevel::Warn);
        assert_eq!(cfg.logging.retention_days, 7);
    }

    #[test]
    fn missing_sections_use_defaults() {
        // An empty file must still default the opt-out settings, which only holds
        // because the section structs impl Default by hand.
        let cfg: Config = toml_edit::de::from_str("").unwrap();
        assert_eq!(cfg.usage.quota.panels, default_quota_panels());
        assert!(cfg.providers.cursor);
        assert!(cfg.providers.grok);
        assert_eq!(cfg.usage.refresh_secs(), 10);
        assert_eq!(cfg.usage.quota_refresh_secs(), 60);
        // A file with no [logging] section backfills the whole section default,
        // which is what keeps the additive section migration-free.
        assert_eq!(cfg.logging, LoggingConfig::default());
        assert_eq!(cfg.performance, PerformanceConfig::default());
    }

    #[test]
    fn scan_threads_resolve_config_then_env_then_auto() {
        let auto = PerformanceConfig { scan_threads: 0 };
        assert_eq!(auto.resolved_scan_threads_with(16, None), 2);
        assert_eq!(auto.resolved_scan_threads_with(1, None), 1);
        assert_eq!(auto.resolved_scan_threads_with(16, Some("7")), 7);
        assert_eq!(auto.resolved_scan_threads_with(4, Some("99")), 4);
        assert_eq!(auto.resolved_scan_threads_with(16, Some("0")), 2);
        assert_eq!(auto.resolved_scan_threads_with(16, Some("invalid")), 2);

        let configured = PerformanceConfig { scan_threads: 12 };
        assert_eq!(configured.resolved_scan_threads_with(8, Some("3")), 8);
    }

    #[test]
    fn partial_usage_section_keeps_quota_default() {
        let cfg: Config = toml_edit::de::from_str("[usage]\nmerge_models = true\n").unwrap();
        assert!(cfg.usage.merge_models);
        assert_eq!(cfg.usage.quota.panels, default_quota_panels());
        assert_eq!(cfg.usage.quota_refresh_secs(), 60);
    }

    #[test]
    fn quota_panels_can_be_narrowed_or_emptied() {
        let cfg: Config =
            toml_edit::de::from_str("[usage.quota]\npanels = [\"claude\"]\n").unwrap();
        assert!(cfg.usage.shows_quota_panel("claude"));
        assert!(!cfg.usage.shows_quota_panel("cursor"));

        let empty: Config = toml_edit::de::from_str("[usage.quota]\npanels = []\n").unwrap();
        assert!(!empty.usage.shows_quota_panel("claude"));
    }

    #[test]
    fn refresh_interval_reads_legacy_secs() {
        // Old files used `refresh_interval_secs`; the migration shim maps it.
        let text = "[usage]\nrefresh_interval_secs = 5\n[analysis]\nrefresh_interval_secs = 7\n";
        let mut cfg: Config = toml_edit::de::from_str(text).unwrap();
        migrate_legacy(&mut cfg, text);
        assert_eq!(cfg.usage.refresh_secs(), 5);
        assert_eq!(cfg.analysis.refresh_secs(), 7);
    }

    #[test]
    fn coexisting_refresh_keys_preserve_the_rest_of_the_config() {
        // A mid-upgrade file carrying BOTH the new and the legacy key must not
        // trip serde's duplicate-field error and reset the whole config to
        // defaults; parsing succeeds, the new key wins, and unrelated sections
        // survive.
        let text = "[general]\ndefault_time_range = \"weekly\"\n[usage]\nrefresh_interval = 5\nrefresh_interval_secs = 10\n[providers]\ncursor = false\n";
        let mut cfg: Config = toml_edit::de::from_str(text).unwrap();
        migrate_legacy(&mut cfg, text);
        assert_eq!(cfg.usage.refresh_secs(), 5);
        assert_eq!(cfg.general.default_time_range, TimeRange::Weekly);
        assert!(!cfg.providers.cursor);
    }

    #[test]
    fn migrates_legacy_quota_panels() {
        // Pre-`[usage.quota]` layout: quota_panels sat directly under [usage].
        let text = "[usage]\nquota_panels = [\"claude\"]\n";
        let mut cfg: Config = toml_edit::de::from_str(text).unwrap();
        migrate_legacy(&mut cfg, text);
        assert_eq!(cfg.usage.quota.panels, vec!["claude".to_string()]);
        assert!(!cfg.usage.shows_quota_panel("cursor"));
    }

    #[test]
    fn new_quota_panels_win_over_legacy() {
        let text = "[usage]\nquota_panels = [\"claude\"]\n[usage.quota]\npanels = []\n";
        let mut cfg: Config = toml_edit::de::from_str(text).unwrap();
        migrate_legacy(&mut cfg, text);
        assert!(cfg.usage.quota.panels.is_empty());
    }

    #[test]
    fn migrate_document_upgrades_a_full_legacy_file() {
        let legacy = "# old header\n\n[usage]\nmerge_models = false\nquota_panels = [\"claude\", \"codex\"]\nrefresh_interval_secs = 15\n\n[analysis]\nrefresh_interval_secs = 20\n";
        let migrated = migrate_text(legacy).unwrap().expect("legacy file changes");
        // The `#:schema` directive lands on the first line.
        assert!(migrated.starts_with("#:schema "));
        // Legacy keys are gone; the current nested layout is in place.
        assert!(!migrated.contains("quota_panels"));
        assert!(!migrated.contains("refresh_interval_secs"));
        assert!(migrated.contains("[usage.quota]"));
        // The user's names keep their order; panels that shipped later are
        // appended once, and the file is stamped so that only happens once.
        assert!(migrated.contains("panels = [\"claude\", \"codex\", \"grok\"]"));
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert_eq!(cfg.usage.refresh_interval, 15);
        assert_eq!(cfg.analysis.refresh_interval, 20);
        assert_eq!(
            cfg.usage.quota.panels,
            vec![
                "claude".to_string(),
                "codex".to_string(),
                "grok".to_string()
            ]
        );
        assert_eq!(cfg.usage.quota.refresh_interval, 60);
        assert_eq!(cfg.general.version, CONFIG_VERSION);
    }

    #[test]
    fn migrate_document_is_idempotent() {
        let legacy = "[usage]\nquota_panels = [\"claude\"]\nrefresh_interval_secs = 15\n";
        let once = migrate_text(legacy).unwrap().expect("first pass changes");
        // A second pass over the migrated text writes nothing.
        assert!(migrate_text(&once).unwrap().is_none());
    }

    #[test]
    fn migrate_document_noops_on_the_generated_default() {
        let current = default_document().to_string();
        assert!(migrate_text(&current).unwrap().is_none());
    }

    #[test]
    fn migrate_document_adds_only_the_schema_directive_when_keys_are_current() {
        // Current key names, nested quota and version marker, but missing the
        // `#:schema` directive.
        let text = "[general]\nversion = 2\n\n[usage]\nrefresh_interval = 10\n\n[usage.quota]\npanels = [\"claude\"]\n";
        let migrated = migrate_text(text).unwrap().expect("adds #:schema");
        assert!(migrated.starts_with("#:schema "));
        assert!(migrated.contains("refresh_interval = 10"));
        assert!(migrated.contains("panels = [\"claude\"]"));
    }

    #[test]
    fn migrate_document_drops_stale_refresh_key_when_both_present() {
        let text = "#:schema x\n[usage]\nrefresh_interval = 5\nrefresh_interval_secs = 10\n";
        let migrated = migrate_text(text).unwrap().expect("drops the legacy key");
        assert!(!migrated.contains("refresh_interval_secs"));
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert_eq!(cfg.usage.refresh_interval, 5);
    }

    #[test]
    fn migrate_document_leaves_an_inline_usage_table_to_the_read_shim() {
        // An inline `usage = { ... }` table is not restructured (only `#:schema`
        // is added), so nothing is lost trying to nest into an inline table.
        let text = "usage = { quota_panels = [\"claude\"], refresh_interval_secs = 30 }\n";
        let migrated = migrate_text(text).unwrap().expect("adds #:schema");
        assert!(migrated.starts_with("#:schema "));
        assert!(migrated.contains("quota_panels"));
        // Still idempotent for the untouched inline table.
        assert!(migrate_text(&migrated).unwrap().is_none());
    }

    #[test]
    fn migrate_text_errors_on_malformed_toml() {
        assert!(migrate_text("= not valid").is_err());
    }

    #[test]
    fn migrate_document_drops_a_malformed_legacy_refresh_value() {
        // A non-u64 legacy value must NOT be promoted into the typed field (that
        // would make serde reject the migrated file and reset every setting); it
        // is dropped so the default applies, and unrelated settings survive.
        let text = "[general]\ndefault_time_range = \"weekly\"\n[usage]\nrefresh_interval_secs = -5\n[providers]\ncursor = false\n";
        let migrated = migrate_text(text).unwrap().expect("legacy file changes");
        assert!(!migrated.contains("refresh_interval = -5"));
        assert!(!migrated.contains("refresh_interval_secs"));
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert_eq!(cfg.general.default_time_range, TimeRange::Weekly);
        assert!(!cfg.providers.cursor);
        assert_eq!(cfg.usage.refresh_interval, 10);
        // The now-clean file is stable across further passes.
        assert!(migrate_text(&migrated).unwrap().is_none());
    }

    #[test]
    fn migrate_document_preserves_a_hand_added_comment_on_a_renamed_key() {
        let text = "[usage]\n# keep me\nrefresh_interval_secs = 15\n";
        let migrated = migrate_text(text).unwrap().expect("legacy file changes");
        assert!(migrated.contains("# keep me"));
        assert!(migrated.contains("refresh_interval = 15"));
    }

    #[test]
    fn migrate_document_adds_the_directive_despite_a_buried_schema_line() {
        // A `#:schema`-prefixed line inside a string value must not be mistaken
        // for the real leading directive and skip the prepend.
        let text = "[usage]\nquota_panels = [\"claude\"]\nnote = \"\"\"\n#:schema fake\n\"\"\"\n";
        let migrated = migrate_text(text)
            .unwrap()
            .expect("adds the real directive");
        assert!(migrated.starts_with("#:schema https://"));
    }

    #[test]
    fn migrate_document_merges_panels_into_an_existing_quota_table() {
        // Legacy quota_panels + a `[usage.quota]` that has refresh_interval but no
        // panels: panels is added and the user's refresh_interval survives.
        let text = "[usage]\nquota_panels = [\"claude\"]\n\n[usage.quota]\nrefresh_interval = 30\n";
        let migrated = migrate_text(text).unwrap().expect("legacy file changes");
        assert!(!migrated.contains("quota_panels"));
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert_eq!(
            cfg.usage.quota.panels,
            vec!["claude".to_string(), "grok".to_string()]
        );
        assert_eq!(cfg.usage.quota.refresh_interval, 30);
        assert!(migrate_text(&migrated).unwrap().is_none());
    }

    #[test]
    fn migrate_document_drops_legacy_quota_panels_when_new_panels_present() {
        let text = "#:schema x\n[usage]\nquota_panels = [\"gemini\"]\n\n[usage.quota]\npanels = [\"claude\"]\n";
        let migrated = migrate_text(text).unwrap().expect("drops the legacy key");
        assert!(!migrated.contains("quota_panels"));
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert_eq!(
            cfg.usage.quota.panels,
            vec!["claude".to_string(), "grok".to_string()]
        );
    }

    #[test]
    fn migrate_document_skips_an_inline_quota_child() {
        // An inline `quota = { ... }` under `[usage]` is left untouched (with its
        // legacy sibling) rather than risk losing data merging into it — and no
        // version marker is stamped, so the file is not recorded as upgraded.
        let text =
            "#:schema x\n[usage]\nquota_panels = [\"claude\"]\nquota = { panels = [\"codex\"] }\n";
        assert!(migrate_text(text).unwrap().is_none());
        assert!(panels_out_of_reach(&text.parse::<DocumentMut>().unwrap()));
    }

    /// The one-shot contract: a panel that shipped after the file was written is
    /// added once, and removing it afterwards sticks.
    #[test]
    fn backfilled_panel_is_added_once_and_stays_removed() {
        let text = "#:schema x\n[general]\ndefault_time_range = \"all\"\n\n[usage.quota]\npanels = [\"claude\", \"codex\"]\n";
        let migrated = migrate_text(text)
            .unwrap()
            .expect("version 1 file upgrades");
        assert!(migrated.contains("panels = [\"claude\", \"codex\", \"grok\"]"));
        assert!(migrated.contains("version = 2"));
        assert!(migrate_text(&migrated).unwrap().is_none());

        // The user removes it again: the marker keeps the upgrade from re-running.
        let pruned = migrated.replace(
            "[\"claude\", \"codex\", \"grok\"]",
            "[\"claude\", \"codex\"]",
        );
        assert!(migrate_text(&pruned).unwrap().is_none());
        let cfg: Config = toml_edit::de::from_str(&pruned).unwrap();
        assert!(!cfg.usage.shows_quota_panel("grok"));
    }

    /// A panel the user dropped *before* this upgrade is not resurrected: only
    /// the names a later version introduced are back-filled.
    #[test]
    fn backfill_leaves_previously_removed_panels_alone() {
        let text = "#:schema x\n[usage.quota]\npanels = [\"claude\"]\n";
        let migrated = migrate_text(text)
            .unwrap()
            .expect("version 1 file upgrades");
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert_eq!(
            cfg.usage.quota.panels,
            vec!["claude".to_string(), "grok".to_string()],
            "codex / copilot / cursor were removed on purpose and stay removed"
        );
    }

    #[test]
    fn backfill_never_reopens_a_band_turned_off() {
        // `panels = []` hides the whole band; the upgrade must not undo that.
        let text = "#:schema x\n[usage.quota]\npanels = []\n";
        let migrated = migrate_text(text).unwrap().expect("the marker is stamped");
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert!(cfg.usage.quota.panels.is_empty());
        assert_eq!(cfg.general.version, CONFIG_VERSION);
    }

    #[test]
    fn backfill_stamps_a_file_with_no_general_section() {
        // A hand-written file may have no `[general]` at all; the marker still
        // needs somewhere to live, and the result must stay valid TOML.
        let text = "#:schema x\n[providers]\ncursor = false\n";
        let migrated = migrate_text(text).unwrap().expect("the marker is stamped");
        let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
        assert_eq!(cfg.general.version, CONFIG_VERSION);
        assert!(!cfg.providers.cursor);
        // An absent panel list simply picks up the current default.
        assert!(cfg.usage.shows_quota_panel("grok"));
        assert!(migrate_text(&migrated).unwrap().is_none());
    }

    #[test]
    fn an_empty_file_reaches_the_current_layout_in_one_pass() {
        // The back-fill creates `[general]` on a file that had no tables at all,
        // so the `#:schema` directive has to be attached after it — otherwise
        // the first pass writes a file the second pass rewrites again.
        for text in ["", "# just a comment\n"] {
            let migrated = migrate_text(text)
                .unwrap()
                .expect("an empty file is stamped");
            assert!(migrated.starts_with("#:schema "));
            assert!(migrated.contains("version = 2"));
            assert!(
                migrate_text(&migrated).unwrap().is_none(),
                "one pass must be enough"
            );
        }
    }

    #[test]
    fn a_panel_list_that_could_not_be_moved_is_not_marked_upgraded() {
        // `migrate_quota_panels` refuses to merge into an inline `quota` child,
        // so the legacy list survives out of reach. Stamping the marker here
        // would retire the one-shot upgrade without ever having run it.
        let text =
            "#:schema x\n[usage]\nquota_panels = [\"claude\"]\nquota = { refresh_interval = 30 }\n";
        assert!(migrate_text(text).unwrap().is_none());
        assert!(panels_out_of_reach(&text.parse::<DocumentMut>().unwrap()));
    }

    #[test]
    fn a_hand_edited_version_value_never_resets_the_config() {
        // A non-integer marker must read as legacy, not fail the document: the
        // infallible read would turn that into a silent reset of every setting.
        for bad in ["\"2\"", "2.5", "true", "-1"] {
            let text = format!(
                "[general]\nversion = {bad}\ndefault_time_range = \"weekly\"\n[providers]\ncursor = false\n"
            );
            let cfg: Config = toml_edit::de::from_str(&text).expect("document still parses");
            assert_eq!(cfg.general.version, legacy_config_version(), "bad = {bad}");
            assert_eq!(cfg.general.default_time_range, TimeRange::Weekly);
            assert!(!cfg.providers.cursor);
            // Being read as legacy, the upgrade pass rewrites it with a real one.
            let migrated = migrate_text(&text)
                .unwrap()
                .expect("the marker is repaired");
            let cfg: Config = toml_edit::de::from_str(&migrated).unwrap();
            assert_eq!(cfg.general.version, CONFIG_VERSION);
        }
    }

    #[test]
    fn every_backfilled_panel_ships_by_the_current_version() {
        for (version, name) in PANELS_ADDED_BY_VERSION {
            assert!(
                *version <= CONFIG_VERSION,
                "{name} is scheduled for a version this build never stamps"
            );
            assert!(
                default_quota_panels().iter().any(|p| p == name),
                "{name} is back-filled but is not a current default panel"
            );
        }
    }

    #[test]
    fn refresh_secs_clamps_zero_to_one() {
        let cfg = UsageConfig {
            refresh_interval: 0,
            quota: QuotaConfig {
                refresh_interval: 0,
                ..QuotaConfig::default()
            },
            ..UsageConfig::default()
        };
        assert_eq!(cfg.refresh_secs(), 1);
        assert_eq!(cfg.quota_refresh_secs(), 1);
    }

    #[test]
    fn providers_default_all_enabled() {
        let p = ProvidersConfig::default();
        assert!(
            p.claude
                && p.codex
                && p.copilot
                && p.gemini
                && p.opencode
                && p.cursor
                && p.hermes
                && p.grok
        );
    }

    #[test]
    fn committed_schema_matches_generated() {
        // Guards `vct.schema.json` against drift from the typed Config.
        // Regenerate with: `vct config schema > vct.schema.json`.
        let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../vct.schema.json");
        let committed: Value =
            serde_json::from_str(&std::fs::read_to_string(path).expect("vct.schema.json exists"))
                .expect("vct.schema.json is valid JSON");
        assert_eq!(committed, json_schema());
    }
}