worktrunk 0.50.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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
//! 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_configured_platform_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 (the configured platform still 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 the platform explicitly 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 the platform is set 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);
        // The configured platform should force GitHub detection even with a 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_gitea_forge_platform(mut repo: TestRepo) {
    // `forge.platform = "gitea"` resolves to the (experimental) Gitea CI
    // backend, but without `tea` installed there's nothing to show — CI stays
    // blank, and `wt list` must not warn that the value is "invalid". (Gitea CI
    // detection with a mocked `tea` is covered by the `gitea_*` tests below.)
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/test-owner/test-repo.git",
    ]);
    repo.write_project_config("[forge]\nplatform = \"gitea\"\n");

    repo.add_worktree("feature");

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

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

    // Set an invalid platform value - 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);
    });
}

// =============================================================================
// Azure DevOps CI status tests
// =============================================================================

/// Set up a repo with an Azure DevOps remote and a `feature` worktree.
/// Returns the `feature` branch HEAD SHA.
fn setup_azure_repo_with_feature(repo: &mut TestRepo) -> String {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://dev.azure.com/myorg/myproject/_git/test-repo",
    ]);
    repo.add_worktree("feature");
    setup_tracking_for_all_branches(repo, "origin");
    branch_sha(repo, "feature")
}

/// Run an Azure DevOps CI status test with the given `az repos pr list` and
/// `az pipelines runs list` mock responses.
fn run_azure_ci_status_test(
    repo: &mut TestRepo,
    snapshot_name: &str,
    pr_list_json: &str,
    runs_json: &str,
) {
    repo.setup_mock_az_with_ci_data(pr_list_json, runs_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);
    });
}

/// An active PR with `mergeStatus: "conflicts"` surfaces as a Conflicts
/// indicator (exercises `detect_azure_pr`).
#[rstest]
fn test_list_full_with_azure_pr_conflicts(mut repo: TestRepo) {
    let head_sha = setup_azure_repo_with_feature(&mut repo);

    let pr_list_json = format!(
        r#"[{{
        "pullRequestId": 7,
        "mergeStatus": "conflicts",
        "lastMergeSourceCommit": {{"commitId": "{}"}},
        "repository": {{"name": "test-repo", "project": {{"name": "myproject"}}}}
    }}]"#,
        head_sha
    );

    run_azure_ci_status_test(&mut repo, "azure_pr_conflicts", &pr_list_json, "[]");
}

/// An active PR with `mergeStatus: "queued"` surfaces as a Running indicator.
#[rstest]
fn test_list_full_with_azure_pr_queued(mut repo: TestRepo) {
    let head_sha = setup_azure_repo_with_feature(&mut repo);

    let pr_list_json = format!(
        r#"[{{
        "pullRequestId": 7,
        "mergeStatus": "queued",
        "lastMergeSourceCommit": {{"commitId": "{}"}},
        "repository": {{"name": "test-repo", "project": {{"name": "myproject"}}}}
    }}]"#,
        head_sha
    );

    run_azure_ci_status_test(&mut repo, "azure_pr_queued", &pr_list_json, "[]");
}

/// No PR for the branch falls back to the latest pipeline run
/// (exercises `detect_azure_pipeline` via `parse_azure_pipeline_status`).
#[rstest]
#[case::passed("completed", "succeeded", "azure_pipeline_passed")]
#[case::failed("completed", "failed", "azure_pipeline_failed")]
#[case::running("inProgress", "null", "azure_pipeline_running")]
fn test_list_full_with_azure_pipeline_status(
    mut repo: TestRepo,
    #[case] status: &str,
    #[case] result: &str,
    #[case] snapshot_name: &str,
) {
    let head_sha = setup_azure_repo_with_feature(&mut repo);

    let runs_json = format!(
        r#"[{{
        "id": 4242,
        "status": "{}",
        "result": {},
        "sourceVersion": "{}"
    }}]"#,
        status,
        if result == "null" {
            "null".to_string()
        } else {
            format!(r#""{}""#, result)
        },
        head_sha
    );

    run_azure_ci_status_test(&mut repo, snapshot_name, "[]", &runs_json);
}

/// A pipeline run from a different SHA than local HEAD is marked stale (dimmed).
#[rstest]
fn test_list_full_with_azure_stale_pipeline(mut repo: TestRepo) {
    setup_azure_repo_with_feature(&mut repo);

    let runs_json = r#"[{
        "id": 4242,
        "status": "completed",
        "result": "succeeded",
        "sourceVersion": "0000000000000000000000000000000000000000"
    }]"#;

    run_azure_ci_status_test(&mut repo, "azure_stale_pipeline", "[]", runs_json);
}

/// No PR and no pipeline runs → no CI indicator.
#[rstest]
fn test_list_full_with_azure_no_ci(mut repo: TestRepo) {
    setup_azure_repo_with_feature(&mut repo);
    run_azure_ci_status_test(&mut repo, "azure_no_ci", "[]", "[]");
}

/// A retriable error from `az repos pr list` (e.g., HTTP 429) surfaces as an
/// error indicator rather than NoCI (exercises the `is_retriable_error` branch
/// in `detect_azure_pr`).
#[rstest]
fn test_list_full_with_azure_pr_list_retriable_error(mut repo: TestRepo) {
    setup_azure_repo_with_feature(&mut repo);
    repo.setup_mock_az_with_detection_errors(
        Some("ERROR: HTTP error 429: Too Many Requests"),
        None,
    );

    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!("azure_pr_list_retriable_error", cmd);
    });
}

/// A retriable error from `az pipelines runs list` surfaces as an error
/// indicator (exercises the `is_retriable_error` branch in
/// `detect_azure_pipeline`, reached when no PR exists for the branch).
#[rstest]
fn test_list_full_with_azure_pipeline_retriable_error(mut repo: TestRepo) {
    setup_azure_repo_with_feature(&mut repo);
    repo.setup_mock_az_with_detection_errors(
        None,
        Some("ERROR: HTTP error 429: Too Many Requests"),
    );

    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!("azure_pipeline_retriable_error", cmd);
    });
}

// =============================================================================
// Gitea CI status tests
// =============================================================================

/// Set up a repo with a Gitea remote and a `feature` worktree carrying its own
/// commit (so its HEAD SHA differs from `main`'s, keeping the per-branch
/// commit-status lookups distinct). Returns the `feature` HEAD SHA.
fn setup_gitea_repo_with_feature(repo: &mut TestRepo) -> String {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);
    let feature_wt = repo.add_worktree("feature");
    repo.commit_in_worktree(
        &feature_wt,
        "gitea-ci.txt",
        "gitea ci test",
        "feat: gitea feature",
    );
    setup_tracking_for_all_branches(repo, "origin");
    branch_sha(repo, "feature")
}

/// Run a Gitea CI status test with the given `tea api .../pulls` and
/// `tea api .../commits/{sha}/status` mock responses.
fn run_gitea_ci_status_test(
    repo: &mut TestRepo,
    snapshot_name: &str,
    head_sha: &str,
    pulls_json: &str,
    status_json: &str,
) {
    repo.setup_mock_tea_with_ci_data("owner", "test-repo", head_sha, pulls_json, status_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);
    });
}

/// Build a one-PR `tea api .../pulls` response for the `feature` branch.
fn gitea_feature_pr_json(head_sha: &str, mergeable: bool) -> String {
    format!(
        r#"[{{
        "mergeable": {mergeable},
        "html_url": "https://gitea.example.com/owner/test-repo/pulls/7",
        "head": {{
            "ref": "feature",
            "sha": "{head_sha}",
            "repo": {{"owner": {{"login": "owner"}}}}
        }}
    }}]"#
    )
}

/// An open PR with `mergeable: false` surfaces as a Conflicts indicator
/// (exercises `detect_gitea_pr`).
#[rstest]
fn test_list_full_with_gitea_pr_conflicts(mut repo: TestRepo) {
    let head_sha = setup_gitea_repo_with_feature(&mut repo);
    run_gitea_ci_status_test(
        &mut repo,
        "gitea_pr_conflicts",
        &head_sha,
        &gitea_feature_pr_json(&head_sha, false),
        r#"{"state":"","total_count":0}"#,
    );
}

/// An open PR's CI state comes from the PR head commit's combined status, and
/// the indicator links to the PR.
#[rstest]
#[case::passed("success", "gitea_pr_passed")]
#[case::failed("failure", "gitea_pr_failed")]
#[case::running("pending", "gitea_pr_running")]
fn test_list_full_with_gitea_pr_status(
    mut repo: TestRepo,
    #[case] state: &str,
    #[case] snapshot_name: &str,
) {
    let head_sha = setup_gitea_repo_with_feature(&mut repo);
    let status_json = format!(r#"{{"state":"{state}","total_count":2}}"#);
    run_gitea_ci_status_test(
        &mut repo,
        snapshot_name,
        &head_sha,
        &gitea_feature_pr_json(&head_sha, true),
        &status_json,
    );
}

/// No PR for the branch falls back to the HEAD commit's combined status
/// (exercises `detect_gitea_commit_status` and the `failure` state mapping).
#[rstest]
fn test_list_full_with_gitea_commit_status(mut repo: TestRepo) {
    let head_sha = setup_gitea_repo_with_feature(&mut repo);
    run_gitea_ci_status_test(
        &mut repo,
        "gitea_commit_status",
        &head_sha,
        "[]",
        r#"{"state":"failure","total_count":1}"#,
    );
}

/// No PR and no commit statuses → no CI indicator.
#[rstest]
fn test_list_full_with_gitea_no_ci(mut repo: TestRepo) {
    let head_sha = setup_gitea_repo_with_feature(&mut repo);
    run_gitea_ci_status_test(
        &mut repo,
        "gitea_no_ci",
        &head_sha,
        "[]",
        r#"{"state":"","total_count":0}"#,
    );
}

/// A retriable error from `tea api .../pulls` surfaces as an error indicator
/// rather than NoCI (exercises the `is_retriable_error` branch in
/// `detect_gitea_pr`).
#[rstest]
fn test_list_full_with_gitea_retriable_error(mut repo: TestRepo) {
    setup_gitea_repo_with_feature(&mut repo);
    repo.setup_mock_tea_with_detection_error(
        "Error: GET .../api/v1/repos/owner/test-repo/pulls: 429 Too Many Requests",
    );

    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!("gitea_retriable_error", cmd);
    });
}

/// A retriable error from the commit-status lookup (when no PR exists for the
/// branch) surfaces as an error indicator (exercises the `is_retriable_error`
/// branch in `fetch_combined_status`, reached via `detect_gitea_commit_status`).
#[rstest]
fn test_list_full_with_gitea_commit_status_retriable_error(mut repo: TestRepo) {
    let head_sha = setup_gitea_repo_with_feature(&mut repo);
    repo.setup_mock_tea_commit_status_error(
        &head_sha,
        "Error: GET .../api/v1/repos/owner/test-repo/commits/.../status: 429 Too Many Requests",
    );

    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!("gitea_commit_status_retriable_error", cmd);
    });
}

/// `wt list --remotes --full` exercises the commit-status fallback for a
/// remote-only branch and proves it queries the branch's own remote, not the
/// primary one. Two Gitea remotes (`origin` → `owner/test-repo`, `fork` →
/// `forkowner/test-repo`) plus a remote-only `fork/feature-remote` ref. The
/// mock answers only `forkowner/test-repo` SHA-status requests, so a primary-
/// remote lookup in the fallback would return no CI; the green `●` in the
/// snapshot proves the SHA-status path honors `branch.remote`. (The PR path
/// intentionally uses the primary remote, mirroring the `gh` backend; for this
/// branch it returns no PR and we fall through to the SHA-status path.)
#[rstest]
fn test_list_remotes_full_with_gitea_remote_branch(mut repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/owner/test-repo.git",
    ]);
    repo.run_git(&[
        "remote",
        "add",
        "fork",
        "https://gitea.example.com/forkowner/test-repo.git",
    ]);

    // Build the remote-only `fork/feature-remote` ref in a temporary local
    // branch (mirroring how `test_list_with_remotes_and_full` does it for
    // origin), then drop the local copy so the row appears as remote-only.
    repo.run_git(&["checkout", "-b", "feature-remote"]);
    std::fs::write(repo.root_path().join("gitea-fork.txt"), "fork content").unwrap();
    repo.run_git(&["add", "."]);
    repo.run_git(&["commit", "-m", "feat: fork feature"]);
    let head_sha = branch_sha(&repo, "feature-remote");
    repo.run_git(&["update-ref", "refs/remotes/fork/feature-remote", &head_sha]);
    repo.run_git(&["checkout", "main"]);
    repo.run_git(&["branch", "-D", "feature-remote"]);

    repo.setup_mock_tea_with_ci_data(
        "forkowner",
        "test-repo",
        &head_sha,
        "[]",
        r#"{"state":"success","total_count":1}"#,
    );

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

/// A PR opened from a fork (head owner ≠ the queried upstream owner) is
/// matched: `wt list --full` lists the *primary* remote's open PRs and filters
/// by the branch's push owner against `head.repo.owner.login`. Two Gitea
/// remotes (`origin` → `upstream/test-repo`, `fork` → `forkowner/test-repo`)
/// and the `feature` branch pushes to `fork`. The mock returns two open PRs for
/// the `feature` ref — a decoy from `other-owner` that must be filtered out and
/// the real one from `forkowner` — and answers the upstream's commit-status
/// lookup with `success`. The green `●` proves the fork PR matched; a revert to
/// querying/filtering by the branch's own remote would query `forkowner`'s
/// (unmocked) `/pulls` and lose the indicator. Mirrors the GitHub backend's
/// `test_list_full_filters_by_repo_owner`.
#[rstest]
fn test_list_full_with_gitea_fork_pr(mut repo: TestRepo) {
    repo.run_git(&[
        "remote",
        "set-url",
        "origin",
        "https://gitea.example.com/upstream/test-repo.git",
    ]);
    repo.run_git(&[
        "remote",
        "add",
        "fork",
        "https://gitea.example.com/forkowner/test-repo.git",
    ]);
    let feature_wt = repo.add_worktree("feature");
    repo.commit_in_worktree(
        &feature_wt,
        "gitea-fork-ci.txt",
        "gitea fork ci test",
        "feat: gitea fork feature",
    );
    setup_tracking_for_all_branches(&repo, "fork");
    let head_sha = branch_sha(&repo, "feature");

    let pulls_json = format!(
        r#"[
        {{
            "mergeable": true,
            "html_url": "https://gitea.example.com/upstream/test-repo/pulls/98",
            "head": {{"ref": "feature", "sha": "wrong_sha", "repo": {{"owner": {{"login": "other-owner"}}}}}}
        }},
        {{
            "mergeable": true,
            "html_url": "https://gitea.example.com/upstream/test-repo/pulls/7",
            "head": {{"ref": "feature", "sha": "{head_sha}", "repo": {{"owner": {{"login": "forkowner"}}}}}}
        }}
    ]"#
    );

    repo.setup_mock_tea_with_ci_data(
        "upstream",
        "test-repo",
        &head_sha,
        &pulls_json,
        r#"{"state":"success","total_count":1}"#,
    );

    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!("gitea_fork_pr", cmd);
    });
}