vct-core 2.2.3

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
//! 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";

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

/// `[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`). An empty list hides the band.
    #[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
}

fn default_quota_panels() -> Vec<String> {
    ["claude", "codex", "copilot", "cursor"]
        .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;

    // The `#:schema` directive on the first line drives editor autocomplete.
    if !has_schema_directive(doc) {
        changed |= prepend_schema_directive(doc);
    }

    // `[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"]);
    }

    changed
}

/// 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]"));
        assert!(migrated.contains("panels = [\"claude\", \"codex\"]"));
        // The user's values survive, and the quota default is filled in.
        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()]
        );
        assert_eq!(cfg.usage.quota.refresh_interval, 60);
    }

    #[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() {
        // New key names + nested quota, but missing the `#:schema` directive.
        let text = "[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()]);
        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()]);
    }

    #[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.
        let text =
            "#:schema x\n[usage]\nquota_panels = [\"claude\"]\nquota = { panels = [\"codex\"] }\n";
        assert!(migrate_text(text).unwrap().is_none());
    }

    #[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());
    }
}