dracon-sync 0.1.11

Invisible git sync daemon for deterministic AI-assisted development
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
use anyhow::{Context, Result};
use serde::Deserialize;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};

use crate::git::gh_cmd;
use crate::policy::{AuthType, RemoteConfig};
use crate::secrets::{load_secret, sync_secrets_dir};

/// Strip ANSI escape sequences from a string.
/// Handles CSI sequences (ESC [ ... m), OSC sequences (ESC ] ... BEL/ST),
/// and bare ESC sequences.
fn strip_ansi(s: &str) -> String {
    let mut result = String::with_capacity(s.len());
    let mut chars = s.chars().peekable();
    while let Some(c) = chars.next() {
        if c == '\x1b' {
            // ESC sequence
            match chars.peek() {
                Some('[') => {
                    // CSI sequence: ESC [ ... <final byte>
                    chars.next();
                    while let Some(&next) = chars.peek() {
                        chars.next();
                        if ('@'..='~').contains(&next) {
                            break;
                        }
                    }
                }
                Some(']') => {
                    // OSC sequence: ESC ] ... BEL or ST
                    chars.next();
                    while let Some(next) = chars.next() {
                        if next == '\x07' {
                            break;
                        }
                        if next == '\x1b' && chars.peek() == Some(&'\\') {
                            chars.next();
                            break;
                        }
                    }
                }
                _ => {
                    // Other ESC sequence (2-char): skip the next char
                    chars.next();
                }
            }
        } else {
            result.push(c);
        }
    }
    result
}

/// Directory for visibility sync cache files.
fn visibility_cache_dir() -> PathBuf {
    dirs::home_dir()
        .unwrap_or_else(|| PathBuf::from("."))
        .join(".local/state/dracon/visibility-sync")
}

/// Path to the cache file for a given repo.
/// Uses a hash of the full repo path to avoid collisions between
/// same-named repos in different watch roots.
fn visibility_cache_path(repo_path: &Path) -> PathBuf {
    let path_str = repo_path.to_string_lossy();
    let hash = simple_hash(&path_str);
    visibility_cache_dir().join(format!("{}.last", hash))
}

/// Simple FNV-1a-like hash for cache file names.
/// Not cryptographically secure — just for collision avoidance.
fn simple_hash(s: &str) -> String {
    let mut hash: u64 = 0xcbf29ce484222325; // FNV offset basis
    for byte in s.bytes() {
        hash ^= byte as u64;
        hash = hash.wrapping_mul(0x100000001b3); // FNV prime
    }
    format!("{:016x}", hash)
}

/// Check whether the visibility cache is fresh (within `interval_hours`).
fn is_visibility_cache_fresh(repo_path: &Path, interval_hours: u64) -> bool {
    let path = visibility_cache_path(repo_path);
    if !path.exists() {
        return false;
    }
    let Ok(content) = std::fs::read_to_string(&path) else {
        return false;
    };
    let Ok(last_ts) = content.trim().parse::<u64>() else {
        return false;
    };
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    let interval_secs = interval_hours.saturating_mul(3600);
    now.saturating_sub(last_ts) < interval_secs
}

/// Write the current timestamp to the visibility cache for a repo.
fn update_visibility_cache(repo_path: &Path) {
    let dir = visibility_cache_dir();
    if let Err(e) = std::fs::create_dir_all(&dir) {
        eprintln!(
            "⚠️ failed to create visibility cache dir {}: {}",
            dir.display(),
            e
        );
        return;
    }
    let path = visibility_cache_path(repo_path);
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();
    if let Err(e) = std::fs::write(&path, now.to_string()) {
        eprintln!(
            "⚠️ failed to write visibility cache {}: {}",
            path.display(),
            e
        );
    }
}

/// Parse `owner/repo` from a GitHub remote URL.
/// Supports both SSH (`git@github.com:owner/repo.git`) and HTTPS (`https://github.com/owner/repo.git`).
pub(crate) fn parse_github_owner_repo(remote_url: &str) -> Option<(String, String)> {
    // SSH: git@github.com:owner/repo.git
    if remote_url.contains('@') {
        if let Some(colon) = remote_url.rfind(':') {
            let after_colon = &remote_url[colon + 1..];
            let clean = after_colon.strip_suffix(".git").unwrap_or(after_colon);
            if let Some(slash) = clean.find('/') {
                return Some((clean[..slash].to_string(), clean[slash + 1..].to_string()));
            }
        }
    }
    // HTTPS: https://github.com/owner/repo.git
    if let Some(host_start) = remote_url.find("github.com/") {
        let after_host = &remote_url[host_start + 11..];
        let clean = after_host.strip_suffix(".git").unwrap_or(after_host);
        if let Some(slash) = clean.find('/') {
            return Some((clean[..slash].to_string(), clean[slash + 1..].to_string()));
        }
    }
    None
}

/// Query GitHub for the visibility of a repo using `gh api`.
/// Returns `true` if the repo is private, `false` if public.
/// On any error (gh not installed, no auth, network failure), returns `true` as the safe default.
pub(crate) fn get_github_visibility(owner: &str, repo: &str) -> bool {
    let output = match gh_cmd()
        .args([
            "api",
            &format!("repos/{}/{}", owner, repo),
            "--jq",
            ".private",
        ])
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            eprintln!("⚠️ gh api failed (is gh installed?): {}", e);
            return true;
        }
    };
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("⚠️ gh api failed: {}", stderr.trim());
        return true;
    }
    let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
    // "true" → private, "false" → public, anything else → safe default (private)
    stdout == "true"
}

const GITLAB_API_PROJECTS: &str = "https://gitlab.com/api/v4/projects/{}%2F{}";
const CODEBERG_API_REPOS: &str = "https://codeberg.org/api/v1/repos/{}/{}";

/// Set GitLab repo visibility using `curl` with PRIVATE-TOKEN.
/// The token is passed via stdin (`-H @-`) so it never appears in the
/// process command line (visible to other local users via /proc).
/// `private=true` means private, `private=false` means public.
fn set_gitlab_visibility(owner: &str, repo: &str, token: &str, private: bool) -> Result<()> {
    use std::io::Write;
    let visibility = if private { "private" } else { "public" };
    let encoded = format!("{}%2F{}", owner, repo);
    let url = GITLAB_API_PROJECTS.replace("{}", &encoded);
    let body = format!("visibility={}", visibility);
    let header = format!("PRIVATE-TOKEN: {}\r\n", token);
    let mut child = std::process::Command::new("curl")
        .args([
            "-s",
            "-o",
            "/dev/null",
            "-w",
            "%{http_code}",
            "-H",
            "@-",
            "-X",
            "PUT",
            "--data-binary",
            &body,
            &url,
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .with_context(|| "curl failed to run for GitLab visibility update")?;
    {
        let stdin = child
            .stdin
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("curl stdin not available"))?;
        stdin
            .write_all(header.as_bytes())
            .with_context(|| "failed to write GitLab PRIVATE-TOKEN header to curl stdin")?;
    }
    let output = child
        .wait_with_output()
        .with_context(|| "curl wait_with_output failed for GitLab visibility update")?;

    let code = String::from_utf8_lossy(&output.stdout).trim().to_string();
    match code.as_str() {
        "200" => Ok(()),
        "401" => Err(anyhow::anyhow!(
            "GitLab visibility update failed: unauthorized (invalid token)"
        )),
        "404" => Err(anyhow::anyhow!(
            "GitLab visibility update failed: repo not found"
        )),
        _ => Err(anyhow::anyhow!(
            "GitLab visibility update failed: HTTP {}",
            code
        )),
    }
}

/// Set Codeberg repo visibility using `curl` with Authorization token.
/// The token is passed via stdin (`-H @-`) so it never appears in the
/// process command line (visible to other local users via /proc).
/// `private=true` means private, `private=false` means public.
fn set_codeberg_visibility(owner: &str, repo: &str, token: &str, private: bool) -> Result<()> {
    use std::io::Write;
    let url = CODEBERG_API_REPOS.replace("{}", &format!("{}/{}", owner, repo));
    let json = format!("{{\"private\":{}}}", private);
    let headers = format!(
        "Authorization: token {}\r\nContent-Type: application/json\r\n",
        token
    );
    let mut child = std::process::Command::new("curl")
        .args([
            "-s",
            "-o",
            "/dev/null",
            "-w",
            "%{http_code}",
            "-H",
            "@-",
            "-X",
            "PATCH",
            "--data-binary",
            &json,
            &url,
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .with_context(|| "curl failed to run for Codeberg visibility update")?;
    {
        let stdin = child
            .stdin
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("curl stdin not available"))?;
        stdin
            .write_all(headers.as_bytes())
            .with_context(|| "failed to write Codeberg Authorization header to curl stdin")?;
    }
    let output = child
        .wait_with_output()
        .with_context(|| "curl wait_with_output failed for Codeberg visibility update")?;

    let code = String::from_utf8_lossy(&output.stdout).trim().to_string();
    match code.as_str() {
        "200" => Ok(()),
        "401" => Err(anyhow::anyhow!(
            "Codeberg visibility update failed: unauthorized (invalid token)"
        )),
        "404" => Err(anyhow::anyhow!(
            "Codeberg visibility update failed: repo not found"
        )),
        _ => Err(anyhow::anyhow!(
            "Codeberg visibility update failed: HTTP {}",
            code
        )),
    }
}

/// Query GitHub for the current visibility of the origin repo, then update
/// all configured mirrors (GitLab, Codeberg) to match.
///
/// This function is **non-fatal**: errors are logged but never propagated,
/// so a visibility sync failure will never break the git push pipeline.
pub(crate) fn sync_mirror_visibility(
    origin_url: &str,
    remotes: &[RemoteConfig],
    repo_path: &Path,
    interval_hours: u64,
) {
    // Check cache first
    if is_visibility_cache_fresh(repo_path, interval_hours) {
        return;
    }

    let repo_name = repo_path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();
    if repo_name.is_empty() {
        return;
    }

    let Some((owner, gh_repo)) = parse_github_owner_repo(origin_url) else {
        eprintln!(
            "⚠️ could not parse GitHub owner/repo from origin URL: {}",
            origin_url
        );
        return;
    };

    let github_private = get_github_visibility(&owner, &gh_repo);
    let visibility_str = if github_private { "private" } else { "public" };

    if crate::policy::debug_enabled() {
        eprintln!("🐛 GitHub repo {}/{} is {}", owner, gh_repo, visibility_str);
    }

    for remote in remotes {
        let auth = remote.effective_auth_type();
        let account = remote.resolve_account();
        if auth == AuthType::GitLab {
            let token_var = remote
                .auto_create_token_var
                .as_deref()
                .unwrap_or("GITLAB_TOKEN");
            if let Some(token) = load_secret(token_var, &sync_secrets_dir()) {
                let resolved_name = remote.resolve_repo_name(&repo_name);
                if let Err(e) =
                    set_gitlab_visibility(&account, &resolved_name, &token, github_private)
                {
                    eprintln!(
                        "⚠️ failed to set GitLab visibility for {}: {}",
                        resolved_name, e
                    );
                } else if crate::policy::debug_enabled() {
                    eprintln!(
                        "🐛 set GitLab {}/{} to {}",
                        account, resolved_name, visibility_str
                    );
                }
            } else {
                eprintln!("⚠️ no GITLAB_TOKEN for visibility sync on {}", remote.name);
            }
        }

        if auth == AuthType::Codeberg {
            let token_var = remote
                .auto_create_token_var
                .as_deref()
                .unwrap_or("CODEBERG_TOKEN");
            if let Some(token) = load_secret(token_var, &sync_secrets_dir()) {
                let resolved_name = remote.resolve_repo_name(&repo_name);
                if let Err(e) =
                    set_codeberg_visibility(&account, &resolved_name, &token, github_private)
                {
                    eprintln!(
                        "⚠️ failed to set Codeberg visibility for {}: {}",
                        resolved_name, e
                    );
                } else if crate::policy::debug_enabled() {
                    eprintln!(
                        "🐛 set Codeberg {}/{} to {}",
                        account, resolved_name, visibility_str
                    );
                }
            } else {
                eprintln!(
                    "⚠️ no CODEBERG_TOKEN for visibility sync on {}",
                    remote.name
                );
            }
        }
    }

    // Update cache even on partial failures — we don't want to hammer APIs
    // on every sync cycle when a token is permanently missing.
    update_visibility_cache(repo_path);
}

/// Repo metadata fetched from GitHub: description + topics.
#[derive(Debug, Clone, Default)]
pub(crate) struct RepoMetadata {
    pub(crate) description: String,
    pub(crate) topics: Vec<String>,
}

/// Query GitHub for repo description and topics using `gh api`.
/// Returns empty metadata on any error (non-fatal).
pub(crate) fn get_github_metadata(owner: &str, repo: &str) -> RepoMetadata {
    let output = match gh_cmd()
        .args([
            "api",
            &format!("repos/{}/{}", owner, repo),
            "--jq",
            "{description: .description, topics: .topics}",
        ])
        .output()
    {
        Ok(o) => o,
        Err(e) => {
            eprintln!("⚠️ gh api metadata failed (is gh installed?): {}", e);
            return RepoMetadata::default();
        }
    };
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        eprintln!("⚠️ gh api metadata failed: {}", stderr.trim());
        return RepoMetadata::default();
    }
    let stdout_raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
    // gh api --jq with JSON object construction can include ANSI color codes;
    // strip them before parsing JSON.
    let stdout = strip_ansi(&stdout_raw);
    // Parse JSON: {"description": "...", "topics": ["a","b"]}
    match serde_json::from_str::<RepoMetadataJson>(&stdout) {
        Ok(m) => RepoMetadata {
            description: m.description.unwrap_or_default().trim().to_string(),
            topics: m.topics.unwrap_or_default(),
        },
        Err(e) => {
            eprintln!("⚠️ failed to parse gh api metadata JSON: {}", e);
            RepoMetadata::default()
        }
    }
}

#[derive(Deserialize)]
struct RepoMetadataJson {
    description: Option<String>,
    topics: Option<Vec<String>>,
}

/// Set GitLab repo description and topics using `curl` with PRIVATE-TOKEN.
/// The token is passed via stdin (`-H @-`) so it never appears in the
/// process command line (visible to other local users via /proc).
fn set_gitlab_metadata(owner: &str, repo: &str, token: &str, meta: &RepoMetadata) -> Result<()> {
    use std::io::Write;
    let encoded = format!("{}%2F{}", owner, repo);
    let url = GITLAB_API_PROJECTS.replace("{}", &encoded);
    let mut form_data = vec![format!(
        "description={}",
        urlencoding::encode(&meta.description)
    )];
    for topic in &meta.topics {
        form_data.push(format!("tag_list[]={}", urlencoding::encode(topic)));
    }
    let form_body = form_data.join("&");
    let header = format!("PRIVATE-TOKEN: {}\r\n", token);
    let mut child = std::process::Command::new("curl")
        .args([
            "-s",
            "-o",
            "/dev/null",
            "-w",
            "%{http_code}",
            "-H",
            "@-",
            "-X",
            "PUT",
            "--data-binary",
            &form_body,
            &url,
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .with_context(|| "curl failed to run for GitLab metadata update")?;
    {
        let stdin = child
            .stdin
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("curl stdin not available"))?;
        stdin
            .write_all(header.as_bytes())
            .with_context(|| "failed to write GitLab PRIVATE-TOKEN header to curl stdin")?;
    }
    let output = child
        .wait_with_output()
        .with_context(|| "curl wait_with_output failed for GitLab metadata update")?;

    let code = String::from_utf8_lossy(&output.stdout).trim().to_string();
    match code.as_str() {
        "200" => Ok(()),
        "401" => Err(anyhow::anyhow!(
            "GitLab metadata update failed: unauthorized"
        )),
        "404" => Err(anyhow::anyhow!(
            "GitLab metadata update failed: repo not found"
        )),
        _ => Err(anyhow::anyhow!(
            "GitLab metadata update failed: HTTP {}",
            code
        )),
    }
}

/// Set Codeberg repo description and topics using `curl` with Authorization token.
/// The token is passed via stdin (`-H @-`) so it never appears in the
/// process command line (visible to other local users via /proc).
fn set_codeberg_metadata(owner: &str, repo: &str, token: &str, meta: &RepoMetadata) -> Result<()> {
    use std::io::Write;
    let url = CODEBERG_API_REPOS.replace("{}", &format!("{}/{}", owner, repo));
    let json = serde_json::json!({
        "description": if meta.description.is_empty() { serde_json::Value::Null } else { serde_json::Value::String(meta.description.clone()) },
        "topics": meta.topics,
    });
    let headers = format!(
        "Authorization: token {}\r\nContent-Type: application/json\r\n",
        token
    );
    let mut child = std::process::Command::new("curl")
        .args([
            "-s",
            "-o",
            "/dev/null",
            "-w",
            "%{http_code}",
            "-H",
            "@-",
            "-X",
            "PATCH",
            "--data-binary",
            &json.to_string(),
            &url,
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .with_context(|| "curl failed to run for Codeberg metadata update")?;
    {
        let stdin = child
            .stdin
            .as_mut()
            .ok_or_else(|| anyhow::anyhow!("curl stdin not available"))?;
        stdin
            .write_all(headers.as_bytes())
            .with_context(|| "failed to write Codeberg Authorization header to curl stdin")?;
    }
    let output = child
        .wait_with_output()
        .with_context(|| "curl wait_with_output failed for Codeberg metadata update")?;

    let code = String::from_utf8_lossy(&output.stdout).trim().to_string();
    match code.as_str() {
        "200" => Ok(()),
        "401" => Err(anyhow::anyhow!(
            "Codeberg metadata update failed: unauthorized"
        )),
        "404" => Err(anyhow::anyhow!(
            "Codeberg metadata update failed: repo not found"
        )),
        _ => Err(anyhow::anyhow!(
            "Codeberg metadata update failed: HTTP {}",
            code
        )),
    }
}

/// Sync repo metadata (description + topics) from GitHub to all configured mirrors.
///
/// This function is **non-fatal**: errors are logged but never propagated.
/// Reuses the same cache as visibility sync.
pub(crate) fn sync_mirror_metadata(
    origin_url: &str,
    remotes: &[RemoteConfig],
    repo_path: &Path,
    interval_hours: u64,
) {
    // Check cache first (shares cache with visibility sync)
    if is_visibility_cache_fresh(repo_path, interval_hours) {
        return;
    }

    let repo_name = repo_path
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();
    if repo_name.is_empty() {
        return;
    }

    let Some((owner, gh_repo)) = parse_github_owner_repo(origin_url) else {
        // Already warned by visibility sync if called in same cycle
        return;
    };

    let meta = get_github_metadata(&owner, &gh_repo);

    if crate::policy::debug_enabled() {
        eprintln!(
            "🐛 GitHub {}/{} metadata: description={:?} topics={:?}",
            owner, gh_repo, meta.description, meta.topics
        );
    }

    for remote in remotes {
        let auth = remote.effective_auth_type();
        let account = remote.resolve_account();
        if auth == AuthType::GitLab {
            let token_var = remote
                .auto_create_token_var
                .as_deref()
                .unwrap_or("GITLAB_TOKEN");
            if let Some(token) = load_secret(token_var, &sync_secrets_dir()) {
                let resolved_name = remote.resolve_repo_name(&repo_name);
                if let Err(e) = set_gitlab_metadata(&account, &resolved_name, &token, &meta) {
                    eprintln!(
                        "⚠️ failed to set GitLab metadata for {}: {}",
                        resolved_name, e
                    );
                } else if crate::policy::debug_enabled() {
                    eprintln!("🐛 set GitLab {}/{} metadata", account, resolved_name);
                }
            }
        }

        if auth == AuthType::Codeberg {
            let token_var = remote
                .auto_create_token_var
                .as_deref()
                .unwrap_or("CODEBERG_TOKEN");
            if let Some(token) = load_secret(token_var, &sync_secrets_dir()) {
                let resolved_name = remote.resolve_repo_name(&repo_name);
                if let Err(e) = set_codeberg_metadata(&account, &resolved_name, &token, &meta) {
                    eprintln!(
                        "⚠️ failed to set Codeberg metadata for {}: {}",
                        resolved_name, e
                    );
                } else if crate::policy::debug_enabled() {
                    eprintln!("🐛 set Codeberg {}/{} metadata", account, resolved_name);
                }
            }
        }
    }

    // Don't update cache here — visibility sync will do it in the same cycle
}

/// Remove visibility cache entries for repos that no longer exist on disk.
pub(crate) fn prune_stale_visibility_cache(
    repo_set: &std::collections::BTreeSet<std::path::PathBuf>,
) -> Result<()> {
    let cache_dir = visibility_cache_dir();
    if !cache_dir.exists() {
        return Ok(());
    }
    // Build set of valid cache hashes from current repos
    let valid_hashes: std::collections::HashSet<String> = repo_set
        .iter()
        .map(|r| format!("{}.last", simple_hash(&r.to_string_lossy())))
        .collect();
    let mut removed = 0;
    for entry in std::fs::read_dir(&cache_dir)? {
        let entry = entry?;
        let name = entry.file_name();
        let name_str = name.to_string_lossy();
        if name_str.ends_with(".last") && !valid_hashes.contains(name_str.as_ref()) {
            std::fs::remove_file(entry.path())?;
            removed += 1;
        }
    }
    if removed > 0 {
        eprintln!(
            "🧹 startup: pruned {} stale visibility cache entries",
            removed
        );
    }
    Ok(())
}

/// Check GitHub visibility at repo creation time and return whether the
/// repo should be created as private. If `sync_visibility` is disabled,
/// always returns `true` (private).
#[cfg(test)]
pub(crate) fn github_visibility_at_creation(
    owner: &str,
    repo_name: &str,
    sync_visibility: bool,
) -> bool {
    if !sync_visibility {
        return true;
    }
    get_github_visibility(owner, repo_name)
}

/// Update the `auto_create_account` and `--private` flag for GitHub repo creation
/// based on the visibility setting. When `sync_visibility` is true, queries GitHub
/// to determine if the repo already exists and what its visibility is.
///
/// This is a no-op wrapper around `create_repo_on_github` for the `sync_visibility=false`
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_github_owner_repo_ssh() {
        let result = parse_github_owner_repo("git@github.com:DraconDev/my-repo.git");
        assert_eq!(
            result,
            Some(("DraconDev".to_string(), "my-repo".to_string()))
        );
    }

    #[test]
    fn test_parse_github_owner_repo_https() {
        let result = parse_github_owner_repo("https://github.com/DraconDev/my-repo.git");
        assert_eq!(
            result,
            Some(("DraconDev".to_string(), "my-repo".to_string()))
        );
    }

    #[test]
    fn test_parse_github_owner_repo_no_git_suffix() {
        let result = parse_github_owner_repo("git@github.com:DraconDev/my-repo");
        assert_eq!(
            result,
            Some(("DraconDev".to_string(), "my-repo".to_string()))
        );
    }

    #[test]
    fn test_parse_github_owner_repo_invalid_url() {
        let result = parse_github_owner_repo("not-a-url");
        assert_eq!(result, None);
    }

    #[test]
    fn test_parse_github_owner_repo_gitlab_url() {
        let result = parse_github_owner_repo("git@gitlab.com:someone/repo.git");
        // Should parse as (someone, repo) since the parser is generic enough
        assert_eq!(result, Some(("someone".to_string(), "repo".to_string())));
    }

    #[test]
    fn test_visibility_cache_not_fresh_when_missing() {
        let repo_path = Path::new("/tmp/test_repo_that_should_not_exist_12345");
        assert!(!is_visibility_cache_fresh(repo_path, 24));
    }

    #[test]
    fn test_visibility_cache_fresh_when_recent() {
        let repo_path = Path::new("/tmp/test_cache_fresh");
        update_visibility_cache(repo_path);
        assert!(is_visibility_cache_fresh(repo_path, 24));
        // Cleanup
        let _ = std::fs::remove_file(visibility_cache_path(repo_path));
    }

    #[test]
    fn test_visibility_cache_stale_when_old() {
        let repo_path = Path::new("/tmp/test_cache_stale");
        let path = visibility_cache_path(repo_path);
        let old_ts = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs()
            .saturating_sub(25 * 3600);
        std::fs::create_dir_all(visibility_cache_dir()).unwrap();
        std::fs::write(&path, old_ts.to_string()).unwrap();
        assert!(!is_visibility_cache_fresh(repo_path, 24));
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_visibility_cache_updates_timestamp() {
        let repo_path = Path::new("/tmp/test_cache_update");
        let path = visibility_cache_path(repo_path);
        // Write old timestamp
        let old_ts = "1000";
        std::fs::create_dir_all(visibility_cache_dir()).unwrap();
        std::fs::write(&path, old_ts).unwrap();
        // Update
        update_visibility_cache(repo_path);
        let new_content = std::fs::read_to_string(&path).unwrap();
        let new_ts = new_content.trim().parse::<u64>().unwrap();
        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        assert!(new_ts > 1000);
        assert!(new_ts <= now);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_github_visibility_at_creation_disabled() {
        // When sync_visibility is false, always private
        assert!(github_visibility_at_creation("DraconDev", "test", false));
    }

    #[test]
    fn test_get_github_visibility_returns_safe_default_on_error() {
        // With no gh installed (or in test env), should return true (private)
        let result = get_github_visibility("nonexistent-owner-12345", "nonexistent-repo-67890");
        assert!(result, "safe default should be private");
    }

    #[test]
    fn test_sync_mirror_visibility_skips_when_cache_fresh() {
        let repo_path = Path::new("/tmp/test_skip_cached");
        update_visibility_cache(repo_path);
        // Should return immediately without error even with bad remotes
        let remotes = vec![RemoteConfig {
            name: "gitlab".to_string(),
            push_url: "git@gitlab.com:test/repo.git".to_string(),
            auto_create: false,
            auto_create_account: "test".to_string(),
            auth_type: AuthType::GitLab,
            priority: 50,
            api_endpoint: None,
            auto_create_token_var: None,
            repo_name_map: Default::default(),
            force_push_when_behind: false,
        }];
        sync_mirror_visibility("git@github.com:DraconDev/test.git", &remotes, repo_path, 24);
        // If we got here without panicking, the cache skip worked
        let _ = std::fs::remove_file(visibility_cache_path(repo_path));
    }

    #[test]
    fn test_sync_mirror_visibility_handles_unparseable_origin() {
        let repo_path = Path::new("/tmp/test_bad_origin");
        let remotes: Vec<RemoteConfig> = vec![];
        // Should not panic on unparseable URL
        sync_mirror_visibility("not-a-valid-url", &remotes, repo_path, 0);
        let _ = std::fs::remove_file(visibility_cache_path(repo_path));
    }

    #[test]
    fn test_parse_github_owner_repo_with_dots() {
        let result = parse_github_owner_repo("git@github.com:DraconDev/.dracon.git");
        assert_eq!(
            result,
            Some(("DraconDev".to_string(), ".dracon".to_string()))
        );
    }

    #[test]
    fn test_parse_github_owner_repo_with_name_mapping() {
        let result = parse_github_owner_repo("https://github.com/my-org/some-repo.git");
        assert_eq!(
            result,
            Some(("my-org".to_string(), "some-repo".to_string()))
        );
    }

    // ---- Creation-time visibility tests ----

    #[test]
    fn test_github_visibility_at_creation_enabled_private() {
        // When sync_visibility is true, we check GitHub. In test env (no gh),
        // get_github_visibility returns true (safe default = private).
        assert!(github_visibility_at_creation("DraconDev", "test", true));
    }

    #[test]
    fn test_sync_visibility_defaults_in_policy() {
        // Verify that the default policy parsing gives sync_visibility=false
        let toml = "";
        let policy: crate::policy::SyncPolicy = toml::from_str(toml).unwrap_or_else(|_| {
            // If empty TOML fails, try minimal valid config
            toml::from_str("pulse_interval_secs = 1").unwrap()
        });
        assert!(
            !policy.sync_visibility,
            "sync_visibility should default to false"
        );
        assert_eq!(
            policy.sync_visibility_interval_hours, 24,
            "interval should default to 24"
        );
    }

    #[test]
    fn test_sync_visibility_parses_true() {
        let toml = "sync_visibility = true\nsync_visibility_interval_hours = 6";
        let policy: crate::policy::SyncPolicy = toml::from_str(toml)
            .unwrap_or_else(|_| toml::from_str("pulse_interval_secs = 1\nsync_visibility = true\nsync_visibility_interval_hours = 6").unwrap());
        assert!(policy.sync_visibility);
        assert_eq!(policy.sync_visibility_interval_hours, 6);
    }

    // ---- Mirror update tests with mock curl ----

    #[test]
    fn test_set_gitlab_visibility_builds_correct_request() {
        // We can't easily mock curl, but we can verify the function handles
        // the "curl not found" case gracefully.
        let result = set_gitlab_visibility("testowner", "testrepo", "faketoken", true);
        // curl may or may not be available, but it should not panic
        let _ = result;
    }

    #[test]
    fn test_set_codeberg_visibility_builds_correct_request() {
        let result = set_codeberg_visibility("testowner", "testrepo", "faketoken", false);
        let _ = result;
    }

    // ---- Error isolation tests ----

    #[test]
    fn test_sync_mirror_visibility_does_not_panic_on_all_failures() {
        let _repo_name = "test_all_failures";
        let remotes = vec![
            RemoteConfig {
                name: "gitlab".to_string(),
                push_url: "git@gitlab.com:test/repo.git".to_string(),
                auto_create: false,
                auto_create_account: "test".to_string(),
                auth_type: AuthType::GitLab,
                priority: 50,
                api_endpoint: None,
                auto_create_token_var: Some("NONEXISTENT_TOKEN_VAR_12345".to_string()),
                repo_name_map: Default::default(),
                force_push_when_behind: false,
            },
            RemoteConfig {
                name: "codeberg".to_string(),
                push_url: "git@codeberg.org:test/repo.git".to_string(),
                auto_create: false,
                auto_create_account: "test".to_string(),
                auth_type: AuthType::Codeberg,
                priority: 50,
                api_endpoint: None,
                auto_create_token_var: Some("NONEXISTENT_TOKEN_VAR_12345".to_string()),
                repo_name_map: Default::default(),
                force_push_when_behind: false,
            },
        ];
        // Set interval to 0 to force cache expiration
        sync_mirror_visibility(
            "git@github.com:DraconDev/test.git",
            &remotes,
            Path::new("/tmp/test_all_failures"),
            0,
        );
        // Should not panic even when all tokens are missing
        let _ = std::fs::remove_file(visibility_cache_path(Path::new("/tmp/test_all_failures")));
    }

    // ---- Idempotency / cache behavior ----

    #[test]
    fn test_cache_prevents_repeated_api_calls() {
        let repo_path = Path::new("/tmp/test_idempotency_cache");
        update_visibility_cache(repo_path);
        // Second call with fresh cache should skip entirely
        assert!(is_visibility_cache_fresh(repo_path, 24));
        let _ = std::fs::remove_file(visibility_cache_path(repo_path));
    }

    #[test]
    fn test_cache_written_on_parseable_origin_even_when_tokens_missing() {
        // When origin URL is parseable but tokens are missing, the cache
        // should still be written to prevent hammering on every sync cycle.
        let repo_path = Path::new("/tmp/test_cache_on_failure");
        let remotes: Vec<RemoteConfig> = vec![];
        sync_mirror_visibility("git@github.com:DraconDev/test.git", &remotes, repo_path, 0);
        // Cache should exist even with no remotes to update
        let path = visibility_cache_path(repo_path);
        assert!(
            path.exists(),
            "cache should be written even when no remotes configured"
        );
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn test_cache_not_written_on_unparseable_origin() {
        // When the origin URL can't be parsed, we return early before writing cache.
        // This is correct — the next cycle should retry since we couldn't even
        // determine the GitHub owner/repo.
        let repo_path = Path::new("/tmp/test_cache_unparseable");
        let remotes: Vec<RemoteConfig> = vec![];
        sync_mirror_visibility("not-a-url", &remotes, repo_path, 0);
        let path = visibility_cache_path(repo_path);
        assert!(
            !path.exists(),
            "cache should NOT be written for unparseable URLs (need to retry)"
        );
    }

    // ---- Edge cases ----

    #[test]
    fn test_parse_github_owner_repo_with_hyphens() {
        let result = parse_github_owner_repo("git@github.com:my-org/my-super-repo.git");
        assert_eq!(
            result,
            Some(("my-org".to_string(), "my-super-repo".to_string()))
        );
    }

    #[test]
    fn test_parse_github_owner_repo_empty_string() {
        let result = parse_github_owner_repo("");
        assert_eq!(result, None);
    }

    #[test]
    fn test_visibility_cache_corrupt_file() {
        let repo_path = Path::new("/tmp/test_corrupt_cache");
        let path = visibility_cache_path(repo_path);
        std::fs::create_dir_all(visibility_cache_dir()).unwrap();
        std::fs::write(&path, "not-a-number").unwrap();
        assert!(
            !is_visibility_cache_fresh(repo_path, 24),
            "corrupt cache should be treated as stale"
        );
        let _ = std::fs::remove_file(&path);
    }

    // ---- Metadata sync tests ----

    #[test]
    fn test_get_github_metadata_returns_empty_on_error() {
        let meta = get_github_metadata("nonexistent-owner-12345", "nonexistent-repo-67890");
        assert!(
            meta.description.is_empty(),
            "description should be empty on error"
        );
        assert!(meta.topics.is_empty(), "topics should be empty on error");
    }

    #[test]
    fn test_sync_metadata_defaults_in_policy() {
        let toml = "";
        let policy: crate::policy::SyncPolicy = toml::from_str(toml)
            .unwrap_or_else(|_| toml::from_str("pulse_interval_secs = 1").unwrap());
        assert!(
            !policy.sync_metadata,
            "sync_metadata should default to false"
        );
    }

    #[test]
    fn test_sync_metadata_parses_true() {
        let toml = "sync_metadata = true";
        let policy: crate::policy::SyncPolicy = toml::from_str(toml).unwrap_or_else(|_| {
            toml::from_str("pulse_interval_secs = 1\nsync_metadata = true").unwrap()
        });
        assert!(policy.sync_metadata);
    }

    #[test]
    fn test_sync_mirror_metadata_does_not_panic() {
        let repo_path = Path::new("/tmp/test_metadata_no_panic");
        let remotes: Vec<RemoteConfig> = vec![];
        sync_mirror_metadata("git@github.com:DraconDev/test.git", &remotes, repo_path, 0);
        // Should not panic even with no remotes
        let _ = std::fs::remove_file(visibility_cache_path(repo_path));
    }

    #[test]
    fn test_sync_mirror_metadata_handles_unparseable_origin() {
        let repo_path = Path::new("/tmp/test_metadata_bad_origin");
        let remotes: Vec<RemoteConfig> = vec![];
        sync_mirror_metadata("not-a-url", &remotes, repo_path, 0);
        let _ = std::fs::remove_file(visibility_cache_path(repo_path));
    }

    #[test]
    fn test_repo_metadata_default() {
        let meta = RepoMetadata::default();
        assert!(meta.description.is_empty());
        assert!(meta.topics.is_empty());
    }

    #[test]
    fn test_set_gitlab_metadata_does_not_panic() {
        let meta = RepoMetadata {
            description: "Test repo".to_string(),
            topics: vec!["rust".to_string(), "cli".to_string()],
        };
        let result = set_gitlab_metadata("testowner", "testrepo", "faketoken", &meta);
        let _ = result;
    }

    #[test]
    fn test_set_codeberg_metadata_does_not_panic() {
        let meta = RepoMetadata {
            description: "Test repo".to_string(),
            topics: vec!["rust".to_string()],
        };
        let result = set_codeberg_metadata("testowner", "testrepo", "faketoken", &meta);
        let _ = result;
    }

    #[test]
    fn test_sync_metadata_with_missing_tokens() {
        let _repo_name = "test_metadata_missing_tokens";
        let remotes = vec![
            RemoteConfig {
                name: "gitlab".to_string(),
                push_url: "git@gitlab.com:test/repo.git".to_string(),
                auto_create: false,
                auto_create_account: "test".to_string(),
                auth_type: AuthType::GitLab,
                priority: 50,
                api_endpoint: None,
                auto_create_token_var: Some("NONEXISTENT_TOKEN_VAR_META".to_string()),
                repo_name_map: Default::default(),
                force_push_when_behind: false,
            },
            RemoteConfig {
                name: "codeberg".to_string(),
                push_url: "git@codeberg.org:test/repo.git".to_string(),
                auto_create: false,
                auto_create_account: "test".to_string(),
                auth_type: AuthType::Codeberg,
                priority: 50,
                api_endpoint: None,
                auto_create_token_var: Some("NONEXISTENT_TOKEN_VAR_META2".to_string()),
                repo_name_map: Default::default(),
                force_push_when_behind: false,
            },
        ];
        sync_mirror_metadata(
            "git@github.com:DraconDev/test.git",
            &remotes,
            Path::new("/tmp/test_metadata_missing_tokens"),
            0,
        );
        // Should not panic
        let _ = std::fs::remove_file(visibility_cache_path(Path::new(
            "/tmp/test_metadata_missing_tokens",
        )));
    }

    #[test]
    fn test_strip_ansi_removes_color_codes() {
        // Simulate gh api output with ANSI color codes
        let input = "\x1b[1;38m{\x1b[m\n\x1b[1;34m\"description\"\x1b[m\x1b[1;38m:\x1b[m \x1b[32m\"Hello world\"\x1b[m,\n\x1b[1;34m\"topics\"\x1b[m\x1b[1;38m:\x1b[m\x1b[32m[\"rust\"]\x1b[m\n}";
        let stripped = strip_ansi(input);
        assert!(
            !stripped.contains('\x1b'),
            "ANSI codes should be removed: got {:?}",
            stripped
        );
        let parsed: serde_json::Value =
            serde_json::from_str(&stripped).expect("should be valid JSON after stripping");
        assert_eq!(parsed["description"], "Hello world");
        assert_eq!(parsed["topics"][0], "rust");
    }

    #[test]
    fn test_strip_ansi_passthrough_plain_text() {
        let input = r#"{"description":"plain","topics":[]}"#;
        assert_eq!(strip_ansi(input), input);
    }

    #[test]
    fn test_resolve_account_from_ssh_url() {
        let remote = RemoteConfig {
            name: "gitlab".to_string(),
            push_url: "git@gitlab.com:dracondev/{repo}.git".to_string(),
            auto_create: false,
            auto_create_account: String::new(),
            auth_type: AuthType::GitLab,
            priority: 50,
            api_endpoint: None,
            auto_create_token_var: None,
            repo_name_map: Default::default(),
            force_push_when_behind: false,
        };
        assert_eq!(remote.resolve_account(), "dracondev");
    }

    #[test]
    fn test_resolve_account_from_https_url() {
        let remote = RemoteConfig {
            name: "codeberg".to_string(),
            push_url: "https://codeberg.org/myorg/{repo}.git".to_string(),
            auto_create: false,
            auto_create_account: String::new(),
            auth_type: AuthType::Codeberg,
            priority: 50,
            api_endpoint: None,
            auto_create_token_var: None,
            repo_name_map: Default::default(),
            force_push_when_behind: false,
        };
        assert_eq!(remote.resolve_account(), "myorg");
    }

    #[test]
    fn test_resolve_account_explicit_overrides() {
        let remote = RemoteConfig {
            name: "github".to_string(),
            push_url: "git@github.com:DraconDev/{repo}.git".to_string(),
            auto_create: false,
            auto_create_account: "ExplicitAccount".to_string(),
            auth_type: AuthType::GitHub,
            priority: 50,
            api_endpoint: None,
            auto_create_token_var: None,
            repo_name_map: Default::default(),
            force_push_when_behind: false,
        };
        assert_eq!(remote.resolve_account(), "ExplicitAccount");
    }
}