typeduck-codex-execpolicy 0.6.0

Support package for the standalone Codex Web runtime (codex-core)
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
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
use codex_exec_server::CopyOptions;
use codex_exec_server::CreateDirectoryOptions;
use codex_exec_server::ExecutorFileSystem;
use codex_exec_server::ExecutorFileSystemFuture;
use codex_exec_server::FileMetadata;
use codex_exec_server::FileSystemReadStream;
use codex_exec_server::FileSystemResult;
use codex_exec_server::FileSystemSandboxContext;
use codex_exec_server::LOCAL_FS;
use codex_exec_server::ReadDirectoryEntry;
use codex_exec_server::RemoveOptions;
use codex_git_utils::GitInfo;
use codex_git_utils::GitSha;
use codex_git_utils::collect_git_info;
use codex_git_utils::get_git_repo_root_with_fs;
use codex_git_utils::get_has_changes;
use codex_git_utils::git_diff_to_remote;
use codex_git_utils::recent_commits;
use codex_git_utils::resolve_root_git_project_for_trust;
use codex_utils_path::normalize_for_path_comparison;
use codex_utils_path_uri::PathUri;
use core_test_support::PathBufExt;
use core_test_support::PathExt;
use core_test_support::skip_if_sandbox;
use pretty_assertions::assert_eq;
use std::fs;
use std::io;
#[cfg(unix)]
use std::os::unix::fs::PermissionsExt;
use std::path::PathBuf;
use tempfile::TempDir;
use tokio::process::Command;

struct FailingMetadataFileSystem {
    path: PathUri,
}

impl FailingMetadataFileSystem {
    fn unsupported<T>() -> FileSystemResult<T> {
        Err(io::Error::new(
            io::ErrorKind::Unsupported,
            "operation is not used by Git root discovery",
        ))
    }
}

impl ExecutorFileSystem for FailingMetadataFileSystem {
    fn canonicalize<'a>(
        &'a self,
        _path: &'a PathUri,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, PathUri> {
        Box::pin(async { Self::unsupported() })
    }

    fn read_file<'a>(
        &'a self,
        _path: &'a PathUri,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, Vec<u8>> {
        Box::pin(async { Self::unsupported() })
    }

    fn read_file_stream<'a>(
        &'a self,
        _path: &'a PathUri,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, FileSystemReadStream> {
        Box::pin(async { Self::unsupported() })
    }

    fn write_file<'a>(
        &'a self,
        _path: &'a PathUri,
        _contents: Vec<u8>,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }

    fn create_directory<'a>(
        &'a self,
        _path: &'a PathUri,
        _options: CreateDirectoryOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }

    fn get_metadata<'a>(
        &'a self,
        path: &'a PathUri,
        sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, FileMetadata> {
        Box::pin(async move {
            if path == &self.path {
                Err(io::Error::new(
                    io::ErrorKind::PermissionDenied,
                    "injected metadata failure",
                ))
            } else {
                LOCAL_FS.get_metadata(path, sandbox).await
            }
        })
    }

    fn read_directory<'a>(
        &'a self,
        _path: &'a PathUri,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, Vec<ReadDirectoryEntry>> {
        Box::pin(async { Self::unsupported() })
    }

    fn remove<'a>(
        &'a self,
        _path: &'a PathUri,
        _options: RemoveOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }

    fn copy<'a>(
        &'a self,
        _source_path: &'a PathUri,
        _destination_path: &'a PathUri,
        _options: CopyOptions,
        _sandbox: Option<&'a FileSystemSandboxContext>,
    ) -> ExecutorFileSystemFuture<'a, ()> {
        Box::pin(async { Self::unsupported() })
    }
}

// Helper function to create a test git repository
async fn create_test_git_repo(temp_dir: &TempDir) -> PathBuf {
    let repo_path = temp_dir.path().join("repo");
    fs::create_dir(&repo_path).expect("Failed to create repo dir");
    let envs = vec![
        ("GIT_CONFIG_GLOBAL", "/dev/null"),
        ("GIT_CONFIG_NOSYSTEM", "1"),
    ];

    // Initialize git repo
    Command::new("git")
        .envs(envs.clone())
        .args(["init"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to init git repo");

    // Configure git user (required for commits)
    Command::new("git")
        .envs(envs.clone())
        .args(["config", "user.name", "Test User"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to set git user name");

    Command::new("git")
        .envs(envs.clone())
        .args(["config", "user.email", "test@example.com"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to set git user email");

    // Create a test file and commit it
    let test_file = repo_path.join("test.txt");
    fs::write(&test_file, "test content").expect("Failed to write test file");

    Command::new("git")
        .envs(envs.clone())
        .args(["add", "."])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to add files");

    Command::new("git")
        .envs(envs.clone())
        .args(["commit", "-m", "Initial commit"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to commit");

    repo_path
}

#[tokio::test]
async fn test_recent_commits_non_git_directory_returns_empty() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let entries = recent_commits(temp_dir.path(), /*limit*/ 10).await;
    assert!(entries.is_empty(), "expected no commits outside a git repo");
}

#[tokio::test]
async fn test_recent_commits_orders_and_limits() {
    skip_if_sandbox!();
    use tokio::time::Duration;
    use tokio::time::sleep;

    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    // Make three distinct commits with small delays to ensure ordering by timestamp.
    fs::write(repo_path.join("file.txt"), "one").unwrap();
    Command::new("git")
        .args(["add", "file.txt"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("git add");
    Command::new("git")
        .args(["commit", "-m", "first change"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("git commit 1");

    sleep(Duration::from_millis(1100)).await;

    fs::write(repo_path.join("file.txt"), "two").unwrap();
    Command::new("git")
        .args(["add", "file.txt"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("git add 2");
    Command::new("git")
        .args(["commit", "-m", "second change"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("git commit 2");

    sleep(Duration::from_millis(1100)).await;

    fs::write(repo_path.join("file.txt"), "three").unwrap();
    Command::new("git")
        .args(["add", "file.txt"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("git add 3");
    Command::new("git")
        .args(["commit", "-m", "third change"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("git commit 3");

    // Request the latest 3 commits; should be our three changes in reverse time order.
    let entries = recent_commits(&repo_path, /*limit*/ 3).await;
    assert_eq!(entries.len(), 3);
    assert_eq!(entries[0].subject, "third change");
    assert_eq!(entries[1].subject, "second change");
    assert_eq!(entries[2].subject, "first change");
    // Basic sanity on SHA formatting
    for e in entries {
        assert!(e.sha.len() >= 7 && e.sha.chars().all(|c| c.is_ascii_hexdigit()));
    }
}

async fn create_test_git_repo_with_remote(temp_dir: &TempDir) -> (PathBuf, String) {
    let repo_path = create_test_git_repo(temp_dir).await;
    let remote_path = temp_dir.path().join("remote.git");

    Command::new("git")
        .args(["init", "--bare", remote_path.to_str().unwrap()])
        .output()
        .await
        .expect("Failed to init bare remote");

    Command::new("git")
        .args(["remote", "add", "origin", remote_path.to_str().unwrap()])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to add remote");

    let output = Command::new("git")
        .args(["rev-parse", "--abbrev-ref", "HEAD"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to get branch");
    let branch = String::from_utf8(output.stdout).unwrap().trim().to_string();

    Command::new("git")
        .args(["push", "-u", "origin", &branch])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to push initial commit");

    (repo_path, branch)
}

#[tokio::test]
async fn test_collect_git_info_non_git_directory() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let result = collect_git_info(temp_dir.path()).await;
    assert!(result.is_none());
}

#[tokio::test]
async fn test_collect_git_info_git_repository() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    let git_info = collect_git_info(&repo_path)
        .await
        .expect("Should collect git info from repo");

    // Should have commit hash
    assert!(git_info.commit_hash.is_some());
    let commit_hash = git_info.commit_hash.unwrap().0;
    assert_eq!(commit_hash.len(), 40); // SHA-1 hash should be 40 characters
    assert!(commit_hash.chars().all(|c| c.is_ascii_hexdigit()));

    // Should have branch (likely "main" or "master")
    assert!(git_info.branch.is_some());
    let branch = git_info.branch.unwrap();
    assert!(branch == "main" || branch == "master");

    // Repository URL might be None for local repos without remote
    // This is acceptable behavior
}

#[tokio::test]
async fn test_collect_git_info_with_remote() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    // Add a remote origin
    Command::new("git")
        .args([
            "remote",
            "add",
            "origin",
            "https://github.com/example/repo.git",
        ])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to add remote");

    let git_info = collect_git_info(&repo_path)
        .await
        .expect("Should collect git info from repo");

    let remote_url_output = Command::new("git")
        .args(["remote", "get-url", "origin"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to read remote url");
    // Some dev environments rewrite remotes (e.g., force SSH), so compare against
    // whatever URL Git reports instead of a fixed placeholder.
    let expected_remote = String::from_utf8(remote_url_output.stdout)
        .unwrap()
        .trim()
        .to_string();

    // Should have repository URL
    assert_eq!(git_info.repository_url, Some(expected_remote));
}

#[tokio::test]
async fn test_collect_git_info_detached_head() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    // Get the current commit hash
    let output = Command::new("git")
        .args(["rev-parse", "HEAD"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to get HEAD");
    let commit_hash = String::from_utf8(output.stdout).unwrap().trim().to_string();

    // Checkout the commit directly (detached HEAD)
    Command::new("git")
        .args(["checkout", &commit_hash])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to checkout commit");

    let git_info = collect_git_info(&repo_path)
        .await
        .expect("Should collect git info from repo");

    // Should have commit hash
    assert!(git_info.commit_hash.is_some());
    // Branch should be None for detached HEAD (since rev-parse --abbrev-ref HEAD returns "HEAD")
    assert!(git_info.branch.is_none());
}

#[tokio::test]
async fn test_collect_git_info_with_branch() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    // Create and checkout a new branch
    Command::new("git")
        .args(["checkout", "-b", "feature-branch"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to create branch");

    let git_info = collect_git_info(&repo_path)
        .await
        .expect("Should collect git info from repo");

    // Should have the new branch name
    assert_eq!(git_info.branch, Some("feature-branch".to_string()));
}

#[tokio::test]
async fn test_get_has_changes_non_git_directory_returns_none() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    assert_eq!(get_has_changes(temp_dir.path()).await, None);
}

#[tokio::test]
async fn test_get_has_changes_clean_repo_returns_false() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;
    assert_eq!(get_has_changes(&repo_path).await, Some(false));
}

#[tokio::test]
async fn test_get_has_changes_with_tracked_change_returns_true() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    fs::write(repo_path.join("test.txt"), "updated tracked file").expect("write tracked file");
    assert_eq!(get_has_changes(&repo_path).await, Some(true));
}

#[tokio::test]
async fn test_get_has_changes_with_untracked_change_returns_true() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    fs::write(repo_path.join("new_file.txt"), "untracked").expect("write untracked file");
    assert_eq!(get_has_changes(&repo_path).await, Some(true));
}

#[cfg(unix)]
#[tokio::test]
async fn test_get_has_changes_ignores_configured_hooks_path() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;
    let hooks_dir = repo_path.join(".git/hooks-path-test");
    let hook_path = hooks_dir.join("post-index-change");
    let marker_path = repo_path.join("hook-ran");

    fs::create_dir_all(&hooks_dir).expect("create hook dir");
    fs::write(
        &hook_path,
        format!(
            "#!/bin/sh\nprintf ran > \"{}\"\n",
            marker_path.to_string_lossy()
        ),
    )
    .expect("write post-index-change hook");
    let mut permissions = fs::metadata(&hook_path)
        .expect("read hook metadata")
        .permissions();
    permissions.set_mode(0o755);
    fs::set_permissions(&hook_path, permissions).expect("mark hook executable");

    Command::new("git")
        .args([
            "config",
            "core.hooksPath",
            hooks_dir.to_string_lossy().as_ref(),
        ])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("configure hooks path");

    fs::write(repo_path.join("test.txt"), "test content").expect("refresh tracked file");

    assert_eq!(get_has_changes(&repo_path).await, Some(false));
    assert!(
        !marker_path.exists(),
        "metadata collection should not invoke configured hook directories"
    );
}

#[tokio::test]
async fn test_get_git_working_tree_state_clean_repo() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let (repo_path, branch) = create_test_git_repo_with_remote(&temp_dir).await;

    let remote_sha = Command::new("git")
        .args(["rev-parse", &format!("origin/{branch}")])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to rev-parse remote");
    let remote_sha = String::from_utf8(remote_sha.stdout)
        .unwrap()
        .trim()
        .to_string();

    let state = git_diff_to_remote(&repo_path)
        .await
        .expect("Should collect working tree state");
    assert_eq!(state.sha, GitSha::new(&remote_sha));
    assert!(state.diff.is_empty());
}

#[tokio::test]
async fn test_get_git_working_tree_state_with_changes() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let (repo_path, branch) = create_test_git_repo_with_remote(&temp_dir).await;

    let tracked = repo_path.join("test.txt");
    fs::write(&tracked, "modified").unwrap();
    fs::write(repo_path.join("untracked.txt"), "new").unwrap();

    let remote_sha = Command::new("git")
        .args(["rev-parse", &format!("origin/{branch}")])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to rev-parse remote");
    let remote_sha = String::from_utf8(remote_sha.stdout)
        .unwrap()
        .trim()
        .to_string();

    let state = git_diff_to_remote(&repo_path)
        .await
        .expect("Should collect working tree state");
    assert_eq!(state.sha, GitSha::new(&remote_sha));
    assert!(state.diff.contains("test.txt"));
    assert!(state.diff.contains("untracked.txt"));
}

#[tokio::test]
async fn test_get_git_working_tree_state_branch_fallback() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let (repo_path, _branch) = create_test_git_repo_with_remote(&temp_dir).await;

    Command::new("git")
        .args(["checkout", "-b", "feature"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to create feature branch");
    Command::new("git")
        .args(["push", "-u", "origin", "feature"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to push feature branch");

    Command::new("git")
        .args(["checkout", "-b", "local-branch"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to create local branch");

    let remote_sha = Command::new("git")
        .args(["rev-parse", "origin/feature"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to rev-parse remote");
    let remote_sha = String::from_utf8(remote_sha.stdout)
        .unwrap()
        .trim()
        .to_string();

    let state = git_diff_to_remote(&repo_path)
        .await
        .expect("Should collect working tree state");
    assert_eq!(state.sha, GitSha::new(&remote_sha));
}

#[tokio::test]
async fn resolve_root_git_project_for_trust_returns_none_outside_repo() {
    let tmp = TempDir::new().expect("tempdir");
    assert!(
        resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &tmp.path().abs())
            .await
            .is_none()
    );
}

#[tokio::test]
async fn get_git_repo_root_with_fs_detects_gitdir_pointer() {
    let tmp = TempDir::new().expect("tempdir");
    let proj = tmp.path().join("proj");
    let nested = proj.join("nested");
    std::fs::create_dir_all(&nested).unwrap();
    std::fs::write(proj.join(".git"), "gitdir: /tmp/fake-worktree\n").unwrap();

    assert_eq!(
        get_git_repo_root_with_fs(LOCAL_FS.as_ref(), &nested.abs()).await,
        Some(proj.abs())
    );
}

#[tokio::test]
async fn get_git_repo_root_with_fs_starts_at_parent_for_file() {
    let tmp = TempDir::new().expect("tempdir");
    let proj = tmp.path().join("proj");
    let nested = proj.join("nested");
    std::fs::create_dir_all(proj.join(".git")).unwrap();
    std::fs::create_dir_all(&nested).unwrap();
    let file = nested.join("file.txt");
    std::fs::write(&file, "contents").unwrap();

    assert_eq!(
        get_git_repo_root_with_fs(LOCAL_FS.as_ref(), &file.abs()).await,
        Some(proj.abs())
    );
}

#[tokio::test]
async fn get_git_repo_root_with_fs_ignores_metadata_errors() {
    let tmp = TempDir::new().expect("tempdir");
    let proj = tmp.path().join("proj");
    let nested = proj.join("nested");
    std::fs::create_dir_all(proj.join(".git")).unwrap();
    std::fs::create_dir_all(&nested).unwrap();
    let fs = FailingMetadataFileSystem {
        path: PathUri::from_abs_path(&nested.join(".git").abs()),
    };

    assert_eq!(
        get_git_repo_root_with_fs(&fs, &nested.abs()).await,
        Some(proj.abs())
    );
}

#[cfg(windows)]
#[tokio::test]
async fn get_git_repo_root_with_fs_supports_windows_namespace_paths() {
    let tmp = TempDir::new().expect("tempdir");
    let repo = tmp.path().join("repo");
    std::fs::create_dir_all(repo.join(".git")).unwrap();
    std::fs::create_dir_all(repo.join("nested")).unwrap();

    let namespace_repo = PathBuf::from(format!(r"\\?\{}", repo.display()));
    let namespace_nested = namespace_repo.join("nested");

    assert_eq!(
        get_git_repo_root_with_fs(LOCAL_FS.as_ref(), &namespace_nested.abs()).await,
        Some(namespace_repo.abs())
    );
}

#[tokio::test]
async fn resolve_root_git_project_for_trust_regular_repo_returns_repo_root() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await.abs();

    assert_eq!(
        resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &repo_path).await,
        Some(repo_path.clone())
    );
    let nested = repo_path.join("sub/dir");
    std::fs::create_dir_all(nested.as_path()).unwrap();
    assert_eq!(
        resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &nested).await,
        Some(repo_path)
    );
}

#[tokio::test]
async fn resolve_root_git_project_for_trust_detects_worktree_and_returns_main_root() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let repo_path = create_test_git_repo(&temp_dir).await;

    // Create a linked worktree
    let wt_root = temp_dir.path().join("wt");
    let _ = std::process::Command::new("git")
        .args([
            "worktree",
            "add",
            wt_root.to_str().unwrap(),
            "-b",
            "feature/x",
        ])
        .current_dir(&repo_path)
        .output()
        .expect("git worktree add");

    let expected = normalize_for_path_comparison(&repo_path).unwrap();
    let wt_root = wt_root.abs();
    let got = resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &wt_root).await;
    assert_eq!(
        got.as_ref()
            .map(normalize_for_path_comparison)
            .transpose()
            .unwrap(),
        Some(expected.clone())
    );
    let nested = wt_root.join("nested/sub");
    std::fs::create_dir_all(nested.as_path()).unwrap();
    let got_nested = resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &nested).await;
    assert_eq!(
        got_nested
            .as_ref()
            .map(normalize_for_path_comparison)
            .transpose()
            .unwrap(),
        Some(expected)
    );
}

#[tokio::test]
async fn resolve_root_git_project_for_trust_detects_worktree_pointer_without_git_command() {
    let tmp = TempDir::new().expect("tempdir");
    let repo_root = tmp.path().join("repo");
    let common_dir = repo_root.join(".git");
    let worktree_git_dir = common_dir.join("worktrees").join("feature-x");
    let worktree_root = tmp.path().join("wt");
    std::fs::create_dir_all(&worktree_git_dir).unwrap();
    std::fs::create_dir_all(&worktree_root).unwrap();
    std::fs::create_dir_all(worktree_root.join("nested")).unwrap();
    std::fs::write(
        worktree_root.join(".git"),
        format!("gitdir: {}\n", worktree_git_dir.display()),
    )
    .unwrap();

    let expected = repo_root.abs();
    let worktree_root = worktree_root.abs();
    assert_eq!(
        resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &worktree_root).await,
        Some(expected.clone())
    );
    let nested = worktree_root.join("nested");
    assert_eq!(
        resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &nested).await,
        Some(expected)
    );
}

#[tokio::test]
async fn resolve_root_git_project_for_trust_non_worktrees_gitdir_returns_none() {
    let tmp = TempDir::new().expect("tempdir");
    let proj = tmp.path().join("proj");
    std::fs::create_dir_all(proj.join("nested")).unwrap();

    // `.git` is a file but does not point to a worktrees path
    std::fs::write(
        proj.join(".git"),
        format!(
            "gitdir: {}\n",
            tmp.path().join("some/other/location").display()
        ),
    )
    .unwrap();

    let proj = proj.abs();
    assert!(
        resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &proj)
            .await
            .is_none()
    );
    let nested = proj.join("nested");
    assert!(
        resolve_root_git_project_for_trust(LOCAL_FS.as_ref(), &nested)
            .await
            .is_none()
    );
}

#[tokio::test]
async fn test_get_git_working_tree_state_unpushed_commit() {
    let temp_dir = TempDir::new().expect("Failed to create temp dir");
    let (repo_path, branch) = create_test_git_repo_with_remote(&temp_dir).await;

    let remote_sha = Command::new("git")
        .args(["rev-parse", &format!("origin/{branch}")])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to rev-parse remote");
    let remote_sha = String::from_utf8(remote_sha.stdout)
        .unwrap()
        .trim()
        .to_string();

    fs::write(repo_path.join("test.txt"), "updated").unwrap();
    Command::new("git")
        .args(["add", "test.txt"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to add file");
    Command::new("git")
        .args(["commit", "-m", "local change"])
        .current_dir(&repo_path)
        .output()
        .await
        .expect("Failed to commit");

    let state = git_diff_to_remote(&repo_path)
        .await
        .expect("Should collect working tree state");
    assert_eq!(state.sha, GitSha::new(&remote_sha));
    assert!(state.diff.contains("updated"));
}

#[test]
fn test_git_info_serialization() {
    let git_info = GitInfo {
        commit_hash: Some(GitSha::new("abc123def456")),
        branch: Some("main".to_string()),
        repository_url: Some("https://github.com/example/repo.git".to_string()),
    };

    let json = serde_json::to_string(&git_info).expect("Should serialize GitInfo");
    let parsed: serde_json::Value = serde_json::from_str(&json).expect("Should parse JSON");

    assert_eq!(parsed["commit_hash"], "abc123def456");
    assert_eq!(parsed["branch"], "main");
    assert_eq!(
        parsed["repository_url"],
        "https://github.com/example/repo.git"
    );
}

#[test]
fn test_git_info_serialization_with_nones() {
    let git_info = GitInfo {
        commit_hash: None,
        branch: None,
        repository_url: None,
    };

    let json = serde_json::to_string(&git_info).expect("Should serialize GitInfo");
    let parsed: serde_json::Value = serde_json::from_str(&json).expect("Should parse JSON");

    // Fields with None values should be omitted due to skip_serializing_if
    assert!(!parsed.as_object().unwrap().contains_key("commit_hash"));
    assert!(!parsed.as_object().unwrap().contains_key("branch"));
    assert!(!parsed.as_object().unwrap().contains_key("repository_url"));
}