ag-git 0.12.9

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

use tokio::task::spawn_blocking;

use super::error::GitError;

/// Returns the origin repository URL normalized to HTTPS form when possible.
///
/// # Arguments
/// * `repo_path` - Path to a git repository or worktree
///
/// # Returns
/// Ok(url) on success, Err([`GitError`]) on failure.
///
/// # Errors
/// Returns an error if the remote URL cannot be read via `git remote get-url`.
pub(crate) async fn repo_url(repo_path: PathBuf) -> Result<String, GitError> {
    let remote = run_git_command(
        repo_path,
        vec![
            "remote".to_string(),
            "get-url".to_string(),
            "origin".to_string(),
        ],
        "Git remote get-url failed".to_string(),
    )
    .await?;

    Ok(normalize_repo_url(remote.trim()))
}

/// Resolves the main repository root for a repository or linked worktree.
///
/// Uses `git rev-parse --git-dir --git-common-dir`, normalizes both paths to
/// absolute form, detects whether `repo_path` is a linked worktree (`git-dir`
/// differs from `git-common-dir`), and then returns the shared repository
/// root.
///
/// # Arguments
/// * `repo_path` - Path to a git repository or worktree
///
/// # Returns
/// Ok(path) containing the main repository root, Err([`GitError`]) on failure.
///
/// # Errors
/// Returns an error if git metadata cannot be queried from `repo_path`.
pub(crate) async fn main_repo_root(repo_path: PathBuf) -> Result<PathBuf, GitError> {
    spawn_blocking(move || main_repo_root_sync(&repo_path)).await?
}

/// Resolves the main working checkout for a repository or linked worktree.
///
/// Returns `Some(path)` with the main working checkout root for non-bare shared
/// repositories, and `None` when the shared repository is bare because a bare
/// repository has no main working checkout.
///
/// # Arguments
/// * `repo_path` - Path to a git repository or worktree
///
/// # Returns
/// Ok(Some(path)) with the main working checkout, Ok(None) when the shared
/// repository is bare, Err([`GitError`]) on failure.
///
/// # Errors
/// Returns an error if git metadata cannot be queried from `repo_path`.
pub(crate) async fn main_checkout_working_tree(
    repo_path: PathBuf,
) -> Result<Option<PathBuf>, GitError> {
    spawn_blocking(move || main_checkout_working_tree_sync(&repo_path)).await?
}

/// Resolves the main repository root for `repo_path` in synchronous code.
///
/// Returns the administrative root: the main working checkout for non-bare
/// shared repositories and the bare common git directory for bare shared
/// repositories. Both are valid working directories for `git worktree` and
/// branch administration commands.
pub(super) fn main_repo_root_sync(repo_path: &Path) -> Result<PathBuf, GitError> {
    match resolve_shared_repo_sync(repo_path)? {
        SharedRepo::Working(path) | SharedRepo::Bare(path) => Ok(path),
    }
}

/// Resolves the main working checkout for `repo_path` in synchronous code.
///
/// Returns `Some(path)` for non-bare shared repositories and `None` for bare
/// shared repositories, which have no main working checkout.
pub(super) fn main_checkout_working_tree_sync(
    repo_path: &Path,
) -> Result<Option<PathBuf>, GitError> {
    match resolve_shared_repo_sync(repo_path)? {
        SharedRepo::Working(path) => Ok(Some(path)),
        SharedRepo::Bare(_) => Ok(None),
    }
}

/// Classifies the shared repository backing a worktree.
pub(super) enum SharedRepo {
    /// Non-bare shared repository. The path is the main working checkout root.
    Working(PathBuf),
    /// Bare shared repository. The path is the bare common git directory, which
    /// has no main working checkout but is a valid administrative working
    /// directory for `git worktree` and branch commands.
    Bare(PathBuf),
}

/// Resolves the shared repository backing `repo_path`.
///
/// Reads the git and common git directories, detects whether the shared
/// repository is bare by running `git rev-parse --is-bare-repository` inside
/// the common git directory, and returns [`SharedRepo::Bare`] with the bare
/// common git directory when bare. Otherwise returns [`SharedRepo::Working`]
/// with the main working checkout root, matching the historical
/// `main_repo_root_sync` resolution for non-bare layouts.
///
/// # Errors
/// Returns an error if git metadata cannot be queried from `repo_path`.
pub(super) fn resolve_shared_repo_sync(repo_path: &Path) -> Result<SharedRepo, GitError> {
    let (git_dir, git_common_dir) = git_directory_paths(repo_path)?;

    // Probe the common git directory directly by running git there, so the
    // shared repository's bareness is detected even from a linked worktree
    // (where `--is-bare-repository` reports the worktree, not the shared repo).
    // Passing the directory through `current_dir` keeps non-UTF-8 paths intact,
    // unlike converting it to a `--git-dir` string argument.
    let is_bare = run_git_command_sync(
        &git_common_dir,
        &["rev-parse", "--is-bare-repository"],
        "Git rev-parse --is-bare-repository failed",
    )?;
    if is_bare.trim() == "true" {
        return Ok(SharedRepo::Bare(git_common_dir));
    }

    if git_dir == git_common_dir {
        return Ok(SharedRepo::Working(repo_root_from_git_dir(
            repo_path, &git_dir,
        )?));
    }

    Ok(SharedRepo::Working(repo_root_from_git_dir(
        repo_path,
        &git_common_dir,
    )?))
}

/// Resolves the git directory path for a repository root or worktree root.
pub(super) fn resolve_git_dir(repo_dir: &Path) -> Option<PathBuf> {
    let dot_git = repo_dir.join(".git");
    if dot_git.is_dir() {
        return Some(dot_git);
    }

    if dot_git.is_file() {
        let content = fs::read_to_string(&dot_git).ok()?;
        let git_dir_line = content.lines().find(|line| line.starts_with("gitdir:"))?;
        let git_dir_path = git_dir_line.trim_start_matches("gitdir:").trim();
        let git_dir = PathBuf::from(git_dir_path);

        if git_dir.is_absolute() {
            return Some(git_dir);
        }

        return Some(repo_dir.join(git_dir));
    }

    None
}

/// Runs a git command in a blocking task and returns stdout text.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `args` - Git command arguments
/// * `error_context` - Prefix used for command failure messages
///
/// # Returns
/// The command stdout on success.
///
/// # Errors
/// Returns [`GitError::Join`] if the blocking task panics, or
/// [`GitError::CommandFailed`] if spawning fails or the command exits with
/// a non-zero status.
pub(super) async fn run_git_command(
    repo_path: PathBuf,
    args: Vec<String>,
    error_context: String,
) -> Result<String, GitError> {
    spawn_blocking(move || {
        let argument_refs: Vec<&str> = args.iter().map(String::as_str).collect();

        run_git_command_sync(&repo_path, &argument_refs, &error_context)
    })
    .await?
}

/// Runs a git command in `repo_path` and returns stdout text.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `args` - Git command arguments
/// * `error_context` - Human-readable label prepended to the stderr detail on
///   failure (e.g. `"Failed to read squash merge diff"`)
///
/// # Returns
/// The command stdout on success.
///
/// # Errors
/// Returns [`GitError::CommandFailed`] with the concrete git invocation in
/// `command` and the `error_context` plus stderr/stdout detail in `stderr`.
pub(super) fn run_git_command_sync(
    repo_path: &Path,
    args: &[&str],
    error_context: &str,
) -> Result<String, GitError> {
    let output = run_git_command_output_sync(repo_path, args)?;
    if !output.status.success() {
        let detail = command_output_detail(&output.stdout, &output.stderr);
        let git_invocation = format_git_invocation(args);

        return Err(GitError::CommandFailed {
            command: git_invocation,
            stderr: format!("{error_context}: {detail}"),
        });
    }

    Ok(String::from_utf8_lossy(&output.stdout).into_owned())
}

/// Formats the full git invocation string from command arguments.
fn format_git_invocation(args: &[&str]) -> String {
    if args.is_empty() {
        return "git".to_string();
    }

    format!("git {}", args.join(" "))
}

/// Runs a git command in `repo_path` and returns raw process output.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `args` - Git command arguments
///
/// # Returns
/// The process output, including status, stdout, and stderr.
///
/// # Errors
/// Returns [`GitError::CommandFailed`] if spawning the command fails.
pub(super) fn run_git_command_output_sync(
    repo_path: &Path,
    args: &[&str],
) -> Result<Output, GitError> {
    run_git_command_output_with_env_sync(repo_path, args, &[])
}

/// Runs a git command in `repo_path` with environment overrides and returns
/// raw process output.
///
/// Applies non-interactive defaults (`GIT_TERMINAL_PROMPT=0`,
/// `GCM_INTERACTIVE=never`, and SSH batch mode) and closes stdin so
/// credential failures do not block waiting for terminal input.
/// Caller-provided `environment` pairs are then applied and can override
/// these defaults.
///
/// # Arguments
/// * `repo_path` - Path to the git repository or worktree
/// * `args` - Git command arguments
/// * `environment` - Environment variables applied to the git process
///
/// # Returns
/// The process output, including status, stdout, and stderr.
///
/// # Errors
/// Returns [`GitError::CommandFailed`] if spawning the command fails.
pub(super) fn run_git_command_output_with_env_sync(
    repo_path: &Path,
    args: &[&str],
    environment: &[(&str, &str)],
) -> Result<Output, GitError> {
    let mut command = Command::new("git");
    command
        .args(args)
        .current_dir(repo_path)
        .stdin(Stdio::null());
    apply_non_interactive_environment(&mut command);

    for (key, value) in environment {
        command.env(key, value);
    }

    command.output().map_err(|error| GitError::CommandFailed {
        command: format_git_invocation(args),
        stderr: error.to_string(),
    })
}

/// Applies non-interactive defaults so git failures return immediately instead
/// of waiting for terminal credential prompts.
fn apply_non_interactive_environment(command: &mut Command) {
    let git_ssh_command = std::env::var("GIT_SSH_COMMAND").map_or_else(
        |_| "ssh -o BatchMode=yes".to_string(),
        |configured_command| format!("{configured_command} -o BatchMode=yes"),
    );

    command
        .env("GIT_TERMINAL_PROMPT", "0")
        .env("GCM_INTERACTIVE", "never")
        .env("GIT_SSH_COMMAND", git_ssh_command);
}

/// Extracts the best human-readable error detail from command output.
pub(super) fn command_output_detail(stdout: &[u8], stderr: &[u8]) -> String {
    let stderr_text = String::from_utf8_lossy(stderr).trim().to_string();
    if !stderr_text.is_empty() {
        return stderr_text;
    }

    let stdout_text = String::from_utf8_lossy(stdout).trim().to_string();
    if !stdout_text.is_empty() {
        return stdout_text;
    }

    "Unknown git error".to_string()
}

/// Converts SSH-style GitHub remotes into HTTPS while preserving other URLs.
fn normalize_repo_url(remote: &str) -> String {
    let trimmed = remote.trim_end_matches(".git");
    if let Some(path) = trimmed.strip_prefix("git@github.com:") {
        return format!("https://github.com/{path}");
    }

    if let Some(path) = trimmed.strip_prefix("ssh://git@github.com/") {
        return format!("https://github.com/{path}");
    }

    trimmed.to_string()
}

/// Reads absolute git and common git directory paths for `repo_path`.
fn git_directory_paths(repo_path: &Path) -> Result<(PathBuf, PathBuf), GitError> {
    let stdout = run_git_command_sync(
        repo_path,
        &["rev-parse", "--git-dir", "--git-common-dir"],
        "Git rev-parse failed",
    )?;
    let mut lines = stdout
        .lines()
        .map(str::trim)
        .filter(|line| !line.is_empty());
    let git_dir = lines
        .next()
        .ok_or_else(|| GitError::OutputParse("Git rev-parse output missing git-dir".to_string()))?;
    let git_common_dir = lines.next().ok_or_else(|| {
        GitError::OutputParse("Git rev-parse output missing git-common-dir".to_string())
    })?;

    Ok((
        normalize_git_dir_path(repo_path, git_dir),
        normalize_git_dir_path(repo_path, git_common_dir),
    ))
}

/// Converts a git directory path (typically `.git`) into repository root.
fn repo_root_from_git_dir(repo_path: &Path, git_dir: &Path) -> Result<PathBuf, GitError> {
    if git_dir
        .file_name()
        .and_then(|name| name.to_str())
        .is_some_and(|name| name == ".git")
    {
        return git_dir.parent().map(Path::to_path_buf).ok_or_else(|| {
            GitError::OutputParse(format!(
                "Git directory has no parent: {}",
                git_dir.display()
            ))
        });
    }

    let root = run_git_command_sync(
        repo_path,
        &["rev-parse", "--show-toplevel"],
        "Git rev-parse --show-toplevel failed",
    )?;
    let root = root.trim().to_string();
    if root.is_empty() {
        return Err(GitError::OutputParse(
            "Git rev-parse --show-toplevel returned empty output".to_string(),
        ));
    }

    Ok(PathBuf::from(root))
}

/// Normalizes a git metadata path into absolute form for path comparisons.
fn normalize_git_dir_path(repo_path: &Path, git_path: &str) -> PathBuf {
    let git_path = PathBuf::from(git_path);
    let git_path = if git_path.is_absolute() {
        git_path
    } else {
        repo_path.join(git_path)
    };

    std::fs::canonicalize(&git_path).unwrap_or(git_path)
}

#[cfg(test)]
mod tests {
    use tempfile::tempdir;

    use super::*;

    #[test]
    fn test_apply_non_interactive_environment_sets_git_prompt_controls() {
        // Arrange
        let mut command = Command::new("git");

        // Act
        apply_non_interactive_environment(&mut command);

        // Assert
        let env_pairs: Vec<(String, String)> = command
            .get_envs()
            .filter_map(|(key, value)| {
                value.map(|resolved_value| {
                    (
                        key.to_string_lossy().to_string(),
                        resolved_value.to_string_lossy().to_string(),
                    )
                })
            })
            .collect();
        assert!(
            env_pairs
                .iter()
                .any(|(key, value)| key == "GIT_TERMINAL_PROMPT" && value == "0")
        );
        assert!(
            env_pairs
                .iter()
                .any(|(key, value)| key == "GCM_INTERACTIVE" && value == "never")
        );
        assert!(
            env_pairs
                .iter()
                .any(|(key, value)| key == "GIT_SSH_COMMAND" && value.contains("BatchMode=yes"))
        );
    }

    #[test]
    fn test_command_output_detail_prefers_stderr_then_stdout_then_unknown() {
        // Arrange

        // Act
        let stderr_detail = command_output_detail(b"stdout detail", b"stderr detail");
        let stdout_detail = command_output_detail(b"stdout detail", b"");
        let unknown_detail = command_output_detail(b"", b"");

        // Assert
        assert_eq!(stderr_detail, "stderr detail");
        assert_eq!(stdout_detail, "stdout detail");
        assert_eq!(unknown_detail, "Unknown git error");
    }

    #[test]
    fn test_normalize_repo_url_converts_supported_github_formats() {
        // Arrange

        // Act
        let ssh_short = normalize_repo_url("git@github.com:agentty-xyz/agentty.git");
        let ssh_long = normalize_repo_url("ssh://git@github.com/agentty-xyz/agentty.git");
        let passthrough = normalize_repo_url("https://example.com/agentty-xyz/agentty.git");

        // Assert
        assert_eq!(ssh_short, "https://github.com/agentty-xyz/agentty");
        assert_eq!(ssh_long, "https://github.com/agentty-xyz/agentty");
        assert_eq!(passthrough, "https://example.com/agentty-xyz/agentty");
    }

    #[test]
    fn test_resolve_git_dir_supports_directories_and_gitdir_files() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let repo_with_directory = temp_dir.path().join("repo-directory");
        let repo_with_absolute_file = temp_dir.path().join("repo-absolute");
        let repo_with_relative_file = temp_dir.path().join("repo-relative");
        let relative_git_dir = repo_with_relative_file.join(".actual-git");
        let malformed_repo = temp_dir.path().join("repo-malformed");
        fs::create_dir_all(repo_with_directory.join(".git"))
            .expect("failed to create .git directory repo");
        fs::create_dir_all(&repo_with_absolute_file).expect("failed to create absolute repo");
        fs::create_dir_all(&repo_with_relative_file).expect("failed to create relative repo");
        fs::create_dir_all(&relative_git_dir).expect("failed to create relative git dir");
        fs::create_dir_all(&malformed_repo).expect("failed to create malformed repo");
        fs::write(
            repo_with_absolute_file.join(".git"),
            format!("gitdir: {}", temp_dir.path().join("absolute-git").display()),
        )
        .expect("failed to write absolute gitdir file");
        fs::write(
            repo_with_relative_file.join(".git"),
            "gitdir: .actual-git\n",
        )
        .expect("failed to write relative gitdir file");
        fs::write(malformed_repo.join(".git"), "not-a-gitdir-file")
            .expect("failed to write malformed gitdir file");

        // Act
        let directory_git_dir = resolve_git_dir(&repo_with_directory);
        let absolute_git_dir = resolve_git_dir(&repo_with_absolute_file);
        let relative_git_dir_resolved = resolve_git_dir(&repo_with_relative_file);
        let malformed_git_dir = resolve_git_dir(&malformed_repo);

        // Assert
        assert_eq!(directory_git_dir, Some(repo_with_directory.join(".git")));
        assert_eq!(absolute_git_dir, Some(temp_dir.path().join("absolute-git")));
        assert_eq!(relative_git_dir_resolved, Some(relative_git_dir));
        assert_eq!(malformed_git_dir, None);
    }

    #[test]
    fn test_run_git_command_sync_returns_command_failed_on_invalid_subcommand() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");

        // Act
        let result = run_git_command_sync(
            temp_dir.path(),
            &["definitely-not-a-git-subcommand"],
            "Git command failed",
        );

        // Assert
        let error = result.expect_err("invalid git command should fail");
        assert!(
            matches!(&error, GitError::CommandFailed { command, stderr }
                if command == "git definitely-not-a-git-subcommand"
                    && stderr.contains("Git command failed")),
            "unexpected error: {error:?}"
        );
    }

    #[test]
    fn test_main_repo_root_sync_returns_command_failed_outside_git_repository() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");

        // Act
        let result = main_repo_root_sync(temp_dir.path());

        // Assert
        let error = result.expect_err("non-repo should fail");
        assert!(
            matches!(&error, GitError::CommandFailed { command, stderr }
                if command.starts_with("git rev-parse")
                    && stderr.contains("Git rev-parse failed")),
            "unexpected error: {error:?}"
        );
    }

    /// Runs a setup git command in `cwd`, asserting success and returning
    /// trimmed stdout.
    fn run_setup_git(cwd: &Path, args: &[&str]) -> String {
        let output = Command::new("git")
            .args(args)
            .current_dir(cwd)
            .output()
            .expect("failed to run setup git command");
        assert!(
            output.status.success(),
            "git command {args:?} failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        String::from_utf8_lossy(&output.stdout).trim().to_string()
    }

    #[test]
    fn test_bare_layout_resolves_bare_admin_root_and_no_working_checkout() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let root = temp_dir.path();
        let bare_dir = root.join(".bare");
        run_setup_git(root, &["init", "--bare", ".bare"]);
        run_setup_git(&bare_dir, &["config", "user.name", "Test User"]);
        run_setup_git(&bare_dir, &["config", "user.email", "test@example.com"]);
        let empty_tree =
            run_setup_git(&bare_dir, &["hash-object", "-w", "-t", "tree", "/dev/null"]);
        let commit = run_setup_git(&bare_dir, &["commit-tree", &empty_tree, "-m", "init"]);
        run_setup_git(&bare_dir, &["update-ref", "refs/heads/main", &commit]);
        run_setup_git(&bare_dir, &["symbolic-ref", "HEAD", "refs/heads/main"]);
        let main_worktree = root.join("main");
        let session_worktree = root.join("session");
        run_setup_git(
            &bare_dir,
            &[
                "worktree",
                "add",
                main_worktree.to_str().expect("main worktree path is utf-8"),
                "main",
            ],
        );
        run_setup_git(
            &bare_dir,
            &[
                "worktree",
                "add",
                "-b",
                "session",
                session_worktree
                    .to_str()
                    .expect("session worktree path is utf-8"),
                "main",
            ],
        );

        // Act
        let admin_root =
            main_repo_root_sync(&session_worktree).expect("failed to resolve admin root");
        let working_checkout = main_checkout_working_tree_sync(&session_worktree)
            .expect("failed to resolve working checkout");

        // Assert
        assert_eq!(
            admin_root,
            fs::canonicalize(&bare_dir).expect("failed to canonicalize bare dir")
        );
        assert_eq!(working_checkout, None);
    }

    #[test]
    fn test_non_bare_layout_resolves_main_working_checkout_for_linked_worktree() {
        // Arrange
        let temp_dir = tempdir().expect("failed to create temp dir");
        let root = temp_dir.path();
        let main_checkout = root.join("main");
        fs::create_dir_all(&main_checkout).expect("failed to create main checkout dir");
        run_setup_git(&main_checkout, &["init", "-b", "main"]);
        run_setup_git(&main_checkout, &["config", "user.name", "Test User"]);
        run_setup_git(
            &main_checkout,
            &["config", "user.email", "test@example.com"],
        );
        fs::write(main_checkout.join("README.md"), "test repo").expect("failed to write file");
        run_setup_git(&main_checkout, &["add", "README.md"]);
        run_setup_git(&main_checkout, &["commit", "-m", "Initial commit"]);
        let session_worktree = root.join("session");
        run_setup_git(
            &main_checkout,
            &[
                "worktree",
                "add",
                "-b",
                "session",
                session_worktree
                    .to_str()
                    .expect("session worktree path is utf-8"),
                "main",
            ],
        );

        // Act
        let working_checkout = main_checkout_working_tree_sync(&session_worktree)
            .expect("failed to resolve working checkout");

        // Assert
        assert_eq!(
            working_checkout,
            Some(fs::canonicalize(&main_checkout).expect("failed to canonicalize main checkout"))
        );
    }

    #[test]
    fn test_format_git_invocation_returns_bare_git_for_empty_args() {
        // Act / Assert
        assert_eq!(format_git_invocation(&[]), "git");
    }

    #[test]
    fn test_format_git_invocation_joins_args_after_git() {
        // Act / Assert
        assert_eq!(
            format_git_invocation(&["diff", "--cached", "--quiet"]),
            "git diff --cached --quiet"
        );
    }
}