vibe_coding_tracker 1.9.0

Vibe Coding Tracker - AI coding assistant telemetry/usage parser, aggregate JSONL events 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
//! 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.

use crate::cli::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::{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 providers: ProvidersConfig,
}

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

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

fn default_true() -> bool {
    true
}

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();
        };
        let mut config: Config = toml_edit::de::from_str(&text).unwrap_or_default();
        migrate_legacy(&mut config, &text);
        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()
}

/// Self-healing migration 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, so upgrading vct never silently
/// resets a trimmed panel list. The user's file is left untouched (no forced
/// rewrite); the renamed `refresh_interval` handles its own legacy key via a
/// serde `alias`.
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;
    }
}

/// 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.providers, ProvidersConfig::default());
        assert!(cfg.providers.cursor);
    }

    #[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_eq!(cfg.usage.refresh_secs(), 10);
        assert_eq!(cfg.usage.quota_refresh_secs(), 60);
    }

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

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