surjection-core 1.1.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
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
//! Git remotes (SPEC 9.6, 9.8): any git URL, through the system `git` CLI
//! run in the store folder. The URL is passed to git unchanged; Surjection
//! has no host-specific code paths besides the optional `gh` helper.
//!
//! ```text
//! git [auth flags] push --progress <url> refs/heads/main:refs/heads/main 'refs/tags/*:refs/tags/*'
//! git [auth flags] fetch --progress <url> +refs/heads/main:refs/remotes/<name>/main '+refs/tags/*:refs/tags/*'
//! ```
//!
//! Auth (`auth` in `state/remotes.toml`):
//!
//! - `system` (default): no flags; whatever the user's git does.
//! - `gh`: `-c credential.helper= -c 'credential.helper=!gh auth git-credential'`.
//! - `token`: `-c credential.helper= -c 'credential.helper=!"<surjection>" git-credential --remote <name>'`;
//!   the token comes from the OS keyring through [`super::credential`].
//!
//! No token is ever put in git's environment or arguments. Git's own
//! prompts are off (`GIT_TERMINAL_PROMPT=0`; stdin is closed anyway);
//! credential managers with their own windows still work. A git that
//! prints nothing for [`IDLE_TIMEOUT`] is stopped. In a process that hides
//! console windows (the app, [`crate::process::hide_console_windows`]),
//! ssh runs in batch mode unless the user set their own ssh command
//! ([`ssh_batch_mode`]): a passphrase or host-key prompt nobody could see
//! fails at once instead of hanging until the idle timeout.

use std::collections::BTreeMap;
use std::ffi::{OsStr, OsString};
use std::io::{self, Read};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Arc, Mutex, mpsc};
use std::time::Duration;

use crate::brand;
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::process::{self, hide_window};
use crate::remote::config::{RemoteConfig, RemoteKind, check_name};
use crate::remote::folder::{PullReport, SiblingPull};
use crate::store::merge::{MergeOutcome, PendingMerge, RecordedConflict, write_merge_state};
use crate::store::{CommitId, LOCK_TIMEOUT, Store, StoreLock};

/// A git that prints nothing for this long is stopped (SPEC 9.6).
pub const IDLE_TIMEOUT: Duration = Duration::from_secs(120);

/// How a git remote authenticates.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum GitAuth {
    /// The user's own git setup (credential manager, SSH agent, ...).
    #[default]
    System,
    /// `gh auth git-credential`.
    Gh,
    /// A token from the OS keyring through `surject git-credential`.
    Token,
}

impl GitAuth {
    pub const fn as_str(self) -> &'static str {
        match self {
            GitAuth::System => "system",
            GitAuth::Gh => "gh",
            GitAuth::Token => "token",
        }
    }

    /// `auth` as configured; absent means `system`.
    pub fn parse(text: Option<&str>) -> Result<Self, CoreError> {
        match text {
            None | Some("system") => Ok(Self::System),
            Some("gh") => Ok(Self::Gh),
            Some("token") => Ok(Self::Token),
            Some(other) => Err(CoreError::new(
                ErrorCode::InvalidValue,
                format!("unknown auth {other:?}; expected system, gh or token"),
            )),
        }
    }
}

/// Whether `url` points at github.com (where `auth = gh` is offered).
pub fn is_github_url(url: &str) -> bool {
    let host = url_host(url).unwrap_or_default();
    host.eq_ignore_ascii_case("github.com") || host.eq_ignore_ascii_case("www.github.com")
}

/// The scheme and host (with port) of `url`: `https://host:port/path`,
/// `ssh://user@host/path` or scp-style `user@host:path` (scheme `ssh`).
/// `None` for local paths and `file://`.
pub fn url_scheme_host(url: &str) -> Option<(String, String)> {
    if let Some((scheme, rest)) = url.split_once("://") {
        if scheme.eq_ignore_ascii_case("file") {
            return None;
        }
        let authority = rest.split(['/', '?', '#']).next().unwrap_or_default();
        let host = authority.rsplit('@').next().unwrap_or_default();
        return (!host.is_empty())
            .then(|| (scheme.to_ascii_lowercase(), host.to_ascii_lowercase()));
    }
    // scp-style: [user@]host:path, where host has no '/' and is not a
    // drive letter.
    let (before, _) = url.split_once(':')?;
    if before.contains('/') || before.contains('\\') || before.len() < 2 {
        return None;
    }
    let host = before.rsplit('@').next().unwrap_or_default();
    (!host.is_empty()).then(|| ("ssh".to_owned(), host.to_ascii_lowercase()))
}

fn url_host(url: &str) -> Option<String> {
    url_scheme_host(url).map(|(_, host)| {
        host.rsplit_once(':')
            .map_or(host.clone(), |(name, _)| name.to_owned())
    })
}

/// `git` on `PATH`. Relative `PATH` entries are skipped, so a project
/// folder cannot shadow it.
pub fn locate(env: &Env, fs: &dyn Fs) -> Option<PathBuf> {
    locate_program(env, fs, "git")
}

/// `tool_not_found` for a missing git, as one sentence naming what needs
/// it (#29): the app shows this message on its own, never after the
/// generic "a required program is missing" text.
pub fn git_not_found(needed_for: &str) -> CoreError {
    CoreError::new(
        ErrorCode::ToolNotFound,
        format!("Git isn't installed or isn't on PATH; install Git to use {needed_for}."),
    )
}

/// An executable on `PATH` (`.exe` added on Windows).
pub(crate) fn locate_program(env: &Env, fs: &dyn Fs, name: &str) -> Option<PathBuf> {
    let (separator, file) = match env.os() {
        Os::Windows => (';', format!("{name}.exe")),
        Os::Linux | Os::MacOs => (':', name.to_owned()),
    };
    let path_var = env.var("PATH")?.to_string_lossy().into_owned();
    path_var
        .split(separator)
        .map(|dir| PathBuf::from(dir.trim().trim_matches('"')))
        .filter(|dir| dir.is_absolute())
        .map(|dir| dir.join(&file))
        .find(|candidate| fs.exists(candidate) && !fs.is_dir(candidate))
}

/// One process to run: program, arguments, the complete environment and
/// the working directory. Kept as data so tests can check what a git
/// receives.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Invocation {
    pub program: PathBuf,
    pub args: Vec<OsString>,
    pub env: Vec<(OsString, OsString)>,
    pub cwd: PathBuf,
}

/// What a finished (or stopped) process left.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct RunOutput {
    pub success: bool,
    pub stdout: String,
    pub stderr: String,
    /// Stopped after printing nothing for the runner's idle timeout.
    pub timed_out: bool,
}

/// Runs processes; tests record or script it.
pub trait Runner: Send + Sync {
    /// Runs `invocation`, calling `progress` with each line (or `\r`
    /// update) of its stderr.
    fn run(&self, invocation: &Invocation, progress: &mut dyn FnMut(&str))
    -> io::Result<RunOutput>;
}

/// The real thing: stdin closed, stdout and stderr captured, stopped when
/// silent for `idle_timeout`.
#[derive(Debug, Clone, Copy)]
pub struct SystemRunner {
    pub idle_timeout: Duration,
}

impl Default for SystemRunner {
    fn default() -> Self {
        Self {
            idle_timeout: IDLE_TIMEOUT,
        }
    }
}

/// The ssh command git runs from a process without console windows.
pub const SSH_BATCH_COMMAND: &str = "ssh -o BatchMode=yes";

/// `GIT_SSH_COMMAND=`[`SSH_BATCH_COMMAND`] for a git started without a
/// console window (`hiding`): ssh then fails at once ("Host key
/// verification failed.", "Permission denied (publickey).") where it
/// would ask for a passphrase or a new host key on a console nobody sees.
/// Keys in ssh-agent still work. `None` when `hiding` is off, the program
/// is not git, or the user chose an ssh command of their own
/// (`GIT_SSH_COMMAND` or `GIT_SSH` in the environment, `core.sshCommand` in
/// the arguments, or `configured()` saying git's config sets it; an
/// unknown answer counts as set). `configured` runs only when needed.
pub fn ssh_batch_mode(
    hiding: bool,
    invocation: &Invocation,
    configured: impl FnOnce() -> Option<bool>,
) -> Option<(OsString, OsString)> {
    let git = invocation
        .program
        .file_stem()
        .is_some_and(|stem| stem.eq_ignore_ascii_case("git"));
    if !hiding || !git {
        return None;
    }
    let own_env = invocation.env.iter().any(|(name, _)| {
        name.eq_ignore_ascii_case("GIT_SSH_COMMAND") || name.eq_ignore_ascii_case("GIT_SSH")
    });
    let own_arg = invocation.args.iter().any(|arg| {
        arg.to_string_lossy()
            .to_ascii_lowercase()
            .contains("core.sshcommand")
    });
    if own_env || own_arg || configured() != Some(false) {
        return None;
    }
    Some(("GIT_SSH_COMMAND".into(), SSH_BATCH_COMMAND.into()))
}

/// Whether git's config, as `invocation`'s git sees it in its folder, sets
/// `core.sshCommand` (`git config --get` exits 1 when it is unset); `None`
/// when git could not answer.
fn ssh_command_configured(invocation: &Invocation) -> Option<bool> {
    let status = hide_window(&mut Command::new(&invocation.program))
        .args(["config", "--get", "core.sshCommand"])
        .env_clear()
        .envs(invocation.env.iter().map(|(k, v)| (k, v)))
        .current_dir(&invocation.cwd)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status()
        .ok()?;
    match status.code() {
        Some(0) => Some(true),
        Some(1) => Some(false),
        _ => None,
    }
}

impl Runner for SystemRunner {
    fn run(
        &self,
        invocation: &Invocation,
        progress: &mut dyn FnMut(&str),
    ) -> io::Result<RunOutput> {
        let batch = ssh_batch_mode(process::hiding_console_windows(), invocation, || {
            ssh_command_configured(invocation)
        });
        let mut child = hide_window(&mut Command::new(&invocation.program))
            .args(&invocation.args)
            .env_clear()
            .envs(invocation.env.iter().map(|(k, v)| (k, v)))
            .envs(batch)
            .current_dir(&invocation.cwd)
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()?;
        let mut stdout = child.stdout.take().expect("piped");
        let mut stderr = child.stderr.take().expect("piped");
        let (sender, receiver) = mpsc::channel::<String>();
        let out_sender = sender.clone();
        let stdout_bytes = Arc::new(Mutex::new(Vec::new()));
        let out_bytes = Arc::clone(&stdout_bytes);
        // The readers end when every holder of the pipes has exited. A
        // helper git started (ssh, git-remote-https) can outlive git, so
        // after a timeout they are left to finish on their own, never
        // joined.
        let out_thread = std::thread::spawn(move || {
            let mut buf = [0u8; 4096];
            loop {
                match stdout.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        if let Ok(mut bytes) = out_bytes.lock() {
                            bytes.extend_from_slice(&buf[..n]);
                        }
                        // Output on stdout counts as activity too.
                        let _ = out_sender.send(String::new());
                    }
                }
            }
        });
        let err_thread = std::thread::spawn(move || {
            let mut line = Vec::new();
            let mut buf = [0u8; 4096];
            loop {
                match stderr.read(&mut buf) {
                    Ok(0) | Err(_) => break,
                    Ok(n) => {
                        for &byte in &buf[..n] {
                            if byte == b'\n' || byte == b'\r' {
                                let text = String::from_utf8_lossy(&line).into_owned();
                                line.clear();
                                if sender.send(text).is_err() {
                                    return;
                                }
                            } else {
                                line.push(byte);
                            }
                        }
                    }
                }
            }
            if !line.is_empty() {
                let _ = sender.send(String::from_utf8_lossy(&line).into_owned());
            }
        });
        let mut stderr_text = String::new();
        let mut timed_out = false;
        loop {
            match receiver.recv_timeout(self.idle_timeout) {
                Ok(line) => {
                    if !line.is_empty() {
                        progress(&line);
                        stderr_text.push_str(&line);
                        stderr_text.push('\n');
                    }
                }
                Err(mpsc::RecvTimeoutError::Timeout) => {
                    timed_out = true;
                    kill_tree(invocation, &mut child);
                    break;
                }
                Err(mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }
        let status = child.wait()?;
        if !timed_out {
            // Both pipes closed: the readers are done.
            let _ = out_thread.join();
            let _ = err_thread.join();
        }
        while let Ok(line) = receiver.try_recv() {
            if !line.is_empty() {
                stderr_text.push_str(&line);
                stderr_text.push('\n');
            }
        }
        let stdout = stdout_bytes.lock().map(|b| b.clone()).unwrap_or_default();
        Ok(RunOutput {
            success: status.success() && !timed_out,
            stdout: String::from_utf8_lossy(&stdout).into_owned(),
            stderr: stderr_text,
            timed_out,
        })
    }
}

/// Stops `child` and, on Windows, every process it started (Git for
/// Windows' `git.exe` on `PATH` is a launcher for the real git, which
/// starts `ssh` or `git-remote-https`): `taskkill /T /F`. Elsewhere the
/// direct child is killed; its helpers end when their pipes close.
fn kill_tree(invocation: &Invocation, child: &mut std::process::Child) {
    if cfg!(windows) {
        let root = invocation
            .env
            .iter()
            .find(|(name, _)| name.eq_ignore_ascii_case("SYSTEMROOT"))
            .map_or_else(
                || PathBuf::from(r"C:\Windows"),
                |(_, value)| PathBuf::from(value),
            );
        let _ = hide_window(&mut Command::new(
            root.join("System32").join("taskkill.exe"),
        ))
        .args(["/T", "/F", "/PID", &child.id().to_string()])
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .status();
    }
    let _ = child.kill();
}

/// How to reach git and, for `auth = token`, this binary.
pub struct GitCli<'a> {
    /// The git executable.
    pub git: PathBuf,
    pub runner: &'a dyn Runner,
    /// This binary, for `auth = token` (`surject git-credential`).
    pub helper: Option<PathBuf>,
}

impl<'a> GitCli<'a> {
    /// Git from `PATH`; `tool_not_found` without it.
    pub fn from_env(
        env: &Env,
        fs: &dyn Fs,
        runner: &'a dyn Runner,
        helper: Option<PathBuf>,
    ) -> Result<Self, CoreError> {
        let git = locate(env, fs).ok_or_else(|| git_not_found("Git remotes"))?;
        Ok(Self {
            git,
            runner,
            helper,
        })
    }
}

/// The `-c` flags for the remote's `auth`.
pub fn auth_args(
    remote: &RemoteConfig,
    helper: Option<&Path>,
    os: Os,
) -> Result<Vec<OsString>, CoreError> {
    // The name goes into a shell command line below; `remotes.toml` may
    // have been edited by hand.
    check_name(&remote.name)?;
    let helper_flag = |value: String| -> Vec<OsString> {
        vec![
            "-c".into(),
            "credential.helper=".into(),
            "-c".into(),
            format!("credential.helper={value}").into(),
        ]
    };
    Ok(match GitAuth::parse(remote.auth.as_deref())? {
        GitAuth::System => Vec::new(),
        GitAuth::Gh => helper_flag("!gh auth git-credential".to_owned()),
        GitAuth::Token => {
            let exe = helper.ok_or_else(|| {
                CoreError::new(
                    ErrorCode::InvalidValue,
                    "auth = token needs the surjection binary as the credential helper",
                )
            })?;
            // Git runs `!` helpers through a POSIX shell (Git for Windows'
            // sh too): forward slashes, inside double quotes.
            let mut path = exe.to_string_lossy().into_owned();
            if os == Os::Windows {
                path = path.replace('\\', "/");
            }
            if path.contains(['"', '$', '`', '\\']) {
                return Err(CoreError::new(
                    ErrorCode::InvalidPath,
                    "the surjection binary's path cannot be quoted for git",
                )
                .with_path(exe));
            }
            helper_flag(format!(
                "!\"{path}\" git-credential --remote {}",
                remote.name
            ))
        }
    })
}

fn url(remote: &RemoteConfig) -> Result<&str, CoreError> {
    check_name(&remote.name)?;
    if remote.kind != RemoteKind::Git {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("{} is not a git remote", remote.name),
        ));
    }
    let url = remote
        .url
        .as_deref()
        .filter(|u| !u.trim().is_empty())
        .ok_or_else(|| {
            CoreError::new(
                ErrorCode::MissingField,
                format!("git remote {} has no url", remote.name),
            )
        })?;
    if url.starts_with('-') {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("git remote {} has an invalid url {url:?}", remote.name),
        ));
    }
    Ok(url)
}

/// Git's repository-local variables (`git rev-parse --local-env-vars`): an
/// inherited `GIT_DIR` (Surjection run from a git hook) would point the push
/// at another repository.
const REPOSITORY_VARS: [&str; 16] = [
    "GIT_ALTERNATE_OBJECT_DIRECTORIES",
    "GIT_COMMON_DIR",
    "GIT_CONFIG",
    "GIT_CONFIG_COUNT",
    "GIT_CONFIG_PARAMETERS",
    "GIT_DIR",
    "GIT_GRAFT_FILE",
    "GIT_IMPLICIT_WORK_TREE",
    "GIT_INDEX_FILE",
    "GIT_INTERNAL_SUPER_PREFIX",
    "GIT_NAMESPACE",
    "GIT_NO_REPLACE_OBJECTS",
    "GIT_OBJECT_DIRECTORY",
    "GIT_PREFIX",
    "GIT_REPLACE_REF_BASE",
    "GIT_SHALLOW_FILE",
];

fn invocation(store: &Store<'_>, git: &GitCli<'_>, args: Vec<OsString>) -> Invocation {
    let overridden = |name: &OsStr| {
        let name = name.to_string_lossy();
        name.eq_ignore_ascii_case("GIT_TERMINAL_PROMPT")
            || name.eq_ignore_ascii_case("GIT_WORK_TREE")
            || name.eq_ignore_ascii_case(brand::HOME_ENV_VAR)
            || name.eq_ignore_ascii_case(brand::legacy::HOME_ENV_VAR)
            || REPOSITORY_VARS
                .iter()
                .any(|var| name.eq_ignore_ascii_case(var))
    };
    let mut env: Vec<(OsString, OsString)> = store
        .env()
        .vars()
        .map(|(name, value)| (OsString::from(name), value.to_owned()))
        .filter(|(name, _)| !overridden(name))
        .collect();
    env.push(("GIT_TERMINAL_PROMPT".into(), "0".into()));
    // A `surject git-credential` helper reads this data directory's
    // remotes, also when it was chosen with `--home`.
    if let Some(home) = store.root().parent() {
        env.push((brand::HOME_ENV_VAR.into(), home.as_os_str().to_owned()));
    }
    Invocation {
        program: git.git.clone(),
        args,
        env,
        cwd: store.root().to_path_buf(),
    }
}

/// A push refused because the remote has commits this machine lacks.
fn is_non_fast_forward(output: &RunOutput) -> bool {
    let lower = output.stderr.to_lowercase();
    lower.contains("[rejected]")
        && (lower.contains("non-fast-forward") || lower.contains("fetch first"))
}

/// Maps a failed git run to an error code by its message
/// [verify: wording per git version and host].
fn failure(remote: &RemoteConfig, action: &str, output: &RunOutput) -> CoreError {
    let lower = output.stderr.to_lowercase();
    let first = output
        .stderr
        .lines()
        .map(str::trim)
        .rfind(|line| {
            line.starts_with("fatal:") || line.starts_with("error:") || line.contains("rejected]")
        })
        .or_else(|| {
            output
                .stderr
                .lines()
                .map(str::trim)
                .rfind(|l| !l.is_empty())
        })
        .unwrap_or("no error message");
    let first: String = first.chars().take(300).collect();
    let code = if output.timed_out {
        ErrorCode::RemoteUnreachable
    } else if lower.contains("[rejected]")
        || lower.contains("[remote rejected]")
        || lower.contains("failed to push some refs")
    {
        ErrorCode::RemoteRejected
    } else if lower.contains("authentication failed")
        || lower.contains("permission denied (publickey")
        || lower.contains("could not read username")
        || lower.contains("could not read password")
        || lower.contains("terminal prompts disabled")
        || lower.contains("returned error: 401")
        || lower.contains("returned error: 403")
    {
        ErrorCode::RemoteAuthFailed
    } else {
        ErrorCode::RemoteUnreachable
    };
    let message = if output.timed_out {
        format!(
            "git {action} with {} printed nothing for too long and was stopped",
            remote.name
        )
    } else {
        format!("git {action} with {} failed: {first}", remote.name)
    };
    CoreError::new(code, message)
}

/// Runs git; only a failure to start it is an error here.
fn run_raw(
    store: &Store<'_>,
    git: &GitCli<'_>,
    args: Vec<OsString>,
    progress: &mut dyn FnMut(&str),
) -> Result<RunOutput, CoreError> {
    let invocation = invocation(store, git, args);
    git.runner.run(&invocation, progress).map_err(|err| {
        CoreError::new(ErrorCode::ToolNotFound, format!("cannot run git: {err}"))
            .with_path(&git.git)
    })
}

fn run(
    store: &Store<'_>,
    git: &GitCli<'_>,
    remote: &RemoteConfig,
    action: &str,
    args: Vec<OsString>,
    progress: &mut dyn FnMut(&str),
) -> Result<RunOutput, CoreError> {
    let output = run_raw(store, git, args, progress)?;
    if output.success {
        Ok(output)
    } else {
        Err(failure(remote, action, &output))
    }
}

/// What a push did.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct GitPush {
    pub head: CommitId,
    /// The pull a rejected push ran before its one retry.
    pub pulled: Option<PullReport>,
}

/// `git push` of `main` and every tag. A non-fast-forward rejection pulls
/// (merges) and retries once (SPEC 9.8); a pull with conflicts stops there
/// with `merge_conflict`, and a pull that failed with its own error. Other
/// rejections (a protected branch, a hook) are `remote_rejected` at once.
pub fn push(
    store: &Store<'_>,
    git: &GitCli<'_>,
    remote: &RemoteConfig,
    progress: &mut dyn FnMut(&str),
) -> Result<GitPush, CoreError> {
    match push_once(store, git, remote, progress)? {
        Ok(head) => Ok(GitPush { head, pulled: None }),
        Err(output) if is_non_fast_forward(&output) => {
            let report = pull(store, git, remote, progress)?;
            if let Some(err) = report
                .siblings
                .iter()
                .find_map(|s| s.outcome.as_ref().err())
            {
                return Err(err.clone());
            }
            if report.conflicts() > 0 {
                return Err(CoreError::new(
                    ErrorCode::MergeConflict,
                    format!(
                        "{} has changes that conflict with this machine's; nothing pushed",
                        remote.name
                    ),
                ));
            }
            match push_once(store, git, remote, progress)? {
                Ok(head) => Ok(GitPush {
                    head,
                    pulled: Some(report),
                }),
                Err(output) => Err(failure(remote, "push", &output)),
            }
        }
        Err(output) => Err(failure(remote, "push", &output)),
    }
}

/// One `git push`: the head pushed, or the failed run.
fn push_once(
    store: &Store<'_>,
    git: &GitCli<'_>,
    remote: &RemoteConfig,
    progress: &mut dyn FnMut(&str),
) -> Result<Result<CommitId, RunOutput>, CoreError> {
    let url = url(remote)?;
    let head = store.head()?;
    let mut args = auth_args(remote, git.helper.as_deref(), store.env().os())?;
    args.extend(
        [
            "push",
            "--progress",
            "--",
            url,
            "refs/heads/main:refs/heads/main",
            "refs/tags/*:refs/tags/*",
        ]
        .map(OsString::from),
    );
    let output = run_raw(store, git, args, progress)?;
    Ok(if output.success {
        Ok(head)
    } else {
        Err(output)
    })
}

/// `git fetch` of `main` into `refs/remotes/<name>/main` and of every tag.
/// `None` when the remote has no `main` yet (a new, empty repository).
pub fn fetch(
    store: &Store<'_>,
    git: &GitCli<'_>,
    remote: &RemoteConfig,
    progress: &mut dyn FnMut(&str),
) -> Result<Option<CommitId>, CoreError> {
    let url = url(remote)?;
    let tracking = format!("refs/remotes/{}/main", remote.name);
    let mut args = auth_args(remote, git.helper.as_deref(), store.env().os())?;
    args.extend(
        [
            "fetch".to_owned(),
            "--progress".to_owned(),
            "--no-write-fetch-head".to_owned(),
            "--".to_owned(),
            url.to_owned(),
            format!("+refs/heads/main:{tracking}"),
            "+refs/tags/*:refs/tags/*".to_owned(),
        ]
        .map(OsString::from),
    );
    let _lock = StoreLock::acquire(store.fs(), store.state_dir(), LOCK_TIMEOUT)?;
    match run(store, git, remote, "fetch", args, progress) {
        Ok(_) => {}
        Err(err) if is_empty_remote(&err) => return Ok(None),
        Err(err) => return Err(err),
    }
    store.reference_target(&tracking)
}

fn is_empty_remote(err: &CoreError) -> bool {
    let lower = err.message().to_lowercase();
    lower.contains("couldn't find remote ref") || lower.contains("could not find remote ref")
}

/// Fetches and merges the remote's `main` (SPEC 9.9): tagged
/// `auto/pre-pull/<ts>` when it brings anything; conflicts go to
/// `state/merge/MERGE_STATE.json` and leave HEAD as it was.
pub fn pull(
    store: &Store<'_>,
    git: &GitCli<'_>,
    remote: &RemoteConfig,
    progress: &mut dyn FnMut(&str),
) -> Result<PullReport, CoreError> {
    let tag_targets = |store: &Store<'_>| -> Result<BTreeMap<String, CommitId>, CoreError> {
        Ok(store
            .tags()?
            .into_iter()
            .map(|tag| (tag.name, tag.target))
            .collect())
    };
    let before = tag_targets(store)?;
    let incoming = fetch(store, git, remote, progress)?;
    let after = tag_targets(store)?;
    let head_before = store.head()?;
    let mut report = PullReport {
        remote: remote.name.clone(),
        tag: None,
        head_before: head_before.clone(),
        head_after: head_before,
        siblings: Vec::new(),
        artifacts: Vec::new(),
        tags_imported: after
            .keys()
            .filter(|name| !before.contains_key(*name))
            .cloned()
            .collect(),
        // SPEC 9.6 fetches tags with `+`: a same-named tag of the remote
        // replaces ours. Never silently.
        tags_moved: after
            .iter()
            .filter(|(name, target)| before.get(*name).is_some_and(|old| old != *target))
            .map(|(name, _)| name.clone())
            .collect(),
    };
    // A head at another store version is refused before it is tagged or
    // merged. The refusal is the remote's outcome, so the tags the fetch
    // already moved are still reported (SPEC 9.6: never silently).
    let refusal = incoming.as_ref().and_then(|incoming| {
        store
            .check_incoming(incoming, &format!("The remote \"{}\"", remote.name))
            .err()
    });
    // Only a merged head replaces the conflicts recorded for this remote.
    let attempted = if incoming.is_some() && refusal.is_none() {
        vec![remote.name.clone()]
    } else {
        Vec::new()
    };
    let mut pending = Vec::new();
    if let Some(incoming) = incoming {
        let outcome = match refusal {
            Some(err) => Err(err),
            None => {
                if !store.contains(&incoming) {
                    report.tag = Some(store.create_auto_tag("pre-pull")?);
                }
                store.merge_incoming(&incoming, &remote.name)
            }
        };
        if let Ok(MergeOutcome::Conflicts { base, conflicts }) = &outcome {
            pending.push(PendingMerge {
                source: remote.name.clone(),
                incoming: incoming.to_string(),
                base: base.as_ref().map(ToString::to_string),
                conflicts: conflicts.iter().map(RecordedConflict::from).collect(),
            });
        }
        report.siblings.push(SiblingPull {
            machine_id: None,
            label: remote.name.clone(),
            outcome,
        });
    }
    write_merge_state(store.fs(), store.state_dir(), &attempted, &pending)?;
    report.head_after = store.head()?;
    Ok(report)
}