dracon-sync 0.1.10

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
//! Multi-remote management — create, configure, and push to multiple git remotes.

use std::collections::HashSet;
use std::path::Path;
use std::time::Duration;
use tokio::time::sleep;

use anyhow::{Context, Result};

use crate::helpers::is_repo_already_exists;
use crate::policy::{std_git_command, AuthType, RemoteConfig};

use super::{
    current_branch, gh_cmd, git_ssh_hardening, is_permanent_push_rejection, is_push_rejected,
    is_safe_branch_name, load_secret, push_https_fallback, run_git_capture_output,
    run_git_with_timeout_env_progress,
};

/// Configure a remote URL. Adds if missing, updates if URL differs.
pub(crate) fn ensure_remote(repo: &Path, name: &str, url: &str) -> Result<()> {
    let existing = get_remote_url(repo, name);
    match existing {
        Some(cur) if cur == url => Ok(()),
        Some(_) => {
            std_git_command()
                .args(["remote", "set-url", name, url])
                .current_dir(repo)
                .status()
                .with_context(|| format!("git remote set-url {} in {}", name, repo.display()))?;
            Ok(())
        }
        None => {
            std_git_command()
                .args(["remote", "add", name, url])
                .current_dir(repo)
                .status()
                .with_context(|| format!("git remote add {} in {}", name, repo.display()))?;
            Ok(())
        }
    }
}

/// Configure all remotes from policy for a given repo.
pub(crate) fn configure_all_remotes(repo: &Path, remotes: &[RemoteConfig], repo_name: &str) {
    for remote in remotes {
        let url = remote.resolve_push_url(repo_name);
        if let Err(e) = ensure_remote(repo, &remote.name, &url) {
            eprintln!(
                "⚠️ failed to configure remote {} for {}: {}",
                remote.name,
                repo.display(),
                e
            );
        }
    }
}

/// Push to all mirror remotes, auto-creating repos if configured.
pub(crate) async fn push_mirror_remotes(
    repo: &Path,
    remotes: &[RemoteConfig],
    timeout_secs: u64,
    retries: u32,
    private: bool,
) -> Vec<(String, Result<()>)> {
    let repo_name = repo
        .file_name()
        .map(|n| n.to_string_lossy().to_string())
        .unwrap_or_default();

    configure_all_remotes(repo, remotes, &repo_name);

    for (remote_name, create_result) in auto_create_all_remotes(remotes, &repo_name, private).await
    {
        match create_result {
            Ok(_) => {}
            Err(e) => {
                eprintln!(
                    "⚠️ auto-create failed for {} on {}: {}",
                    repo_name, remote_name, e
                );
            }
        }
    }

    let all_remote_names: Vec<_> = remotes.iter().map(|r| r.name.as_str()).collect();
    if let Err(e) = remove_stale_remotes(repo, &all_remote_names) {
        eprintln!(
            "⚠️ failed to clean stale remotes for {}: {}",
            repo.display(),
            e
        );
    }

    push_to_all_remotes(repo, remotes, timeout_secs, retries).await
}

/// Get the URL for a given remote name.
pub(crate) fn get_remote_url(repo: &Path, name: &str) -> Option<String> {
    let output = std_git_command()
        .args(["remote", "get-url", name])
        .current_dir(repo)
        .output()
        .ok()?;
    if output.status.success() {
        Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
    } else {
        None
    }
}

/// List all remotes for a repo.
pub(crate) fn list_remotes(repo: &Path) -> Vec<String> {
    let output = std_git_command()
        .args(["remote"])
        .current_dir(repo)
        .output()
        .ok();
    match output {
        Some(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
            .lines()
            .map(String::from)
            .filter(|s| !s.is_empty())
            .collect(),
        _ => Vec::new(),
    }
}

/// Remove stale remotes (anything not in the keep list, except origin).
pub(crate) fn remove_stale_remotes(repo: &Path, keep: &[&str]) -> Result<()> {
    let current = list_remotes(repo);
    let keep_set: HashSet<_> = keep.iter().collect();
    for remote in current {
        if remote == "origin" {
            continue;
        }
        if !keep_set.contains(&remote.as_str()) {
            std_git_command()
                .args(["remote", "remove", &remote])
                .current_dir(repo)
                .status()
                .with_context(|| format!("git remote remove {} in {}", remote, repo.display()))?;
        }
    }
    Ok(())
}

/// Push to a named remote with SSH hardening, HTTPS fallback, and retries.
pub(crate) async fn push_to_named_remote(
    repo: &Path,
    remote_name: &str,
    timeout_secs: u64,
    retries: u32,
    force_when_behind: bool,
) -> Result<()> {
    let branch = current_branch(repo).unwrap_or_else(|| "main".to_string());
    let refspec = format!("HEAD:refs/heads/{}", branch);
    let ssh_hardening = git_ssh_hardening();

    let attempt_ssh = run_git_with_timeout_env_progress(
        repo,
        &["push", remote_name, &refspec],
        timeout_secs,
        &format!("push-to-{}", remote_name),
        &[
            ("GIT_SSH_COMMAND", &ssh_hardening),
            ("GIT_TERMINAL_PROMPT", "0"),
        ],
    )
    .await;

    if attempt_ssh.is_ok() {
        return Ok(());
    }

    let remote_url = get_remote_url(repo, remote_name)
        .ok_or_else(|| anyhow::anyhow!("remote {} not found", remote_name))?;

    let mut last_err = None;
    if is_safe_branch_name(&branch) {
        let fallback_label = format!("push-to-{}", remote_name);
        match push_https_fallback(repo, &remote_url, &refspec, timeout_secs, &fallback_label).await
        {
            Ok(()) => return Ok(()),
            Err(e) => last_err = Some(e),
        }
    }

    for attempt in 1..=retries.max(1) {
        match run_git_with_timeout_env_progress(
            repo,
            &["push", remote_name, "HEAD"],
            timeout_secs,
            &format!("push-to-{}", remote_name),
            &[
                ("GIT_SSH_COMMAND", &ssh_hardening),
                ("GIT_TERMINAL_PROMPT", "0"),
            ],
        )
        .await
        {
            Ok(()) => return Ok(()),
            Err(e) => {
                let err_str = e.to_string();
                let is_rejected = is_push_rejected(&err_str);
                // Permanent server-side rejection (protected branch, hook
                // declined, etc.) — retrying will not fix it. Return the
                // error immediately so the caller can log it once instead
                // of burning retries and flooding the incident ledger.
                if is_permanent_push_rejection(&err_str) {
                    return Err(e);
                }
                if is_rejected && force_when_behind {
                    match diagnose_divergence(repo, remote_name, &branch).await {
                        Ok(Divergence::RemotePurelyBehind) => {
                            let force_result = run_git_with_timeout_env_progress(
                                repo,
                                &[
                                    "push",
                                    "--force-with-lease",
                                    remote_name,
                                    &format!("HEAD:refs/heads/{}", branch),
                                ],
                                timeout_secs,
                                &format!("force-push-to-{}", remote_name),
                                &[
                                    ("GIT_SSH_COMMAND", &ssh_hardening),
                                    ("GIT_TERMINAL_PROMPT", "0"),
                                ],
                            )
                            .await;
                            if force_result.is_ok() {
                                return Ok(());
                            }
                        }
                        Ok(Divergence::Divergent) | Err(_) => {
                            last_err = Some(e);
                        }
                    }
                } else {
                    last_err = Some(e);
                }
                if attempt < retries.max(1) {
                    sleep(Duration::from_secs(attempt as u64)).await;
                }
            }
        }
    }
    Err(last_err.unwrap_or_else(|| anyhow::anyhow!("push to {} failed", remote_name)))
}

/// Result of divergence diagnosis.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Divergence {
    /// Remote is purely behind local (safe to force push).
    RemotePurelyBehind,
    /// Both sides have diverged.
    Divergent,
}

/// Check whether the remote is purely behind or truly diverged.
pub(crate) async fn diagnose_divergence(
    repo: &Path,
    remote_name: &str,
    branch: &str,
) -> Result<Divergence> {
    let local_head = run_git_capture_output(repo, &["rev-parse", "HEAD"], "rev-parse")?;
    let local_head = local_head.trim();
    let remote_ref = format!("refs/remotes/{}/{}", remote_name, branch);

    let rev_list_output = run_git_capture_output(
        repo,
        &[
            "rev-list",
            "--left-right",
            "--count",
            &format!("{}...{}", local_head, remote_ref),
        ],
        "rev-list",
    )?;

    let counts: Vec<&str> = rev_list_output.trim().split('\t').collect();
    if counts.len() != 2 {
        return Ok(Divergence::Divergent);
    }

    let local_ahead: u32 = match counts[0].parse() {
        Ok(v) => v,
        Err(e) => {
            eprintln!(
                "⚠️ failed to parse local ahead count from rev-list output (\"{}\"): {}",
                counts[0], e
            );
            return Ok(Divergence::Divergent);
        }
    };
    let remote_ahead: u32 = match counts[1].parse() {
        Ok(v) => v,
        Err(e) => {
            eprintln!(
                "⚠️ failed to parse remote ahead count from rev-list output (\"{}\"): {}",
                counts[1], e
            );
            return Ok(Divergence::Divergent);
        }
    };

    if remote_ahead == 0 && local_ahead > 0 {
        Ok(Divergence::RemotePurelyBehind)
    } else if remote_ahead > 0 {
        Ok(Divergence::Divergent)
    } else {
        Ok(Divergence::RemotePurelyBehind)
    }
}

/// Push to all remotes in priority order.
///
/// SEQUENTIAL (not concurrent) as of goal `87c1bf4d` (2026-06-16).
/// The previous concurrent implementation via `tokio::spawn` had
/// a race condition: when one remote (gitlab, codeberg) was
/// slower on the network than another (origin, github), a
/// subsequent fast-forward could land on the fast remote but be
/// rejected by the slow remote (which was still at an older tip).
/// After `push_max_retries` consecutive failures, the daemon
/// marked the repo PUSH_STUCK.
///
/// Sequential push trades ~3-6s of total wall-clock latency per
/// commit (4 remotes × ~1.5s each, instead of 1.5s in parallel)
/// for ELIMINATION of the race. The user-visible cadence is
/// similar because the daemon's apply phase deadline
/// (`pulse_interval_secs * 2` = 2s) was already causing trailing-
/// drain events on every commit when concurrent pushes took >2s.
pub(crate) async fn push_to_all_remotes(
    repo: &Path,
    remotes: &[RemoteConfig],
    timeout_secs: u64,
    retries: u32,
) -> Vec<(String, Result<()>)> {
    let mut sorted = remotes.to_vec();
    sorted.sort_by_key(|r| r.priority);

    // Push to remotes sequentially, in priority order. A failure
    // on one remote does NOT abort subsequent pushes: the daemon
    // continues to the next remote and reports the failure in
    // the returned Vec. The caller (sync_repo) handles per-remote
    // failure tracking.
    let mut results = Vec::new();
    for remote in sorted {
        let force_push = remote.force_push_when_behind;
        let result =
            push_to_named_remote(repo, &remote.name, timeout_secs, retries, force_push).await;
        results.push((remote.name, result));
    }
    results
}

/// Create a private repo on GitHub using `gh` CLI.
pub(crate) fn create_repo_on_github(account: &str, repo_name: &str) -> Result<String> {
    let mut cmd = gh_cmd();
    cmd.args(["repo", "create", repo_name, "--private"]);

    let output = cmd.output().with_context(|| "gh repo create failed")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if is_repo_already_exists(&stderr) {
            return Ok(format!("https://github.com/{}/{}.git", account, repo_name));
        }
        anyhow::bail!("gh repo create failed: {}", stderr.trim());
    }

    // Set default branch to main via API (gh CLI doesn't support --default-branch)
    let mut patch = gh_cmd();
    patch.args([
        "api",
        "-X",
        "PATCH",
        &format!("repos/{}/{}", account, repo_name),
        "--field",
        "default_branch=main",
    ]);
    let _ = patch.output(); // best effort — repo is created either way

    Ok(format!("https://github.com/{}/{}.git", account, repo_name))
}

/// Create a repo on GitLab using `glab` CLI.
pub(crate) fn create_repo_on_gitlab(
    account: &str,
    repo_name: &str,
    private: bool,
) -> Result<String> {
    let mut cmd = std::process::Command::new("glab");
    cmd.args(["repo", "create", repo_name]);
    if private {
        cmd.arg("--private");
    } else {
        cmd.arg("--public");
    }

    if let Some(token) = load_secret("GITLAB_TOKEN") {
        cmd.env("GITLAB_TOKEN", token);
    }

    let output = cmd.output().with_context(|| "glab repo create failed")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        if is_repo_already_exists(&stderr) {
            return Ok(format!("git@gitlab.com:{}/{}.git", account, repo_name));
        }
        anyhow::bail!("glab repo create failed: {}", stderr.trim());
    }

    Ok(format!("git@gitlab.com:{}/{}.git", account, repo_name))
}

/// Create a repo on Codeberg via REST API.
pub(crate) async fn create_repo_on_codeberg(
    token: &str,
    account: &str,
    repo_name: &str,
    api_endpoint: &str,
    private: bool,
) -> Result<String> {
    let client = reqwest::Client::new();
    let response = client
        .post(api_endpoint)
        .header("Authorization", format!("Bearer {}", token))
        .header("Content-Type", "application/json")
        .json(&serde_json::json!({
            "name": repo_name,
            "private": private,
            "default_branch": "main"
        }))
        .send()
        .await
        .with_context(|| "reqwest codeberg repo create failed")?;

    let status = response.status();
    if status.as_u16() == 409 || status.as_u16() == 422 {
        return Ok(format!("git@codeberg.org:{}/{}.git", account, repo_name));
    }

    if !status.is_success() {
        let body = response.text().await.unwrap_or_default();
        anyhow::bail!("codeberg repo create failed ({}): {}", status, body);
    }

    Ok(format!("git@codeberg.org:{}/{}.git", account, repo_name))
}

/// Auto-create a repo on the given remote platform.
pub(crate) async fn auto_create_repo(
    config: &RemoteConfig,
    repo_name: &str,
    private: bool,
) -> Result<String> {
    let account = config.resolve_account();
    match config.effective_auth_type() {
        AuthType::GitHub => create_repo_on_github(&account, repo_name),
        AuthType::GitLab => create_repo_on_gitlab(&account, repo_name, private),
        AuthType::Codeberg => {
            let token_var = config
                .auto_create_token_var
                .as_deref()
                .unwrap_or("CODEBERG_TOKEN");
            let token = load_secret(token_var)
                .with_context(|| format!("missing token for Codeberg (set {} env var or ~/.dracon/utilities/sync/secrets/*.env file)", token_var))?;
            let endpoint = config
                .api_endpoint
                .as_deref()
                .unwrap_or("https://codeberg.org/api/v1/user/repos");
            create_repo_on_codeberg(&token, &account, repo_name, endpoint, private).await
        }
        AuthType::Generic => anyhow::bail!("Generic auth cannot auto-create repos"),
    }
}

/// Auto-create all configured remotes for a repo.
pub(crate) async fn auto_create_all_remotes(
    remotes: &[RemoteConfig],
    repo_name: &str,
    private: bool,
) -> Vec<(String, Result<String>)> {
    let mut results = Vec::new();
    for remote in remotes {
        if remote.auto_create {
            let resolved_name = remote.resolve_repo_name(repo_name);
            let result = auto_create_repo(remote, &resolved_name, private).await;
            results.push((remote.name.clone(), result));
        }
    }
    results
}

// ============================================================================
// Tests for push_to_all_remotes (goal 87c1bf4d, 2026-06-16)
//
// The concurrent → sequential refactor must preserve three invariants:
//   1. Push order follows the `priority` field (lowest first)
//   2. An empty `remotes` slice returns an empty Vec (no spurious entries)
//   3. A failure on one remote does NOT abort subsequent pushes
//      (the daemon continues to the next remote)
//
// These tests use a tiny local-only mock to avoid network and SSH. They
// verify the *shape* of the returned Vec and the *order* of attempts, not
// the wire-level push behavior. Wire-level push is exercised by the live
// daemon and the integration tests.
// ============================================================================

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

    /// Helper: build a minimal RemoteConfig for testing.
    /// `name` and `priority` are the only fields that affect the sort.
    fn make_remote(name: &str, priority: u32) -> RemoteConfig {
        RemoteConfig {
            name: name.to_string(),
            push_url: format!("git@invalid.example.com:{}.git", name),
            auto_create: false,
            auto_create_account: String::new(),
            auth_type: crate::policy::AuthType::GitHub,
            priority,
            api_endpoint: None,
            auto_create_token_var: None,
            repo_name_map: std::collections::HashMap::new(),
            force_push_when_behind: false,
        }
    }

    /// Test: empty remotes list returns empty Vec.
    ///
    /// Regression test for goal `87c1bf4d`: the sequential
    /// implementation must handle the empty case without
    /// panicking or returning a spurious empty Ok entry.
    #[tokio::test]
    async fn test_push_to_all_remotes_empty_list_returns_empty() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let repo = tmp.path().join("test-repo");
        std::fs::create_dir_all(&repo).expect("create repo dir");
        let results = push_to_all_remotes(&repo, &[], 1, 1).await;
        assert!(
            results.is_empty(),
            "empty remotes should return empty Vec, got {:?}",
            results
        );
    }

    /// Test: remotes are attempted in priority order (lowest first).
    ///
    /// Regression test for goal `87c1bf4d`: the sort by `priority`
    /// must apply to the input `remotes` slice before any push is
    /// attempted. We don't verify the push actually succeeds (the
    /// fake URL will fail), but we verify the *order of attempts*
    /// by checking that all entries in the result Vec appear in
    /// priority order. The exact error vs. success status is
    /// implementation-dependent on the underlying git command,
    /// so we just check ordering.
    #[tokio::test]
    async fn test_push_to_all_remotes_respects_priority_order() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let repo = tmp.path().join("test-repo");
        std::fs::create_dir_all(&repo).expect("create repo dir");
        // Intentionally out of priority order
        let remotes = vec![
            make_remote("z-high-priority", 100),
            make_remote("a-low-priority", 1),
            make_remote("m-mid-priority", 50),
        ];
        let results = push_to_all_remotes(&repo, &remotes, 1, 1).await;
        assert_eq!(results.len(), 3, "should return one entry per remote");
        let names: Vec<&str> = results.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            names,
            vec!["a-low-priority", "m-mid-priority", "z-high-priority"],
            "remotes must be pushed in priority order (lowest first)"
        );
    }

    /// Test: a failure on one remote does NOT abort the loop.
    ///
    /// Regression test for goal `87c1bf4d`: the sequential
    /// implementation must NOT use `?` or early-return inside
    /// the loop. All remotes must be attempted, with their
    /// results collected in a Vec. The test uses three fake
    /// remotes with invalid URLs; all three should appear in
    /// the result Vec regardless of their success/failure.
    #[tokio::test]
    async fn test_push_to_all_remotes_continues_after_failure() {
        let tmp = tempfile::TempDir::new().expect("temp dir");
        let repo = tmp.path().join("test-repo");
        std::fs::create_dir_all(&repo).expect("create repo dir");
        let remotes = vec![
            make_remote("first-fails", 1),
            make_remote("second-fails", 2),
            make_remote("third-fails", 3),
        ];
        let results = push_to_all_remotes(&repo, &remotes, 1, 1).await;
        assert_eq!(
            results.len(),
            3,
            "all 3 remotes must be attempted (no early-return on failure)"
        );
        // The names must be in priority order
        let names: Vec<&str> = results.iter().map(|(n, _)| n.as_str()).collect();
        assert_eq!(
            names,
            vec!["first-fails", "second-fails", "third-fails"],
            "order must be by priority even when all fail"
        );
    }
}