worktrunk 0.40.0

A CLI for Git worktree management, designed for parallel AI agent workflows
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
858
859
860
861
862
863
864
865
//! Tests for CI status detection and parsing
//!
//! These tests verify that the CI status parsing code correctly handles
//! JSON responses from GitHub (gh) and GitLab (glab) CLI tools.
//!
//! ## Windows support
//!
//! On Windows, mock-stub.exe sets MOCK_SCRIPT_DIR so the mock gh script can
//! reliably locate its JSON data files. Use MOCK_DEBUG=1 to troubleshoot
//! path issues.

use crate::common::{
    TestRepo, make_snapshot_cmd,
    mock_commands::{MockConfig, MockResponse},
    repo, setup_snapshot_settings,
};
use ansi_str::AnsiStr;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
use std::path::Path;
use std::process::Command;

/// Get the HEAD commit SHA for a branch
fn branch_sha(repo: &TestRepo, branch: &str) -> String {
    repo.git_output(&["rev-parse", branch])
}

/// Set up tracking for all branches so @{push} resolves correctly.
///
/// @{push} requires both tracking config AND the remote-tracking ref to exist.
/// This is normally done by fetch/push, but in tests we create refs manually.
fn setup_tracking_for_all_branches(repo: &TestRepo, remote: &str) {
    for branch in ["feature", "feature-a", "feature-b", "feature-c", "main"] {
        repo.run_git(&["config", &format!("branch.{}.remote", branch), remote]);
        repo.run_git(&[
            "config",
            &format!("branch.{}.merge", branch),
            &format!("refs/heads/{}", branch),
        ]);
        // Create the remote-tracking ref
        repo.run_git(&[
            "update-ref",
            &format!("refs/remotes/{}/{}", remote, branch),
            branch,
        ]);
    }
}

/// Helper to run a CI status test with the given mock data
fn run_ci_status_test(repo: &mut TestRepo, snapshot_name: &str, pr_json: &str, run_json: &str) {
    repo.setup_mock_gh_with_ci_data(pr_json, run_json);

    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "list", &["--full"], None);
        repo.configure_mock_commands(&mut cmd);
        assert_cmd_snapshot!(snapshot_name, cmd);
    });
}

/// Setup mock `gh` with configurable `pr list` and `api repos/.../check-runs`
/// responses.
fn setup_mock_gh_with_api_data(
    repo: &TestRepo,
    pr_json: &str,
    api_responses: &[(&str, &str)],
) -> std::path::PathBuf {
    let mock_bin = repo.root_path().join("mock-bin");
    std::fs::create_dir_all(&mock_bin).unwrap();

    let mut gh = MockConfig::new("gh")
        .version("gh version 2.0.0 (mock)")
        .command("pr list", MockResponse::output(pr_json));

    for (command, response) in api_responses {
        gh = gh.command(command, MockResponse::output(response));
    }

    gh.command("_default", MockResponse::exit(1))
        .write(&mock_bin);
    MockConfig::new("glab")
        .version("glab version 1.0.0 (mock)")
        .command("_default", MockResponse::exit(1))
        .write(&mock_bin);

    mock_bin
}

/// Configure command environment for local gh/glab mocks.
fn configure_mock_ci_env(cmd: &mut Command, mock_bin: &Path) {
    cmd.env("MOCK_CONFIG_DIR", mock_bin);

    let (path_var_name, current_path) = std::env::vars_os()
        .find(|(k, _)| k.eq_ignore_ascii_case("PATH"))
        .map(|(k, v)| (k.to_string_lossy().into_owned(), Some(v)))
        .unwrap_or(("PATH".to_string(), None));

    let mut paths: Vec<std::path::PathBuf> = current_path
        .as_deref()
        .map(|p| std::env::split_paths(p).collect())
        .unwrap_or_default();
    paths.insert(0, mock_bin.to_path_buf());
    let new_path = std::env::join_paths(&paths).unwrap();
    cmd.env(path_var_name, new_path);
}

/// Setup a repo with GitHub remote and feature worktree, returns head SHA
fn setup_github_repo_with_feature(repo: &mut TestRepo) -> String {
    // Set origin URL (origin already exists from fixture, just update URL)
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/test-owner/test-repo.git",
    ]);
    repo.add_worktree("feature");
    setup_tracking_for_all_branches(repo, "origin");
    branch_sha(repo, "feature")
}

// =============================================================================
// PR status tests (CheckRun format)
// =============================================================================

#[rstest]
#[case::passed("CLEAN", "COMPLETED", "SUCCESS", "github_pr_passed")]
#[case::failed("BLOCKED", "COMPLETED", "FAILURE", "github_pr_failed")]
#[case::running("UNKNOWN", "IN_PROGRESS", "null", "github_pr_running")]
#[case::conflicts("DIRTY", "COMPLETED", "SUCCESS", "github_pr_conflicts")]
fn test_list_full_with_github_pr_status(
    mut repo: TestRepo,
    #[case] merge_state: &str,
    #[case] status: &str,
    #[case] conclusion: &str,
    #[case] snapshot_name: &str,
) {
    let head_sha = setup_github_repo_with_feature(&mut repo);

    // Format conclusion - use raw value for null, quoted for strings
    let conclusion_json = if conclusion == "null" {
        "null".to_string()
    } else {
        format!("\"{}\"", conclusion)
    };

    let pr_json = format!(
        r#"[{{
        "headRefOid": "{}",
        "mergeStateStatus": "{}",
        "statusCheckRollup": [
            {{"status": "{}", "conclusion": {}}}
        ],
        "url": "https://github.com/test-owner/test-repo/pull/1",
        "headRepositoryOwner": {{"login": "test-owner"}}
    }}]"#,
        head_sha, merge_state, status, conclusion_json
    );

    run_ci_status_test(&mut repo, snapshot_name, &pr_json, "[]");
}

// =============================================================================
// StatusContext tests (external CI systems like Jenkins)
// =============================================================================

#[rstest]
#[case::pending("UNKNOWN", "PENDING", "status_context_pending")]
#[case::failure("BLOCKED", "FAILURE", "status_context_failure")]
fn test_list_full_with_status_context(
    mut repo: TestRepo,
    #[case] merge_state: &str,
    #[case] state: &str,
    #[case] snapshot_name: &str,
) {
    let head_sha = setup_github_repo_with_feature(&mut repo);

    let pr_json = format!(
        r#"[{{
        "headRefOid": "{}",
        "mergeStateStatus": "{}",
        "statusCheckRollup": [
            {{"state": "{}"}}
        ],
        "url": "https://github.com/test-owner/test-repo/pull/1",
        "headRepositoryOwner": {{"login": "test-owner"}}
    }}]"#,
        head_sha, merge_state, state
    );

    run_ci_status_test(&mut repo, snapshot_name, &pr_json, "[]");
}

// =============================================================================
// Workflow run tests (no PR, just workflow runs)
// =============================================================================

#[rstest]
#[case::completed("completed", "success", "github_workflow_run")]
#[case::running("in_progress", "null", "github_workflow_running")]
fn test_list_full_with_github_workflow(
    mut repo: TestRepo,
    #[case] status: &str,
    #[case] conclusion: &str,
    #[case] snapshot_name: &str,
) {
    let head_sha = setup_github_repo_with_feature(&mut repo);

    let conclusion_json = if conclusion == "null" {
        "null".to_string()
    } else {
        format!("\"{}\"", conclusion)
    };

    let run_json = format!(
        r#"[{{
        "status": "{}",
        "conclusion": {},
        "headSha": "{}"
    }}]"#,
        status, conclusion_json, head_sha
    );

    run_ci_status_test(&mut repo, snapshot_name, "[]", &run_json);
}

// =============================================================================
// Special case tests (unique scenarios that don't fit parameterization)
// =============================================================================

#[rstest]
fn test_list_full_with_stale_pr(mut repo: TestRepo) {
    setup_github_repo_with_feature(&mut repo);

    // Make additional commit locally (not pushed)
    let worktree_path = repo.worktrees.get("feature").unwrap().clone();
    std::fs::write(worktree_path.join("new_file.txt"), "new content").unwrap();
    repo.stage_all(&worktree_path);
    repo.run_git_in(&worktree_path, &["commit", "-m", "Local commit"]);

    // PR HEAD differs from local HEAD - simulates stale PR
    let pr_json = r#"[{
        "headRefOid": "old_sha_from_before_local_commit",
        "mergeStateStatus": "CLEAN",
        "statusCheckRollup": [
            {"status": "COMPLETED", "conclusion": "SUCCESS"}
        ],
        "url": "https://github.com/test-owner/test-repo/pull/1",
        "headRepositoryOwner": {"login": "test-owner"}
    }]"#;

    run_ci_status_test(&mut repo, "stale_pr", pr_json, "[]");
}

#[rstest]
fn test_list_full_with_mixed_check_types(mut repo: TestRepo) {
    let head_sha = setup_github_repo_with_feature(&mut repo);

    // Mixed: CheckRun (passed) + StatusContext (pending)
    let pr_json = format!(
        r#"[{{
        "headRefOid": "{}",
        "mergeStateStatus": "UNKNOWN",
        "statusCheckRollup": [
            {{"status": "COMPLETED", "conclusion": "SUCCESS"}},
            {{"state": "PENDING"}}
        ],
        "url": "https://github.com/test-owner/test-repo/pull/1",
        "headRepositoryOwner": {{"login": "test-owner"}}
    }}]"#,
        head_sha
    );

    run_ci_status_test(&mut repo, "mixed_check_types", &pr_json, "[]");
}

#[rstest]
fn test_list_full_with_no_ci_checks(mut repo: TestRepo) {
    let head_sha = setup_github_repo_with_feature(&mut repo);

    let pr_json = format!(
        r#"[{{
        "headRefOid": "{}",
        "mergeStateStatus": "CLEAN",
        "statusCheckRollup": [],
        "url": "https://github.com/test-owner/test-repo/pull/1",
        "headRepositoryOwner": {{"login": "test-owner"}}
    }}]"#,
        head_sha
    );

    run_ci_status_test(&mut repo, "no_ci_checks", &pr_json, "[]");
}

#[rstest]
fn test_list_full_filters_by_repo_owner(mut repo: TestRepo) {
    // Use different org name
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/my-org/test-repo.git",
    ]);
    repo.add_worktree("feature");
    setup_tracking_for_all_branches(&repo, "origin");
    let head_sha = branch_sha(&repo, "feature");

    // Multiple PRs - only one from our org (should filter to my-org's PR)
    let pr_json = format!(
        r#"[
        {{
            "headRefOid": "wrong_sha",
            "mergeStateStatus": "CLEAN",
            "statusCheckRollup": [{{"status": "COMPLETED", "conclusion": "FAILURE"}}],
            "url": "https://github.com/other-org/test-repo/pull/99",
            "headRepositoryOwner": {{"login": "other-org"}}
        }},
        {{
            "headRefOid": "{}",
            "mergeStateStatus": "CLEAN",
            "statusCheckRollup": [{{"status": "COMPLETED", "conclusion": "SUCCESS"}}],
            "url": "https://github.com/my-org/test-repo/pull/1",
            "headRepositoryOwner": {{"login": "my-org"}}
        }}
    ]"#,
        head_sha
    );

    run_ci_status_test(&mut repo, "filters_by_repo_owner", &pr_json, "[]");
}

#[rstest]
fn test_list_full_with_platform_override_github(mut repo: TestRepo) {
    // Set a non-GitHub remote (bitbucket) as origin - platform won't be auto-detected
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://bitbucket.org/test-owner/test-repo.git",
    ]);

    // Add a GitHub remote for PR detection (platform override needs a GitHub remote
    // to determine which repo's PRs to check)
    repo.run_git(&[
        "remote",
        "add",
        "github",
        "https://github.com/test-owner/test-repo.git",
    ]);

    // Set platform override in project config
    repo.write_project_config(
        r#"
[ci]
platform = "github"
"#,
    );

    // Create a feature branch with tracking to the github remote
    repo.add_worktree("feature");
    setup_tracking_for_all_branches(&repo, "github");

    // Get actual commit SHA
    let head_sha = branch_sha(&repo, "feature");

    // Setup mock gh with PR data - this should work because platform is overridden to github
    let pr_json = format!(
        r#"[{{
        "headRefOid": "{}",
        "mergeStateStatus": "CLEAN",
        "statusCheckRollup": [
            {{"status": "COMPLETED", "conclusion": "SUCCESS"}}
        ],
        "url": "https://github.com/test-owner/test-repo/pull/1",
        "headRepositoryOwner": {{"login": "test-owner"}}
    }}]"#,
        head_sha
    );
    let run_json = "[]";
    repo.setup_mock_gh_with_ci_data(&pr_json, run_json);

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);
        repo.configure_mock_commands(&mut cmd);
        // Platform override should force GitHub detection even with bitbucket remote
        assert_cmd_snapshot!(cmd);
    });
}

#[rstest]
fn test_list_full_with_gitlab_remote(mut repo: TestRepo) {
    // Set GitLab remote URL - tests get_gitlab_host_for_repo path
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.example.com/test-owner/test-repo.git",
    ]);

    // Create a feature branch
    repo.add_worktree("feature");

    // No mock glab setup - this tests the hint path when glab isn't available
    // The get_gitlab_host_for_repo function is called to detect GitLab platform

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);
        // Don't configure mocks - we want to test the "no CI tool" hint path
        // which exercises get_gitlab_host_for_repo
        assert_cmd_snapshot!(cmd);
    });
}

#[rstest]
fn test_list_full_with_invalid_platform_override(mut repo: TestRepo) {
    // Set GitHub remote URL
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/test-owner/test-repo.git",
    ]);

    // Set INVALID platform override - should warn and fall back to URL detection
    repo.write_project_config(
        r#"
[ci]
platform = "invalid_platform"
"#,
    );

    // Create a feature branch with tracking
    repo.add_worktree("feature");
    setup_tracking_for_all_branches(&repo, "origin");
    let head_sha = branch_sha(&repo, "feature");

    // Setup mock gh - platform should fall back to GitHub via URL detection
    let pr_json = format!(
        r#"[{{
        "headRefOid": "{}",
        "mergeStateStatus": "CLEAN",
        "statusCheckRollup": [
            {{"status": "COMPLETED", "conclusion": "SUCCESS"}}
        ],
        "url": "https://github.com/test-owner/test-repo/pull/1",
        "headRepositoryOwner": {{"login": "test-owner"}}
    }}]"#,
        head_sha
    );
    repo.setup_mock_gh_with_ci_data(&pr_json, "[]");

    let mut settings = setup_snapshot_settings(&repo);
    // Normalize worker thread ID prefix in log output (e.g., [n], [z], [A] -> [W])
    settings.add_filter(r"\[[a-zA-Z]\]", "[W]");
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);
        repo.configure_mock_commands(&mut cmd);
        // Invalid platform should fall back to URL detection (GitHub)
        assert_cmd_snapshot!(cmd);
    });
}

// =============================================================================
// GitLab MR status tests
// =============================================================================

/// Helper to run a GitLab CI status test with the given mock data
fn run_gitlab_ci_status_test(
    repo: &mut TestRepo,
    snapshot_name: &str,
    mr_json: &str,
    project_id: Option<u64>,
) {
    repo.setup_mock_glab_with_ci_data(mr_json, project_id);

    let settings = setup_snapshot_settings(repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(repo, "list", &["--full"], None);
        repo.configure_mock_commands(&mut cmd);
        assert_cmd_snapshot!(snapshot_name, cmd);
    });
}

/// Setup a repo with GitLab remote and feature worktree, returns head SHA
fn setup_gitlab_repo_with_feature(repo: &mut TestRepo) -> String {
    // Set origin URL (origin already exists from fixture, just update URL)
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/test-group/test-project.git",
    ]);
    repo.add_worktree("feature");
    setup_tracking_for_all_branches(repo, "origin");
    branch_sha(repo, "feature")
}

#[rstest]
#[case::passed("success", false, "gitlab_mr_passed")]
#[case::failed("failed", false, "gitlab_mr_failed")]
#[case::running("running", false, "gitlab_mr_running")]
#[case::pending("pending", false, "gitlab_mr_pending")]
#[case::conflicts("success", true, "gitlab_mr_conflicts")]
fn test_list_full_with_gitlab_mr_status(
    mut repo: TestRepo,
    #[case] pipeline_status: &str,
    #[case] has_conflicts: bool,
    #[case] snapshot_name: &str,
) {
    let head_sha = setup_gitlab_repo_with_feature(&mut repo);

    let mr_json = format!(
        r#"[{{
        "iid": 1,
        "sha": "{}",
        "has_conflicts": {},
        "detailed_merge_status": null,
        "head_pipeline": {{"status": "{}"}},
        "source_project_id": 12345,
        "web_url": "https://gitlab.com/test-group/test-project/-/merge_requests/1"
    }}]"#,
        head_sha, has_conflicts, pipeline_status
    );

    run_gitlab_ci_status_test(&mut repo, snapshot_name, &mr_json, Some(12345));
}

#[rstest]
fn test_list_full_with_gitlab_stale_mr(mut repo: TestRepo) {
    setup_gitlab_repo_with_feature(&mut repo);

    // Make additional commit locally (not pushed)
    let worktree_path = repo.worktrees.get("feature").unwrap().clone();
    std::fs::write(worktree_path.join("new_file.txt"), "new content").unwrap();
    repo.stage_all(&worktree_path);
    repo.run_git_in(&worktree_path, &["commit", "-m", "Local commit"]);

    // MR HEAD differs from local HEAD - simulates stale MR
    let mr_json = r#"[{
        "iid": 1,
        "sha": "old_sha_from_before_local_commit",
        "has_conflicts": false,
        "detailed_merge_status": null,
        "head_pipeline": {"status": "success"},
        "source_project_id": 12345,
        "web_url": "https://gitlab.com/test-group/test-project/-/merge_requests/1"
    }]"#;

    run_gitlab_ci_status_test(&mut repo, "gitlab_stale_mr", mr_json, Some(12345));
}

#[rstest]
fn test_list_full_with_gitlab_no_ci(mut repo: TestRepo) {
    let head_sha = setup_gitlab_repo_with_feature(&mut repo);

    // MR with no pipeline
    let mr_json = format!(
        r#"[{{
        "iid": 1,
        "sha": "{}",
        "has_conflicts": false,
        "detailed_merge_status": null,
        "head_pipeline": null,
        "source_project_id": 12345,
        "web_url": "https://gitlab.com/test-group/test-project/-/merge_requests/1"
    }}]"#,
        head_sha
    );

    run_gitlab_ci_status_test(&mut repo, "gitlab_no_ci", &mr_json, Some(12345));
}

#[rstest]
fn test_list_full_with_gitlab_filters_by_project_id(mut repo: TestRepo) {
    // Use a specific project for our repo
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitlab.com/my-group/my-project.git",
    ]);
    repo.add_worktree("feature");
    setup_tracking_for_all_branches(&repo, "origin");
    let head_sha = branch_sha(&repo, "feature");

    // Multiple MRs - only one from our project (should filter to project 99999)
    // The "other" MR is listed first to prove filtering works (not just taking first element)
    let mr_json = format!(
        r#"[
        {{
            "iid": 99,
            "sha": "wrong_sha",
            "has_conflicts": false,
            "detailed_merge_status": null,
            "head_pipeline": {{"status": "failed"}},
            "source_project_id": 11111,
            "web_url": "https://gitlab.com/other-group/other-project/-/merge_requests/99"
        }},
        {{
            "iid": 1,
            "sha": "{}",
            "has_conflicts": false,
            "detailed_merge_status": null,
            "head_pipeline": {{"status": "success"}},
            "source_project_id": 99999,
            "web_url": "https://gitlab.com/my-group/my-project/-/merge_requests/1"
        }}
    ]"#,
        head_sha
    );

    run_gitlab_ci_status_test(
        &mut repo,
        "gitlab_filters_by_project_id",
        &mr_json,
        Some(99999),
    );
}

// =============================================================================
// GitLab project ID edge cases (PR #846 panic prevention)
// =============================================================================

/// Test that single MR without project ID works (unambiguous case).
///
/// When `glab repo view` fails to return a project ID but there's only one MR,
/// we can safely use it since there's no ambiguity.
#[rstest]
fn test_list_full_with_gitlab_single_mr_no_project_id(mut repo: TestRepo) {
    let head_sha = setup_gitlab_repo_with_feature(&mut repo);

    // Single MR - should work even without project ID to filter by
    let mr_json = format!(
        r#"[{{
        "iid": 1,
        "sha": "{}",
        "has_conflicts": false,
        "detailed_merge_status": null,
        "head_pipeline": {{"status": "success"}},
        "source_project_id": 12345,
        "web_url": "https://gitlab.com/test-group/test-project/-/merge_requests/1"
    }}]"#,
        head_sha
    );

    // Pass None for project_id to trigger "no project ID" path
    run_gitlab_ci_status_test(&mut repo, "gitlab_single_mr_no_project_id", &mr_json, None);
}

/// Test that empty MR list without project ID returns None gracefully.
///
/// When no MRs are found and we don't have a project ID, the code should
/// return None without panicking. This falls through to pipeline detection.
#[rstest]
fn test_list_full_with_gitlab_empty_mr_list_no_project_id(mut repo: TestRepo) {
    setup_gitlab_repo_with_feature(&mut repo);

    // Empty MR list + no project ID -> falls through to pipeline check
    run_gitlab_ci_status_test(
        &mut repo,
        "gitlab_empty_mr_list_no_project_id",
        "[]", // Empty MR list
        None, // No project ID
    );
}

/// Test that multiple MRs without project ID are skipped (ambiguous case).
///
/// When there are multiple MRs with the same branch name and we can't determine
/// which project we're in, we skip CI detection rather than showing the wrong one.
/// This falls through to pipeline detection via `glab ci list`.
#[rstest]
fn test_list_full_with_gitlab_multiple_mrs_no_project_id(mut repo: TestRepo) {
    let head_sha = setup_gitlab_repo_with_feature(&mut repo);

    // Multiple MRs from different projects - ambiguous without project ID
    let mr_json = format!(
        r#"[
        {{
            "iid": 1,
            "sha": "{}",
            "has_conflicts": false,
            "detailed_merge_status": null,
            "head_pipeline": {{"status": "failed"}},
            "source_project_id": 11111,
            "web_url": "https://gitlab.com/org-a/project/-/merge_requests/1"
        }},
        {{
            "iid": 2,
            "sha": "{}",
            "has_conflicts": false,
            "detailed_merge_status": null,
            "head_pipeline": {{"status": "success"}},
            "source_project_id": 22222,
            "web_url": "https://gitlab.com/org-b/project/-/merge_requests/2"
        }}
    ]"#,
        head_sha, head_sha
    );

    // Pass None for project_id - should skip MR detection due to ambiguity
    // and fall through to pipeline detection (which will show NoCI since
    // our mock returns empty pipeline list)
    run_gitlab_ci_status_test(
        &mut repo,
        "gitlab_multiple_mrs_no_project_id",
        &mr_json,
        None,
    );
}

// =============================================================================
// URL-based pushremote tests (gh pr checkout scenario)
// =============================================================================

/// Test that CI status works when pushremote is a URL instead of a remote name.
///
/// This simulates the `gh pr checkout` scenario where git sets:
/// - branch.<name>.pushremote = https://github.com/fork-owner/repo.git (a URL)
/// - branch.<name>.merge = refs/pull/123/head (a PR ref)
///
/// Git's @{push} syntax fails with URLs, so we fall back to reading the config directly.
#[rstest]
fn test_list_full_with_url_based_pushremote(mut repo: TestRepo) {
    // Set origin URL (the upstream repo where PRs are opened)
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://github.com/upstream-owner/test-repo.git",
    ]);
    repo.add_worktree("feature");
    let head_sha = branch_sha(&repo, "feature");

    // Simulate `gh pr checkout` behavior:
    // - Sets pushremote to the fork URL (not a remote name)
    // - Sets merge to a PR ref (not a normal branch ref)
    repo.run_git(&[
        "config",
        "branch.feature.pushremote",
        "https://github.com/fork-owner/test-repo.git", // URL, not remote name
    ]);
    repo.run_git(&[
        "config",
        "branch.feature.merge",
        "refs/pull/123/head", // PR ref, not branch ref
    ]);

    // The PR comes from the fork owner (matches pushremote URL)
    let pr_json = format!(
        r#"[{{
        "headRefOid": "{}",
        "mergeStateStatus": "CLEAN",
        "statusCheckRollup": [
            {{"status": "COMPLETED", "conclusion": "SUCCESS"}}
        ],
        "url": "https://github.com/upstream-owner/test-repo/pull/123",
        "headRepositoryOwner": {{"login": "fork-owner"}}
    }}]"#,
        head_sha
    );

    run_ci_status_test(&mut repo, "url_based_pushremote", &pr_json, "[]");
}

/// When a branch has no PR yet, fallback check-runs detection should query the
/// branch's pushremote repository rather than the first GitHub remote in the
/// repo.
#[rstest]
fn test_list_full_with_branch_fallback_using_fork_pushremote(mut repo: TestRepo) {
    setup_github_repo_with_feature(&mut repo);

    let feature_a_sha = branch_sha(&repo, "feature-a");
    repo.run_git(&[
        "config",
        "branch.feature-a.pushremote",
        "https://github.com/fork-owner/test-repo.git",
    ]);

    let fork_checks = r#"[{"status":"COMPLETED","conclusion":"SUCCESS"}]"#;
    let mock_bin = setup_mock_gh_with_api_data(
        &repo,
        "[]",
        &[
            (
                &format!("api repos/upstream-owner/test-repo/commits/{feature_a_sha}/check-runs"),
                "[]",
            ),
            (
                &format!("api repos/fork-owner/test-repo/commits/{feature_a_sha}/check-runs"),
                fork_checks,
            ),
        ],
    );

    let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);
    configure_mock_ci_env(&mut cmd, &mock_bin);
    let output = cmd.output().unwrap();
    assert!(output.status.success(), "wt list should succeed");

    let stdout = String::from_utf8_lossy(&output.stdout)
        .ansi_strip()
        .into_owned();
    let feature_a_line = stdout
        .lines()
        .find(|line| line.contains("feature-a"))
        .expect("expected feature-a line in wt list output");
    assert!(
        feature_a_line.contains(""),
        "expected feature-a to show passed branch CI from the fork repo fallback\nstdout:\n{stdout}",
    );
}

// =============================================================================
// GitLab error path tests
// =============================================================================

/// Test that when `glab mr view` fails after finding an MR, we show error status (not NoCI).
#[rstest]
fn test_list_full_with_gitlab_mr_view_failure(mut repo: TestRepo) {
    let head_sha = setup_gitlab_repo_with_feature(&mut repo);

    // Set up mock where mr list succeeds but mr view fails
    let mr_list_json = format!(
        r#"[{{
        "iid": 1,
        "sha": "{}",
        "has_conflicts": false,
        "detailed_merge_status": null,
        "source_project_id": 12345,
        "web_url": "https://gitlab.com/test/repo/-/merge_requests/1"
    }}]"#,
        head_sha
    );

    repo.setup_mock_glab_with_failing_mr_view(&mr_list_json, Some(12345));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);
        repo.configure_mock_commands(&mut cmd);
        assert_cmd_snapshot!("gitlab_mr_view_failure", cmd);
    });
}

/// Test that rate limit errors in `glab ci list` show error status (not NoCI).
///
/// This exercises the `is_retriable_error` check in `detect_gitlab_pipeline`,
/// which is the fallback path when no MR exists for a branch.
#[rstest]
fn test_list_full_with_gitlab_ci_rate_limit(mut repo: TestRepo) {
    setup_gitlab_repo_with_feature(&mut repo);

    // Mock returns empty MR list (no MRs), so we fall through to ci list,
    // which returns a rate limit error
    repo.setup_mock_glab_with_ci_rate_limit(Some(12345));

    let settings = setup_snapshot_settings(&repo);
    settings.bind(|| {
        let mut cmd = make_snapshot_cmd(&repo, "list", &["--full"], None);
        repo.configure_mock_commands(&mut cmd);
        assert_cmd_snapshot!("gitlab_ci_rate_limit", cmd);
    });
}