vibestats 2.4.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
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
//! GitHub Contents API module for vibestats.
//!
//! Provides all HTTP calls to the GitHub Contents API.
//! No other module may make inline HTTP calls to GitHub — all GitHub HTTP
//! goes through this module (architecture constraint).
//!
//! # Responsibilities
//! - GET file SHA (to detect create vs update)
//! - PUT file (create or update via GitHub Contents API)
//! - Exponential backoff retry on 429 / 5xx / transport errors
//! - Base64 encoding of file content (std-only, no external crate)
//! - Error logging via `logger::error` before propagating errors
//!
//! # Out of scope
//! - Calling `std::process::exit` — callers handle exit (NFR10)
//! - Writing to stdout or stderr (NFR11)
//! - Reading config — caller passes token + repo as constructor args
//! - Checkpoint state — caller (`sync.rs`) manages checkpoint

// `ureq::Error` is a third-party type sized at ~272 bytes. We cannot reduce its
// size, so suppress result_large_err for this module. The retry wrapper boxes
// errors after inspecting retriability, so callers never hold large errors.
#![allow(clippy::result_large_err)]

use crate::logger;

// ─── Public types ─────────────────────────────────────────────────────────────

/// Handles all GitHub Contents API interactions for vibestats.
pub struct GithubApi {
    token: String,
    repo: String,
}

/// Type alias for error propagation throughout this module.
pub type GithubApiError = Box<dyn std::error::Error>;

// ─── Retriability helpers ─────────────────────────────────────────────────────

/// Returns `true` if an HTTP status code should trigger a retry.
///
/// Retriable: 429 (rate limit), 5xx (server error)
/// Non-retriable: 401, 404, 422, other 4xx
fn is_status_retriable(code: u16) -> bool {
    code == 429 || code >= 500
}

/// Inspect a `ureq::Error` and return `(is_retriable, boxed_error)`.
///
/// Extracts the retriability flag *before* boxing so callers don't need to
/// hold an unboxed `ureq::Error` in a `Result` (which triggers the
/// `clippy::result_large_err` lint due to `ureq::Error` being 272 bytes).
fn classify(err: ureq::Error) -> (bool, GithubApiError) {
    let retriable = match &err {
        ureq::Error::Status(code, _) => is_status_retriable(*code),
        ureq::Error::Transport(_) => true,
    };
    (retriable, Box::new(err))
}

// ─── Retry wrapper ────────────────────────────────────────────────────────────

/// Execute `f` with exponential backoff retry on retriable errors.
///
/// The closure `f` must return `Result<T, ureq::Error>` so retriability can be
/// inspected before boxing. The outer return type is `Result<T, GithubApiError>`
/// (boxed) for ergonomic use throughout the module.
///
/// Retry policy:
/// - Max 3 attempts
/// - Delay before attempt 1: 1s; before attempt 2: 2s (no delay before attempt 0)
/// - Retriable: HTTP 429, HTTP 5xx, transport errors (timeout, DNS)
/// - Non-retriable: 401, 404, other 4xx — propagates immediately
///
/// On final failure: returns the last error (boxed).
#[allow(clippy::result_large_err)]
fn with_retry<F, T>(f: F) -> Result<T, GithubApiError>
where
    F: Fn() -> Result<T, ureq::Error>,
{
    let delays_secs = [1u64, 2]; // delays BEFORE attempts 1 and 2 (not before attempt 0)
    let max_attempts: usize = 3;
    // Seed with a synthetic "retry exhausted" error so we never rely on
    // `unwrap()` in the fallthrough path. This is overwritten on every
    // retriable failure; the seed only surfaces if `max_attempts == 0`.
    let mut last_err: GithubApiError =
        Box::<dyn std::error::Error>::from("github_api: retry exhausted with no recorded error");

    for attempt in 0..max_attempts {
        // Sleep before retry (not before the first attempt)
        if attempt > 0 {
            let delay = delays_secs[attempt - 1];
            std::thread::sleep(std::time::Duration::from_secs(delay));
        }

        match f() {
            Ok(val) => return Ok(val),
            Err(e) => {
                let (retriable, boxed) = classify(e);
                if retriable {
                    last_err = boxed;
                    // continue to next attempt
                } else {
                    // Non-retriable: 401, 404, other 4xx — fail immediately
                    return Err(boxed);
                }
            }
        }
    }

    // All attempts exhausted — return the last recorded error.
    Err(last_err)
}

// ─── Constructor ──────────────────────────────────────────────────────────────

impl GithubApi {
    /// Create a new `GithubApi` instance.
    ///
    /// * `token` — GitHub personal access token (oauth_token from config)
    /// * `repo`  — Full repository name, e.g. `"owner/repo-name"` (vibestats_data_repo from config)
    pub fn new(token: &str, repo: &str) -> Self {
        Self {
            token: token.to_string(),
            repo: repo.to_string(),
        }
    }

    // ─── Public API ───────────────────────────────────────────────────────────

    /// Create or update a file in the GitHub repository.
    ///
    /// * `path`    — Full path within the repo (e.g. `machines/year=2026/month=04/day=10/.../data.json`)
    /// * `content` — Raw string content to write (will be base64-encoded before upload)
    ///
    /// Behaviour:
    /// - Calls `get_file_sha` to detect whether the file already exists.
    /// - If not found (404): creates the file (PUT without `sha`).
    /// - If found: updates the file (PUT with current `sha`).
    /// - Retries on 429 / 5xx / transport errors (exponential backoff).
    /// - On 401: logs and returns `Err` without retrying.
    pub fn put_file(&self, path: &str, content: &str) -> Result<(), GithubApiError> {
        let encoded = base64_encode(content.as_bytes());

        // Step 1: Get SHA (with retry)
        let current_sha = match with_retry(|| get_file_sha_inner(&self.token, &self.repo, path)) {
            Ok(sha) => sha,
            Err(e) => {
                logger::error(&format!(
                    "github_api: get_file_sha failed for {}: {}",
                    path, e
                ));
                return Err(e);
            }
        };

        // Step 2: PUT file (with retry)
        match with_retry(|| put_file_inner(&self.token, &self.repo, path, &encoded, &current_sha)) {
            Ok(()) => Ok(()),
            Err(e) => {
                logger::error(&format!("github_api: put_file failed for {}: {}", path, e));
                Err(e)
            }
        }
    }

    /// Retrieve the current SHA of a file in the repository.
    ///
    /// Returns:
    /// - `Ok(Some(sha))` — file exists, `sha` is the current blob SHA
    /// - `Ok(None)`      — file does not exist (404)
    /// - `Err(_)`        — network error or unexpected HTTP status
    #[allow(dead_code)] // intentionally kept: public API surface for external callers
    pub fn get_file_sha(&self, path: &str) -> Result<Option<String>, GithubApiError> {
        with_retry(|| get_file_sha_inner(&self.token, &self.repo, path))
    }

    /// Retrieve the decoded content of a file in the repository.
    ///
    /// Returns:
    /// - `Ok(Some(content))` — file exists, `content` is the decoded UTF-8 string
    /// - `Ok(None)`          — file does not exist (404)
    /// - `Err(_)`            — network error, unexpected HTTP status, or 401
    pub fn get_file_content(&self, path: &str) -> Result<Option<String>, GithubApiError> {
        with_retry(|| get_file_content_inner(&self.token, &self.repo, path))
    }

    /// Delete a file from the repository.
    ///
    /// Steps:
    /// 1. GET current SHA — if 404 (already deleted), returns `Ok(())` (idempotent).
    /// 2. DELETE using the SHA — retries on 429 / 5xx / transport errors.
    ///
    /// Returns:
    /// - `Ok(())` — file deleted (or was already absent)
    /// - `Err(_)` — network error, 401, or other non-retriable failure
    pub fn delete_file(&self, path: &str) -> Result<(), GithubApiError> {
        // Step 1: get SHA (with retry)
        let sha = match with_retry(|| get_file_sha_inner(&self.token, &self.repo, path)) {
            Ok(Some(sha)) => sha,
            Ok(None) => return Ok(()), // Already deleted — idempotent
            Err(e) => {
                logger::error(&format!(
                    "github_api: get_file_sha failed for {}: {}",
                    path, e
                ));
                return Err(e);
            }
        };
        // Step 2: DELETE (with retry)
        match with_retry(|| delete_file_inner(&self.token, &self.repo, path, &sha)) {
            Ok(()) => Ok(()),
            Err(e) => {
                logger::error(&format!(
                    "github_api: delete_file failed for {}: {}",
                    path, e
                ));
                Err(e)
            }
        }
    }

    /// List all entries (both files and subdirectories) in a directory.
    ///
    /// Returns a tuple `(files, dirs)` where each is a `Vec<String>` of paths.
    /// Returns `(vec![], vec![])` if the directory does not exist (404).
    /// Returns `Err(_)` on network or API failure.
    pub fn list_directory_all(
        &self,
        path: &str,
    ) -> Result<(Vec<String>, Vec<String>), GithubApiError> {
        with_retry(|| list_directory_all_inner(&self.token, &self.repo, path))
    }

    /// Check auth token validity by calling `GET /user`.
    ///
    /// Returns:
    /// - `Ok(login)` — token is valid; `login` is the authenticated GitHub username
    /// - `Err(_)`    — token is invalid (401) or network/server error
    ///
    /// Note: 401 is non-retriable per `is_status_retriable` — propagated immediately.
    /// 429 / 5xx / transport errors are retried via `with_retry`.
    pub fn get_user(&self) -> Result<String, GithubApiError> {
        with_retry(|| get_user_inner(&self.token))
    }
}

// ─── Internal HTTP helpers ────────────────────────────────────────────────────

/// Inner GET helper — returns `Ok(Some(sha))`, `Ok(None)` for 404, or `Err`.
///
/// Returns `ureq::Error` directly (not boxed) so `with_retry` can classify
/// the error for retriability before boxing.
#[allow(clippy::result_large_err)]
fn get_file_sha_inner(token: &str, repo: &str, path: &str) -> Result<Option<String>, ureq::Error> {
    let url = format!("https://api.github.com/repos/{}/contents/{}", repo, path);

    let response = ureq::get(&url)
        .set("Authorization", &format!("Bearer {}", token))
        .set("User-Agent", "vibestats")
        .set("Accept", "application/vnd.github+json")
        .set("X-GitHub-Api-Version", "2022-11-28")
        .call();

    match response {
        Ok(r) => {
            // 200: file exists — parse sha from response body.
            //
            // Body read and JSON parse failures must NOT be collapsed into
            // `Ok(None)`: a subsequent PUT-without-sha against an existing
            // file would return 422 from GitHub and mask a real transport
            // or server-side problem. Surface these as ureq Transport
            // errors so the retry wrapper classifies them as retriable
            // and the caller logs them.
            let body = r.into_string().map_err(ureq::Error::from)?;

            let json: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
                // Malformed JSON is a server contract violation. Wrap in a
                // synthetic io::Error so From<io::Error> yields a
                // Transport variant that with_retry will classify as
                // retriable.
                ureq::Error::from(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("github_api: malformed JSON from Contents API: {}", e),
                ))
            })?;

            Ok(json["sha"].as_str().map(|s| s.to_string()))
        }
        Err(ureq::Error::Status(404, _)) => {
            // File does not exist — first-time create path
            Ok(None)
        }
        Err(e) => Err(e),
    }
}

/// Inner PUT helper. Returns `Ok(())` on 200/201, `Err` otherwise.
///
/// Returns `ureq::Error` directly (not boxed) so `with_retry` can classify
/// the error for retriability before boxing.
#[allow(clippy::result_large_err)]
fn put_file_inner(
    token: &str,
    repo: &str,
    path: &str,
    encoded_content: &str,
    current_sha: &Option<String>,
) -> Result<(), ureq::Error> {
    let url = format!("https://api.github.com/repos/{}/contents/{}", repo, path);

    let body = if let Some(sha) = current_sha {
        serde_json::json!({
            "message": "vibestats sync",
            "content": encoded_content,
            "sha": sha
        })
        .to_string()
    } else {
        serde_json::json!({
            "message": "vibestats sync",
            "content": encoded_content
        })
        .to_string()
    };

    let response = ureq::put(&url)
        .set("Authorization", &format!("Bearer {}", token))
        .set("User-Agent", "vibestats")
        .set("Accept", "application/vnd.github+json")
        .set("X-GitHub-Api-Version", "2022-11-28")
        .set("Content-Type", "application/json")
        .send_string(&body);

    match response {
        Ok(_) => Ok(()), // 200 (update) or 201 (create) = success
        Err(e) => Err(e),
    }
}

/// Inner GET helper for file content — returns `Ok(Some(content))`, `Ok(None)` for 404, or `Err`.
///
/// Returns `ureq::Error` directly (not boxed) so `with_retry` can classify
/// the error for retriability before boxing.
#[allow(clippy::result_large_err)]
fn get_file_content_inner(
    token: &str,
    repo: &str,
    path: &str,
) -> Result<Option<String>, ureq::Error> {
    let url = format!("https://api.github.com/repos/{}/contents/{}", repo, path);

    let response = ureq::get(&url)
        .set("Authorization", &format!("Bearer {}", token))
        .set("User-Agent", "vibestats")
        .set("Accept", "application/vnd.github+json")
        .set("X-GitHub-Api-Version", "2022-11-28")
        .call();

    match response {
        Ok(r) => {
            let body = r.into_string().map_err(ureq::Error::from)?;

            let json: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
                ureq::Error::from(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("github_api: malformed JSON from Contents API: {}", e),
                ))
            })?;

            let encoded = match json["content"].as_str() {
                Some(s) => s,
                None => {
                    return Err(ureq::Error::from(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "github_api: missing content field in Contents API response",
                    )));
                }
            };

            // GitHub wraps base64 at 60 chars with newlines — strip before decoding
            let stripped = encoded.replace('\n', "");

            match base64_decode(&stripped) {
                Ok(content) => Ok(Some(content)),
                Err(e) => Err(ureq::Error::from(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("github_api: base64 decode failed: {}", e),
                ))),
            }
        }
        Err(ureq::Error::Status(404, _)) => {
            // File does not exist
            Ok(None)
        }
        Err(e) => Err(e),
    }
}

/// Inner DELETE helper. Returns `Ok(())` on success, `Err` otherwise.
///
/// Returns `ureq::Error` directly (not boxed) so `with_retry` can classify
/// the error for retriability before boxing.
#[allow(clippy::result_large_err)]
fn delete_file_inner(token: &str, repo: &str, path: &str, sha: &str) -> Result<(), ureq::Error> {
    let url = format!("https://api.github.com/repos/{}/contents/{}", repo, path);
    let body = serde_json::json!({
        "message": "vibestats: remove machine data",
        "sha": sha
    })
    .to_string();
    let response = ureq::delete(&url)
        .set("Authorization", &format!("Bearer {}", token))
        .set("User-Agent", "vibestats")
        .set("Accept", "application/vnd.github+json")
        .set("X-GitHub-Api-Version", "2022-11-28")
        .set("Content-Type", "application/json")
        .send_string(&body);
    match response {
        Ok(_) => Ok(()),
        Err(ureq::Error::Status(404, _)) => Ok(()), // already deleted — idempotent
        Err(e) => Err(e),
    }
}

/// Inner helper for listing all directory entries (files and subdirectories).
/// Returns `(files, dirs)` tuple, empty vecs for 404.
#[allow(clippy::result_large_err)]
fn list_directory_all_inner(
    token: &str,
    repo: &str,
    path: &str,
) -> Result<(Vec<String>, Vec<String>), ureq::Error> {
    let url = format!("https://api.github.com/repos/{}/contents/{}", repo, path);

    let response = ureq::get(&url)
        .set("Authorization", &format!("Bearer {}", token))
        .set("User-Agent", "vibestats")
        .set("Accept", "application/vnd.github+json")
        .set("X-GitHub-Api-Version", "2022-11-28")
        .call();

    match response {
        Ok(r) => {
            let body = r.into_string().map_err(ureq::Error::from)?;
            let json: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
                ureq::Error::from(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!(
                        "github_api: malformed JSON from Contents API directory: {}",
                        e
                    ),
                ))
            })?;
            let entries = match json.as_array() {
                Some(arr) => arr,
                None => {
                    return Err(ureq::Error::from(std::io::Error::new(
                        std::io::ErrorKind::InvalidData,
                        "github_api: directory listing response is not a JSON array",
                    )));
                }
            };
            let mut files = Vec::new();
            let mut dirs = Vec::new();
            for entry in entries {
                let entry_type = entry["type"].as_str().unwrap_or("");
                let entry_path = entry["path"].as_str().unwrap_or("").to_string();
                if !entry_path.is_empty() {
                    match entry_type {
                        "file" => files.push(entry_path),
                        "dir" => dirs.push(entry_path),
                        _ => {}
                    }
                }
            }
            Ok((files, dirs))
        }
        Err(ureq::Error::Status(404, _)) => Ok((vec![], vec![])),
        Err(e) => Err(e),
    }
}

/// Inner GET helper for GitHub `/user` endpoint — returns the authenticated user's login.
///
/// Returns `ureq::Error` directly (not boxed) so `with_retry` can classify
/// the error for retriability before boxing.
/// 401 is non-retriable per `is_status_retriable` — propagated immediately.
#[allow(clippy::result_large_err)]
fn get_user_inner(token: &str) -> Result<String, ureq::Error> {
    let url = "https://api.github.com/user";
    let response = ureq::get(url)
        .set("Authorization", &format!("Bearer {}", token))
        .set("User-Agent", "vibestats")
        .set("Accept", "application/vnd.github+json")
        .set("X-GitHub-Api-Version", "2022-11-28")
        .call();

    match response {
        Ok(r) => {
            let body = r.into_string().map_err(ureq::Error::from)?;
            let json: serde_json::Value = serde_json::from_str(&body).map_err(|e| {
                ureq::Error::from(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("github_api: malformed JSON from /user: {}", e),
                ))
            })?;
            match json["login"].as_str() {
                Some(login) => Ok(login.to_string()),
                None => Err(ureq::Error::from(std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    "github_api: missing login field in /user response",
                ))),
            }
        }
        Err(e) => Err(e),
    }
}

// ─── Base64 encoding (std-only, RFC 4648 standard alphabet) ───────────────────

/// Encode `input` bytes as standard Base64 (RFC 4648).
///
/// Uses the standard alphabet (`A–Z`, `a–z`, `0–9`, `+`, `/`) with `=` padding.
/// No external crates — stdlib only.
fn base64_encode(input: &[u8]) -> String {
    const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::new();
    let mut i = 0;

    // Process full 3-byte groups
    while i + 2 < input.len() {
        let b0 = input[i] as usize;
        let b1 = input[i + 1] as usize;
        let b2 = input[i + 2] as usize;
        out.push(ALPHABET[b0 >> 2] as char);
        out.push(ALPHABET[((b0 & 0x3) << 4) | (b1 >> 4)] as char);
        out.push(ALPHABET[((b1 & 0xf) << 2) | (b2 >> 6)] as char);
        out.push(ALPHABET[b2 & 0x3f] as char);
        i += 3;
    }

    // Handle remaining bytes with padding
    match input.len() - i {
        1 => {
            let b0 = input[i] as usize;
            out.push(ALPHABET[b0 >> 2] as char);
            out.push(ALPHABET[(b0 & 0x3) << 4] as char);
            out.push('=');
            out.push('=');
        }
        2 => {
            let b0 = input[i] as usize;
            let b1 = input[i + 1] as usize;
            out.push(ALPHABET[b0 >> 2] as char);
            out.push(ALPHABET[((b0 & 0x3) << 4) | (b1 >> 4)] as char);
            out.push(ALPHABET[(b1 & 0xf) << 2] as char);
            out.push('=');
        }
        _ => {} // 0 remaining bytes — no padding needed
    }

    out
}

// ─── Base64 decoding (std-only, RFC 4648 standard alphabet) ──────────────────

/// Decode a standard Base64 string (RFC 4648) to a UTF-8 string.
///
/// Input must NOT contain newlines — strip `\n` before calling.
/// Padding characters (`=`) are automatically stripped.
/// Returns `Err` on invalid base64 characters or invalid UTF-8 bytes.
fn base64_decode(input: &str) -> Result<String, &'static str> {
    const TABLE: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    // Build reverse lookup: 256-byte array mapping ASCII -> 6-bit value (255 = invalid)
    let mut rev = [255u8; 256];
    for (i, &c) in TABLE.iter().enumerate() {
        rev[c as usize] = i as u8;
    }
    // Strip padding before processing
    let input: Vec<u8> = input.bytes().filter(|&b| b != b'=').collect();
    let mut out = Vec::new();
    for chunk in input.chunks(4) {
        let vals: Vec<u8> = chunk.iter().map(|&b| rev[b as usize]).collect();
        if vals.contains(&255) {
            return Err("invalid base64 character");
        }
        match vals.len() {
            4 => {
                out.push((vals[0] << 2) | (vals[1] >> 4));
                out.push((vals[1] << 4) | (vals[2] >> 2));
                out.push((vals[2] << 6) | vals[3]);
            }
            3 => {
                out.push((vals[0] << 2) | (vals[1] >> 4));
                out.push((vals[1] << 4) | (vals[2] >> 2));
            }
            2 => {
                out.push((vals[0] << 2) | (vals[1] >> 4));
            }
            _ => {}
        }
    }
    String::from_utf8(out).map_err(|_| "base64 decoded bytes are not valid UTF-8")
}

// ─── Tests ────────────────────────────────────────────────────────────────────

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

    // ── base64_encode test vectors (RFC 4648) ─────────────────────────────────

    #[test]
    fn test_base64_empty() {
        assert_eq!(base64_encode(b""), "");
    }

    #[test]
    fn test_base64_one_byte() {
        // "M" → "TQ=="
        assert_eq!(base64_encode(b"M"), "TQ==");
    }

    #[test]
    fn test_base64_two_bytes() {
        // "Ma" → "TWE="
        assert_eq!(base64_encode(b"Ma"), "TWE=");
    }

    #[test]
    fn test_base64_three_bytes() {
        // "Man" → "TWFu"
        assert_eq!(base64_encode(b"Man"), "TWFu");
    }

    #[test]
    fn test_base64_four_bytes() {
        // "Many" → "TWFueQ=="
        assert_eq!(base64_encode(b"Many"), "TWFueQ==");
    }

    #[test]
    fn test_base64_hello() {
        // "hello" → "aGVsbG8="
        assert_eq!(base64_encode(b"hello"), "aGVsbG8=");
    }

    #[test]
    fn test_base64_all_zeros() {
        // 3 zero bytes → "AAAA"
        assert_eq!(base64_encode(&[0u8, 0, 0]), "AAAA");
    }

    #[test]
    fn test_base64_all_ones() {
        // 3 bytes of 0xFF → "////"
        assert_eq!(base64_encode(&[0xFFu8, 0xFF, 0xFF]), "////");
    }

    #[test]
    fn test_base64_longer_string() {
        // "Many hands make light work." → known Base64 output
        assert_eq!(
            base64_encode(b"Many hands make light work."),
            "TWFueSBoYW5kcyBtYWtlIGxpZ2h0IHdvcmsu"
        );
    }

    // ── is_status_retriable: HTTP status classification ───────────────────────

    #[test]
    fn test_status_retriable_429() {
        assert!(
            is_status_retriable(429),
            "429 (rate limit) must be retriable"
        );
    }

    #[test]
    fn test_status_retriable_500() {
        assert!(
            is_status_retriable(500),
            "500 (server error) must be retriable"
        );
    }

    #[test]
    fn test_status_retriable_503() {
        assert!(
            is_status_retriable(503),
            "503 (service unavailable) must be retriable"
        );
    }

    #[test]
    fn test_status_retriable_599() {
        assert!(is_status_retriable(599), "all 5xx must be retriable");
    }

    #[test]
    fn test_status_not_retriable_401() {
        assert!(
            !is_status_retriable(401),
            "401 (unauthorized) must NOT be retriable"
        );
    }

    #[test]
    fn test_status_not_retriable_404() {
        assert!(
            !is_status_retriable(404),
            "404 (not found) must NOT be retriable"
        );
    }

    #[test]
    fn test_status_not_retriable_422() {
        assert!(
            !is_status_retriable(422),
            "422 (unprocessable entity) must NOT be retriable"
        );
    }

    #[test]
    fn test_status_not_retriable_200() {
        assert!(!is_status_retriable(200), "200 (OK) must NOT be retriable");
    }

    #[test]
    fn test_status_not_retriable_400() {
        assert!(
            !is_status_retriable(400),
            "400 (bad request) must NOT be retriable"
        );
    }

    // ── with_retry: success on first attempt ──────────────────────────────────

    #[test]
    fn test_retry_succeeds_on_first_attempt() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let cc = call_count.clone();

        let result: Result<i32, GithubApiError> = with_retry(|| {
            cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(42)
        });

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
        assert_eq!(call_count.load(std::sync::atomic::Ordering::SeqCst), 1);
    }

    #[test]
    fn test_retry_invokes_f_exactly_once_on_success() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let cc = call_count.clone();

        let _ = with_retry::<_, ()>(|| {
            cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Ok(())
        });

        assert_eq!(
            call_count.load(std::sync::atomic::Ordering::SeqCst),
            1,
            "f should be invoked exactly once when it succeeds immediately"
        );
    }

    // ── with_retry: transport errors are retriable ────────────────────────────
    //
    // `std::io::Error` implements `From<io::Error> for ureq::Error` via the
    // public `ureq::Error::from` conversion, giving us a valid Transport variant
    // without requiring network access or test-mode server infrastructure.

    fn make_transport_error() -> ureq::Error {
        ureq::Error::from(std::io::Error::new(
            std::io::ErrorKind::ConnectionRefused,
            "simulated network error for test",
        ))
    }

    #[test]
    fn test_classify_transport_error_is_retriable() {
        let err = make_transport_error();
        let (retriable, _) = classify(err);
        assert!(
            retriable,
            "transport errors must be classified as retriable"
        );
    }

    #[test]
    fn test_retry_transport_error_exhausts_3_attempts() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let cc = call_count.clone();

        // Always return a transport error — should exhaust all 3 attempts
        let result: Result<(), GithubApiError> = with_retry(|| {
            cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            Err(make_transport_error())
        });

        assert!(result.is_err());
        assert_eq!(
            call_count.load(std::sync::atomic::Ordering::SeqCst),
            3,
            "transport error should trigger 3 total attempts (no early exit)"
        );
    }

    #[test]
    fn test_retry_succeeds_after_two_transport_errors() {
        let call_count = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
        let cc = call_count.clone();

        // Fail with transport error twice, succeed on third attempt
        let result: Result<i32, GithubApiError> = with_retry(|| {
            let n = cc.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
            if n < 2 {
                Err(make_transport_error())
            } else {
                Ok(77)
            }
        });

        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 77);
        assert_eq!(
            call_count.load(std::sync::atomic::Ordering::SeqCst),
            3,
            "should have been called exactly 3 times (2 failures + 1 success)"
        );
    }

    // ── get_file_sha: SHA parsing from JSON body ──────────────────────────────

    #[test]
    fn test_parse_sha_present_in_json_body() {
        let json_body = r#"{"sha": "abc123def456", "content": "aGVsbG8=", "encoding": "base64"}"#;
        let json: serde_json::Value = serde_json::from_str(json_body).unwrap();
        let sha = json["sha"].as_str().map(|s| s.to_string());
        assert_eq!(sha, Some("abc123def456".to_string()));
    }

    #[test]
    fn test_parse_sha_missing_field_returns_none() {
        let json_body = r#"{"content": "aGVsbG8=", "encoding": "base64"}"#;
        let json: serde_json::Value = serde_json::from_str(json_body).unwrap();
        let sha = json["sha"].as_str().map(|s| s.to_string());
        assert_eq!(sha, None);
    }

    // ── put_file body construction ────────────────────────────────────────────

    #[test]
    fn test_put_body_without_sha_excludes_sha_field() {
        // When SHA is None, the JSON body must NOT include a "sha" field (first-time create)
        let sha: Option<String> = None;
        let body = build_put_body("aGVsbG8=", &sha);
        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert!(
            parsed.get("sha").is_none(),
            "body must not include sha field when creating a new file"
        );
        assert_eq!(parsed["message"], "vibestats sync");
        assert_eq!(parsed["content"], "aGVsbG8=");
    }

    #[test]
    fn test_put_body_with_sha_includes_sha_field() {
        // When SHA is Some, the JSON body must include the "sha" field (update)
        let sha: Option<String> = Some("abc123".to_string());
        let body = build_put_body("aGVsbG8=", &sha);
        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(
            parsed["sha"], "abc123",
            "body must include sha field when updating existing file"
        );
        assert_eq!(parsed["message"], "vibestats sync");
        assert_eq!(parsed["content"], "aGVsbG8=");
    }

    /// Helper that mirrors the body-building logic in `put_file_inner`.
    fn build_put_body(encoded_content: &str, current_sha: &Option<String>) -> String {
        if let Some(sha) = current_sha {
            serde_json::json!({
                "message": "vibestats sync",
                "content": encoded_content,
                "sha": sha
            })
            .to_string()
        } else {
            serde_json::json!({
                "message": "vibestats sync",
                "content": encoded_content
            })
            .to_string()
        }
    }

    // ── base64_decode test vectors (RFC 4648) ─────────────────────────────────

    #[test]
    fn test_base64_decode_hello() {
        // Known vector from story Dev Notes: base64_decode("aGVsbG8=") → "hello"
        assert_eq!(base64_decode("aGVsbG8=").unwrap(), "hello");
    }

    #[test]
    fn test_base64_decode_empty() {
        assert_eq!(base64_decode("").unwrap(), "");
    }

    #[test]
    fn test_base64_decode_roundtrip() {
        // Encode then decode must produce the original string
        let original = "vibestats test content";
        let encoded = base64_encode(original.as_bytes());
        let decoded = base64_decode(&encoded).unwrap();
        assert_eq!(decoded, original);
    }

    #[test]
    fn test_base64_decode_invalid_char() {
        // Character '!' is not in the base64 alphabet
        assert!(base64_decode("aG!sbG8=").is_err());
    }

    #[test]
    fn test_base64_decode_strips_padding() {
        // "TWFu" decodes to "Man" (no padding needed)
        assert_eq!(base64_decode("TWFu").unwrap(), "Man");
        // "TWE=" decodes to "Ma"
        assert_eq!(base64_decode("TWE=").unwrap(), "Ma");
        // "TQ==" decodes to "M"
        assert_eq!(base64_decode("TQ==").unwrap(), "M");
    }

    // ── delete_file body construction ─────────────────────────────────────────

    #[test]
    fn test_delete_body_includes_sha_and_message() {
        let sha = "deadbeef1234";
        let body = build_delete_body(sha);
        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(parsed["sha"], sha, "delete body must include the sha field");
        assert_eq!(
            parsed["message"], "vibestats: remove machine data",
            "delete body must include the correct commit message"
        );
    }

    #[test]
    fn test_delete_body_does_not_include_content_field() {
        let body = build_delete_body("abc123");
        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert!(
            parsed.get("content").is_none(),
            "delete body must not include a content field"
        );
    }

    #[test]
    fn test_delete_body_sha_roundtrip() {
        let sha = "0000000000000000000000000000000000000000";
        let body = build_delete_body(sha);
        let parsed: serde_json::Value = serde_json::from_str(&body).unwrap();
        assert_eq!(parsed["sha"].as_str().unwrap(), sha);
    }

    /// Helper that mirrors the body-building logic in `delete_file_inner`.
    fn build_delete_body(sha: &str) -> String {
        serde_json::json!({
            "message": "vibestats: remove machine data",
            "sha": sha
        })
        .to_string()
    }

    // ── list_directory: JSON parsing ──────────────────────────────────────────

    #[test]
    fn test_list_directory_filters_files_only() {
        // Simulate a GitHub Contents API directory response
        let json_body = r#"[
            {"type": "file", "path": "machines/year=2026/month=04/day=10/harness=claude/machine_id=abc123/data.json"},
            {"type": "dir",  "path": "machines/year=2026/month=04/day=11"},
            {"type": "file", "path": "machines/year=2026/month=04/day=10/harness=claude/machine_id=abc123/other.json"}
        ]"#;
        let json: serde_json::Value = serde_json::from_str(json_body).unwrap();
        let entries = json.as_array().unwrap();
        let paths: Vec<String> = entries
            .iter()
            .filter(|e| e["type"].as_str() == Some("file"))
            .filter_map(|e| e["path"].as_str().map(|s| s.to_string()))
            .collect();
        assert_eq!(paths.len(), 2);
        assert!(paths[0].ends_with("data.json"));
        assert!(paths[1].ends_with("other.json"));
    }

    #[test]
    fn test_list_directory_empty_array_returns_empty_vec() {
        let json_body = "[]";
        let json: serde_json::Value = serde_json::from_str(json_body).unwrap();
        let entries = json.as_array().unwrap();
        let paths: Vec<String> = entries
            .iter()
            .filter(|e| e["type"].as_str() == Some("file"))
            .filter_map(|e| e["path"].as_str().map(|s| s.to_string()))
            .collect();
        assert!(paths.is_empty());
    }

    // ── get_user: login field extraction from /user JSON body ────────────────

    #[test]
    fn test_parse_login_present_in_user_json_body() {
        // Simulate a valid /user response body — verify login field is extracted correctly
        let json_body = r#"{"login": "octocat", "id": 1, "type": "User"}"#;
        let json: serde_json::Value = serde_json::from_str(json_body).unwrap();
        let login = json["login"].as_str().map(|s| s.to_string());
        assert_eq!(login, Some("octocat".to_string()));
    }

    #[test]
    fn test_parse_login_missing_field_returns_none() {
        // Simulate a /user response body without "login" field
        let json_body = r#"{"id": 1, "type": "User"}"#;
        let json: serde_json::Value = serde_json::from_str(json_body).unwrap();
        let login = json["login"].as_str().map(|s| s.to_string());
        assert_eq!(login, None);
    }

    #[test]
    fn test_parse_login_with_hyphenated_username() {
        // GitHub usernames can contain hyphens
        let json_body = r#"{"login": "step-hen-leo", "id": 42}"#;
        let json: serde_json::Value = serde_json::from_str(json_body).unwrap();
        let login = json["login"].as_str().map(|s| s.to_string());
        assert_eq!(login, Some("step-hen-leo".to_string()));
    }

    // ── GithubApi::new ────────────────────────────────────────────────────────

    #[test]
    fn test_github_api_new_stores_token_and_repo() {
        let api = GithubApi::new("my-token", "owner/repo");
        assert_eq!(api.token, "my-token");
        assert_eq!(api.repo, "owner/repo");
    }

    // ── base64_encode produces valid GitHub Contents API encoding ─────────────

    #[test]
    fn test_base64_output_uses_standard_alphabet() {
        // Verify that JSON content encodes to base64 with only valid standard alphabet chars
        let content = r#"{"key": "value", "num": 42}"#;
        let encoded = base64_encode(content.as_bytes());
        assert!(!encoded.is_empty());
        for c in encoded.chars() {
            assert!(
                c.is_ascii_alphanumeric() || c == '+' || c == '/' || c == '=',
                "invalid base64 character in output: {c:?}"
            );
        }
    }
}