vibestats 2.3.1

CLI that syncs Claude Code and Codex session activity to a private GitHub repo and renders a profile heatmap + analytics dashboard.
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
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::Path;

#[derive(Debug, Serialize, Deserialize)]
pub struct Checkpoint {
    /// ISO 8601 UTC string; absent means no sync has run yet
    pub throttle_timestamp: Option<String>,
    /// "active" | "retired" | "purged"; defaults to "active"
    #[serde(default = "default_machine_status")]
    pub machine_status: String,
    /// true when last GitHub API call returned 401
    #[serde(default)]
    pub auth_error: bool,
    /// Per-date SHA256 content hashes; key = "YYYY-MM-DD"
    #[serde(default)]
    pub date_hashes: HashMap<String, String>,
}

fn default_machine_status() -> String {
    "active".to_string()
}

impl Default for Checkpoint {
    fn default() -> Self {
        Self {
            throttle_timestamp: None,
            machine_status: default_machine_status(),
            auth_error: false,
            date_hashes: HashMap::new(),
        }
    }
}

/// Parses "YYYY-MM-DDTHH:MM:SSZ" → SystemTime (UNIX_EPOCH offset).
/// Returns None on any parse error (fail-open: caller treats as no timestamp).
/// Strictly requires a trailing 'Z' and rejects out-of-range fields and pre-1970 dates.
#[cfg_attr(not(test), allow(dead_code))]
fn parse_iso8601_utc(s: &str) -> Option<std::time::SystemTime> {
    // Require explicit trailing Z — we never want to misinterpret a naive local
    // timestamp as UTC. The schema in docs/schemas.md requires the Z suffix.
    let s = s.strip_suffix('Z')?;
    let (date_str, time_str) = s.split_once('T')?;
    let mut dp = date_str.split('-');
    let year: u64 = dp.next()?.parse().ok()?;
    let month: u64 = dp.next()?.parse().ok()?;
    let day: u64 = dp.next()?.parse().ok()?;
    if dp.next().is_some() {
        return None; // extra '-' segments
    }
    let mut tp = time_str.split(':');
    let hour: u64 = tp.next()?.parse().ok()?;
    let min: u64 = tp.next()?.parse().ok()?;
    let sec: u64 = tp.next()?.parse().ok()?;
    if tp.next().is_some() {
        return None; // extra ':' segments (e.g. fractional or offset)
    }

    // Validate ranges before the civil-date math. The u64 arithmetic below
    // relies on the subtraction `- 719468` not underflowing, which requires
    // year >= 1970 (actually >= March 1970, but 1970 is a safe lower bound).
    if year < 1970 || !(1..=12).contains(&month) || !(1..=31).contains(&day) {
        return None;
    }
    if hour >= 24 || min >= 60 || sec >= 60 {
        return None;
    }

    // Days since Unix epoch (1970-01-01) via the civil date formula.
    // Source: https://howardhinnant.github.io/date_algorithms.html  (days_from_civil)
    let y = if month <= 2 { year - 1 } else { year };
    let era = y / 400;
    let yoe = y - era * 400; // [0, 399]
    let doy = (153 * (if month > 2 { month - 3 } else { month + 9 }) + 2) / 5 + day - 1; // [0, 365]
    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; // [0, 146096]
                                                     // days since 1970-01-01; safe: year >= 1970 ⇒ era*146097 + doe >= 719468.
    let days_since_epoch = era * 146097 + doe - 719468;

    let secs = days_since_epoch * 86400 + hour * 3600 + min * 60 + sec;
    Some(std::time::UNIX_EPOCH + std::time::Duration::from_secs(secs))
}

/// Formats a SystemTime as "YYYY-MM-DDTHH:MM:SSZ".
#[cfg_attr(not(test), allow(dead_code))]
fn format_iso8601_utc(t: std::time::SystemTime) -> String {
    let secs = t
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    // Reverse civil date formula (days_from_civil inverse: civil_from_days)
    // Source: https://howardhinnant.github.io/date_algorithms.html
    let z = secs / 86400;
    let time_of_day = secs % 86400;
    let h = time_of_day / 3600;
    let m = (time_of_day % 3600) / 60;
    let s = time_of_day % 60;

    let z = z + 719468;
    let era = z / 146097;
    let doe = z - era * 146097;
    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let mo = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if mo <= 2 { y + 1 } else { y };

    format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", y, mo, d, h, m, s)
}

impl Checkpoint {
    /// Load checkpoint from file; returns default if file is missing or unreadable.
    /// Never panics or exits non-zero on any error (NFR10).
    pub fn load(path: &Path) -> Self {
        std::fs::read_to_string(path)
            .ok()
            .and_then(|s| toml::from_str(&s).ok())
            .unwrap_or_default()
    }

    /// Save checkpoint to file, creating parent directories as needed.
    /// Writes atomically: serializes to a sibling `.tmp` file, then renames
    /// over the target path. This prevents a crash mid-write from producing a
    /// truncated/corrupt checkpoint file (which would lose throttle state and
    /// risk NFR2/NFR12 violations on the next run).
    /// Returns Result — callers decide whether to log or silently ignore.
    pub fn save(&self, path: &Path) -> Result<(), Box<dyn std::error::Error>> {
        let content = toml::to_string(self)?;
        if let Some(parent) = path.parent() {
            if !parent.as_os_str().is_empty() {
                std::fs::create_dir_all(parent)?;
            }
        }
        // Build a sibling temp path: "<path>.tmp". Using a sibling (same dir)
        // guarantees the rename is atomic on POSIX (same filesystem).
        let mut tmp_os = path.as_os_str().to_os_string();
        tmp_os.push(".tmp");
        let tmp_path = std::path::PathBuf::from(tmp_os);
        std::fs::write(&tmp_path, content)?;
        std::fs::rename(&tmp_path, path)?;
        Ok(())
    }

    /// Returns true if throttle_timestamp is within 5 minutes of now.
    /// Returns false if throttle_timestamp is absent or unparseable (fail-safe: allow sync).
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn should_throttle(&self) -> bool {
        let ts_str = match &self.throttle_timestamp {
            Some(ts) => ts,
            None => return false, // no timestamp → allow sync
        };
        let ts = match parse_iso8601_utc(ts_str) {
            Some(t) => t,
            None => return false, // unparseable → fail-safe: allow sync
        };
        let now = std::time::SystemTime::now();
        match now.duration_since(ts) {
            Ok(elapsed) => elapsed.as_secs() < 300, // 5 min = 300 s
            Err(_) => false,                        // clock skew (ts in future) → allow sync
        }
    }

    /// Sets throttle_timestamp to current UTC time as ISO 8601 string.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn update_throttle_timestamp(&mut self) {
        self.throttle_timestamp = Some(format_iso8601_utc(std::time::SystemTime::now()));
    }

    /// Returns true if stored hash for date equals provided hash.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn hash_matches(&self, date: &str, hash: &str) -> bool {
        self.date_hashes
            .get(date)
            .map(|stored| stored == hash)
            .unwrap_or(false)
    }

    /// Returns true if stored hash for harness/date equals provided hash.
    ///
    /// Date-only keys are kept for backward compatibility with existing
    /// Claude-only checkpoints created before harness-aware sync.
    pub fn hash_matches_for_harness(&self, harness: &str, date: &str, hash: &str) -> bool {
        let key = harness_date_key(harness, date);
        self.date_hashes
            .get(&key)
            .or_else(|| {
                if harness == "claude" {
                    self.date_hashes.get(date)
                } else {
                    None
                }
            })
            .map(|stored| stored == hash)
            .unwrap_or(false)
    }

    /// Upserts entry in date_hashes for the given date.
    #[cfg_attr(not(test), allow(dead_code))]
    pub fn update_hash(&mut self, date: &str, hash: &str) {
        self.date_hashes.insert(date.to_string(), hash.to_string());
    }

    /// Upserts entry in date_hashes for the given harness/date.
    pub fn update_hash_for_harness(&mut self, harness: &str, date: &str, hash: &str) {
        self.date_hashes
            .insert(harness_date_key(harness, date), hash.to_string());
    }

    /// Sets auth_error to true.
    pub fn set_auth_error(&mut self) {
        self.auth_error = true;
    }

    /// Sets auth_error to false.
    pub fn clear_auth_error(&mut self) {
        self.auth_error = false;
    }

    /// Returns true when machine_status == "retired".
    pub fn is_retired(&self) -> bool {
        self.machine_status == "retired"
    }

    /// Sets machine_status to the given value.
    pub fn set_machine_status(&mut self, status: &str) {
        self.machine_status = status.to_string();
    }

    /// Returns the catch-up start date derived from `date_hashes`.
    ///
    /// For harness-aware checkpoints, this returns the oldest latest date across
    /// harnesses. That prevents one successfully synced harness from masking a
    /// stale one during SessionStart catch-up.
    /// Returns `None` if `date_hashes` is empty.
    pub fn get_last_sync_date(&self) -> Option<String> {
        let mut latest_by_harness: HashMap<String, String> = HashMap::new();
        for key in self.date_hashes.keys() {
            let Some((harness, date)) = harness_and_date_from_hash_key(key) else {
                continue;
            };
            let entry = latest_by_harness
                .entry(harness)
                .or_insert_with(|| date.clone());
            if date > *entry {
                *entry = date;
            }
        }
        latest_by_harness.into_values().min()
    }
}

fn harness_date_key(harness: &str, date: &str) -> String {
    format!("{harness}:{date}")
}

fn harness_and_date_from_hash_key(key: &str) -> Option<(String, String)> {
    let (harness, date) = key.split_once(':').unwrap_or(("claude", key));
    if date.len() == 10 {
        Some((harness.to_string(), date.to_string()))
    } else {
        None
    }
}

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

    /// Produce a unique temp path per call: combines process id, test name,
    /// and a monotonic nanosecond counter. This prevents collisions between
    /// parallel test runs (cargo test is multi-threaded by default) and
    /// between concurrent repo checkouts on the same machine.
    fn temp_path(name: &str) -> PathBuf {
        use std::sync::atomic::{AtomicU64, Ordering};
        static COUNTER: AtomicU64 = AtomicU64::new(0);
        let pid = std::process::id();
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        let seq = COUNTER.fetch_add(1, Ordering::Relaxed);
        std::env::temp_dir().join(format!("vibestats_{name}_{pid}_{nanos}_{seq}.toml"))
    }

    #[test]
    fn load_missing_file_returns_default() {
        let path = temp_path("missing");
        // Ensure file really does not exist (temp_path is unique, but be defensive).
        let _ = std::fs::remove_file(&path);
        let cp = Checkpoint::load(&path);
        assert!(!cp.auth_error);
        assert_eq!(cp.machine_status, "active");
        assert!(cp.date_hashes.is_empty());
    }

    #[test]
    fn save_load_roundtrip() {
        let path = temp_path("roundtrip");
        let mut cp = Checkpoint::default();
        cp.set_auth_error();
        cp.update_hash("2026-04-10", "abc123");
        cp.save(&path).unwrap();
        let loaded = Checkpoint::load(&path);
        assert!(loaded.auth_error);
        assert!(loaded.hash_matches("2026-04-10", "abc123"));
        let _ = std::fs::remove_file(&path); // cleanup
    }

    #[test]
    fn should_throttle_recent_timestamp() {
        let mut cp = Checkpoint::default();
        cp.update_throttle_timestamp(); // sets to now
        assert!(cp.should_throttle()); // just set — must be throttled
    }

    #[test]
    fn should_throttle_old_timestamp_returns_false() {
        // Use struct-update syntax to avoid clippy::field_reassign_with_default.
        let cp = Checkpoint {
            throttle_timestamp: Some("2020-01-01T00:00:00Z".to_string()),
            ..Default::default()
        };
        assert!(!cp.should_throttle());
    }

    #[test]
    fn hash_matches_correct_and_incorrect() {
        let mut cp = Checkpoint::default();
        cp.update_hash("2026-04-10", "deadbeef");
        assert!(cp.hash_matches("2026-04-10", "deadbeef"));
        assert!(!cp.hash_matches("2026-04-10", "wronghash"));
        assert!(!cp.hash_matches("2026-04-11", "deadbeef")); // different date
    }

    #[test]
    fn harness_hashes_do_not_collide_on_same_date() {
        let mut cp = Checkpoint::default();
        cp.update_hash_for_harness("claude", "2026-05-03", "claudehash");
        cp.update_hash_for_harness("codex", "2026-05-03", "codexhash");

        assert!(cp.hash_matches_for_harness("claude", "2026-05-03", "claudehash"));
        assert!(cp.hash_matches_for_harness("codex", "2026-05-03", "codexhash"));
        assert!(!cp.hash_matches_for_harness("codex", "2026-05-03", "claudehash"));
    }

    #[test]
    fn claude_harness_matches_legacy_date_only_hash() {
        let mut cp = Checkpoint::default();
        cp.update_hash("2026-05-03", "legacyhash");

        assert!(cp.hash_matches_for_harness("claude", "2026-05-03", "legacyhash"));
        assert!(!cp.hash_matches_for_harness("codex", "2026-05-03", "legacyhash"));
    }

    #[test]
    fn auth_error_roundtrip() {
        let mut cp = Checkpoint::default();
        assert!(!cp.auth_error);
        cp.set_auth_error();
        assert!(cp.auth_error);
        cp.clear_auth_error();
        assert!(!cp.auth_error);
    }

    #[test]
    fn is_retired_variants() {
        let mut cp = Checkpoint::default();
        assert!(!cp.is_retired()); // default is "active"
        cp.set_machine_status("retired");
        assert!(cp.is_retired());
        cp.set_machine_status("purged");
        assert!(!cp.is_retired()); // purged is not the same as retired
        cp.set_machine_status("active");
        assert!(!cp.is_retired());
    }

    #[test]
    fn get_last_sync_date_empty_returns_none() {
        let cp = Checkpoint::default();
        assert!(cp.get_last_sync_date().is_none());
    }

    #[test]
    fn get_last_sync_date_returns_max_key() {
        let mut cp = Checkpoint::default();
        cp.update_hash("2026-03-10", "hash1");
        cp.update_hash("2026-04-11", "hash2");
        cp.update_hash("2026-01-01", "hash3");
        assert_eq!(cp.get_last_sync_date(), Some("2026-04-11".to_string()));
    }

    #[test]
    fn get_last_sync_date_handles_harness_keys() {
        let mut cp = Checkpoint::default();
        cp.update_hash_for_harness("claude", "2026-03-10", "hash1");
        cp.update_hash_for_harness("codex", "2026-04-12", "hash2");
        cp.update_hash("2026-04-11", "hash3");
        assert_eq!(cp.get_last_sync_date(), Some("2026-04-11".to_string()));
    }

    #[test]
    fn get_last_sync_date_single_entry() {
        let mut cp = Checkpoint::default();
        cp.update_hash("2026-04-10", "hash1");
        assert_eq!(cp.get_last_sync_date(), Some("2026-04-10".to_string()));
    }

    #[test]
    fn parse_iso8601_rejects_missing_z() {
        // Naive-looking timestamps without Z must be rejected so we never
        // misinterpret a local-time string as UTC.
        assert!(parse_iso8601_utc("2026-04-10T14:23:00").is_none());
    }

    #[test]
    fn parse_iso8601_rejects_out_of_range() {
        assert!(parse_iso8601_utc("2026-13-01T00:00:00Z").is_none()); // month 13
        assert!(parse_iso8601_utc("2026-00-01T00:00:00Z").is_none()); // month 0
        assert!(parse_iso8601_utc("2026-04-32T00:00:00Z").is_none()); // day 32
        assert!(parse_iso8601_utc("2026-04-00T00:00:00Z").is_none()); // day 0
        assert!(parse_iso8601_utc("2026-04-10T24:00:00Z").is_none()); // hour 24
        assert!(parse_iso8601_utc("2026-04-10T00:60:00Z").is_none()); // min 60
        assert!(parse_iso8601_utc("2026-04-10T00:00:60Z").is_none()); // sec 60
    }

    #[test]
    fn parse_iso8601_rejects_pre_1970() {
        // Must reject pre-epoch dates to prevent u64 underflow in the
        // civil-date arithmetic.
        assert!(parse_iso8601_utc("1969-12-31T23:59:59Z").is_none());
        assert!(parse_iso8601_utc("0001-01-01T00:00:00Z").is_none());
    }

    #[test]
    fn format_parse_iso8601_roundtrip() {
        // Formatting a SystemTime and parsing the result must yield the same
        // second-granularity instant. Guards against drift between the
        // civil-date and civil-from-days formulas.
        let now = std::time::SystemTime::now();
        let formatted = format_iso8601_utc(now);
        let parsed = parse_iso8601_utc(&formatted).expect("format output must parse");
        let now_secs = now.duration_since(std::time::UNIX_EPOCH).unwrap().as_secs();
        let parsed_secs = parsed
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert_eq!(now_secs, parsed_secs);
    }

    #[test]
    fn save_is_atomic_no_tmp_left_behind() {
        // After a successful save, no sibling .tmp file should remain.
        let path = temp_path("atomic");
        let cp = Checkpoint::default();
        cp.save(&path).unwrap();
        let mut tmp_os = path.as_os_str().to_os_string();
        tmp_os.push(".tmp");
        let tmp_path = std::path::PathBuf::from(tmp_os);
        assert!(!tmp_path.exists(), "temp file must be renamed away");
        assert!(path.exists(), "target file must exist");
        let _ = std::fs::remove_file(&path);
    }
}