gwm-cli 1.0.3

git worktree manager — TUI + CLI, native libgit2, per-repo bootstrap
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
//! Unit tests for the `github` module: link storage (git branch config),
//! repo-slug extraction from the `origin` remote, and JSON parsing of
//! `gh issue view` / `gh pr view --json` payloads.

mod common;

use common::init_repo;
use gwm::github::{
  self, parse_issue_json, parse_pr_head_json, parse_pr_json, BranchLink, CiState, IssueState, LinkSource, PrState,
};

fn make_branch(repo: &git2::Repository, name: &str) {
  let head = repo.head().unwrap().peel_to_commit().unwrap();
  repo.branch(name, &head, false).unwrap();
}

#[test]
fn read_link_returns_none_when_branch_name_has_no_issue() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "random-branch");

  let link = github::read_link(&repo, "random-branch").unwrap();

  assert_eq!(link.issue, None);
  assert_eq!(link.pr, None);
  assert_eq!(link.issue_source, LinkSource::None);
  assert_eq!(link.pr_source, LinkSource::None);
}

#[test]
fn read_link_auto_detects_issue_from_branch_name() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.issue, Some(42));
  assert_eq!(link.issue_source, LinkSource::BranchName);
  assert_eq!(link.pr, None);
  assert_eq!(link.pr_source, LinkSource::None);
}

#[test]
fn link_issue_writes_branch_config_overriding_auto_detect() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  github::link_issue(&repo, "feat/#42-tui-search", 99).unwrap();
  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.issue, Some(99));
  assert_eq!(link.issue_source, LinkSource::Explicit);
}

#[test]
fn unlink_issue_removes_explicit_override_and_falls_back_to_branch_name() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  github::link_issue(&repo, "feat/#42-tui-search", 99).unwrap();
  github::unlink_issue(&repo, "feat/#42-tui-search").unwrap();
  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  // Auto-detection from branch name kicks back in.
  assert_eq!(link.issue, Some(42));
  assert_eq!(link.issue_source, LinkSource::BranchName);
}

#[test]
fn unlink_issue_on_unlinked_branch_is_idempotent() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "random-branch");

  // Should not error even if nothing to unlink.
  github::unlink_issue(&repo, "random-branch").unwrap();
  github::unlink_issue(&repo, "random-branch").unwrap();
}

#[test]
fn link_pr_writes_branch_config() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  github::link_pr(&repo, "feat/#42-tui-search", 61).unwrap();
  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.pr, Some(61));
  assert_eq!(link.pr_source, LinkSource::Explicit);
}

#[test]
fn unlink_pr_clears_the_pr_link_only() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  github::link_issue(&repo, "feat/#42-tui-search", 99).unwrap();
  github::link_pr(&repo, "feat/#42-tui-search", 61).unwrap();
  github::unlink_pr(&repo, "feat/#42-tui-search").unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(link.issue, Some(99));
  assert_eq!(link.pr, None);
}

// --- Persisted PR detection (issue #283) ---------------------------------

#[test]
fn persist_detected_pr_is_read_back_as_detected_source() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  // The detected PR lives in its own key so the no-fetch table read path
  // can surface it on every row while staying distinguishable from an
  // explicit link.
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.pr, Some(77));
  assert_eq!(link.pr_source, LinkSource::Detected);
}

#[test]
fn read_link_round_trips_persisted_issue_title() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");
  repo
    .config()
    .unwrap()
    .set_str("branch.feat/#42-tui-search.gwm-issue-title", "TUI title \"quoted\"")
    .unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.issue, Some(42));
  assert_eq!(link.issue_source, LinkSource::BranchName);
  assert_eq!(link.issue_title.as_deref(), Some("TUI title \"quoted\""));
}

#[test]
fn read_link_round_trips_explicit_and_detected_pr_titles() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");
  {
    let mut cfg = repo.config().unwrap();
    cfg.set_str("branch.feat/#42-tui-search.gwm-pr", "61").unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-title", "Explicit PR title")
      .unwrap();
    cfg.set_str("branch.feat/#42-tui-search.gwm-pr-detected", "77").unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-detected-title", "Detected PR title")
      .unwrap();
  }

  let explicit = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(explicit.pr, Some(61));
  assert_eq!(explicit.pr_source, LinkSource::Explicit);
  assert_eq!(explicit.pr_title.as_deref(), Some("Explicit PR title"));

  github::unlink_pr(&repo, "feat/#42-tui-search").unwrap();
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  repo
    .config()
    .unwrap()
    .set_str("branch.feat/#42-tui-search.gwm-pr-detected-title", "Detected PR title")
    .unwrap();
  let detected = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(detected.pr, Some(77));
  assert_eq!(detected.pr_source, LinkSource::Detected);
  assert_eq!(detected.pr_title.as_deref(), Some("Detected PR title"));
}

#[test]
fn read_link_round_trips_persisted_issue_state() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");
  github::persist_issue_state(&repo, "feat/#42-tui-search", IssueState::Closed).unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.issue, Some(42));
  assert_eq!(link.issue_source, LinkSource::BranchName);
  assert_eq!(link.issue_state, Some(IssueState::Closed));
}

#[test]
fn read_link_round_trips_explicit_and_detected_pr_states() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");
  github::link_pr(&repo, "feat/#42-tui-search", 61).unwrap();
  github::persist_pr_state(&repo, "feat/#42-tui-search", PrState::Merged).unwrap();
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  github::persist_detected_pr_state(&repo, "feat/#42-tui-search", PrState::Draft).unwrap();

  let explicit = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(explicit.pr, Some(61));
  assert_eq!(explicit.pr_source, LinkSource::Explicit);
  assert_eq!(explicit.pr_state, Some(PrState::Merged));

  github::unlink_pr(&repo, "feat/#42-tui-search").unwrap();
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  github::persist_detected_pr_state(&repo, "feat/#42-tui-search", PrState::Draft).unwrap();
  let detected = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(detected.pr, Some(77));
  assert_eq!(detected.pr_source, LinkSource::Detected);
  assert_eq!(detected.pr_state, Some(PrState::Draft));
}

#[test]
fn unlink_issue_clears_persisted_issue_title() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "random-branch");
  {
    let mut cfg = repo.config().unwrap();
    cfg.set_str("branch.random-branch.gwm-issue", "99").unwrap();
    cfg
      .set_str("branch.random-branch.gwm-issue-title", "Stale issue title")
      .unwrap();
    cfg.set_str("branch.random-branch.gwm-issue-state", "closed").unwrap();
  }

  github::unlink_issue(&repo, "random-branch").unwrap();
  let link = github::read_link(&repo, "random-branch").unwrap();

  assert_eq!(link.issue, None);
  assert_eq!(link.issue_title, None);
  assert_eq!(link.issue_state, None);
}

#[test]
fn unlink_pr_clears_explicit_and_detected_pr_titles() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");
  {
    let mut cfg = repo.config().unwrap();
    cfg.set_str("branch.feat/#42-tui-search.gwm-pr", "61").unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-title", "Explicit PR title")
      .unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-state", "merged")
      .unwrap();
    cfg.set_str("branch.feat/#42-tui-search.gwm-pr-detected", "77").unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-detected-title", "Detected PR title")
      .unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-detected-state", "draft")
      .unwrap();
  }

  github::unlink_pr(&repo, "feat/#42-tui-search").unwrap();
  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.pr, None);
  assert_eq!(link.pr_title, None);
  assert_eq!(link.pr_state, None);
}

#[test]
fn clear_persisted_detected_pr_clears_detected_title() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");
  {
    let mut cfg = repo.config().unwrap();
    cfg.set_str("branch.feat/#42-tui-search.gwm-pr-detected", "77").unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-detected-title", "Detected PR title")
      .unwrap();
    cfg
      .set_str("branch.feat/#42-tui-search.gwm-pr-detected-state", "draft")
      .unwrap();
  }

  github::clear_persisted_detected_pr(&repo, "feat/#42-tui-search").unwrap();
  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();

  assert_eq!(link.pr, None);
  assert_eq!(link.pr_title, None);
  assert_eq!(link.pr_state, None);
}

#[test]
fn explicit_pr_overrides_persisted_detected_pr() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  // Both keys set: the explicit `gwm link --pr` must win, and its source
  // must read back as Explicit (not Detected) so the pane badge is right.
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  github::link_pr(&repo, "feat/#42-tui-search", 61).unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(link.pr, Some(61));
  assert_eq!(link.pr_source, LinkSource::Explicit);
}

#[test]
fn persist_detected_pr_overwrites_a_previous_detection() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  // Re-detection (the branch's PR changed) refreshes the stored value.
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  github::persist_detected_pr_title(&repo, "feat/#42-tui-search", "Old detected title").unwrap();
  github::persist_detected_pr_state(&repo, "feat/#42-tui-search", PrState::Merged).unwrap();
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 88).unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(link.pr, Some(88));
  assert_eq!(link.pr_title, None);
  assert_eq!(link.pr_state, None);
  assert_eq!(link.pr_source, LinkSource::Detected);
}

#[test]
fn persist_detected_pr_keeps_title_when_number_is_unchanged() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  github::persist_detected_pr_title(&repo, "feat/#42-tui-search", "Detected PR title").unwrap();
  github::persist_detected_pr_state(&repo, "feat/#42-tui-search", PrState::Draft).unwrap();

  // A successful refresh that redetects the same PR should not throw away a
  // known title before the follow-up status fetch has a chance to update it.
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(link.pr, Some(77));
  assert_eq!(link.pr_title.as_deref(), Some("Detected PR title"));
  assert_eq!(link.pr_state, Some(PrState::Draft));
  assert_eq!(link.pr_source, LinkSource::Detected);
}

#[test]
fn unlink_pr_also_clears_a_persisted_detection() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  // A persisted detection plus an explicit link, then unlink: unlinking a PR
  // must not resurface a stale auto-detection from the detected key.
  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  github::link_pr(&repo, "feat/#42-tui-search", 61).unwrap();
  github::unlink_pr(&repo, "feat/#42-tui-search").unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(link.pr, None);
  assert_eq!(link.pr_source, LinkSource::None);
}

#[test]
fn clear_persisted_detected_pr_removes_the_detected_link() {
  let (_dir, repo) = init_repo();
  make_branch(&repo, "feat/#42-tui-search");

  github::persist_detected_pr(&repo, "feat/#42-tui-search", 77).unwrap();
  github::clear_persisted_detected_pr(&repo, "feat/#42-tui-search").unwrap();

  let link = github::read_link(&repo, "feat/#42-tui-search").unwrap();
  assert_eq!(link.pr, None);
  assert_eq!(link.pr_source, LinkSource::None);
}

// --- Repo-slug extraction ------------------------------------------------

fn set_origin(repo: &git2::Repository, url: &str) {
  // remote_set_url is a no-op when the remote doesn't exist, so create it first.
  let _ = repo.remote("origin", url);
}

#[test]
fn repo_slug_from_ssh_origin() {
  let (_dir, repo) = init_repo();
  set_origin(&repo, "git@github.com:kbrdn1/gwm-cli.git");

  let slug = github::repo_slug(&repo).unwrap();

  assert_eq!(slug, "kbrdn1/gwm-cli");
}

#[test]
fn repo_slug_from_https_origin() {
  let (_dir, repo) = init_repo();
  set_origin(&repo, "https://github.com/kbrdn1/gwm-cli.git");

  let slug = github::repo_slug(&repo).unwrap();

  assert_eq!(slug, "kbrdn1/gwm-cli");
}

#[test]
fn repo_slug_strips_trailing_dot_git_when_absent() {
  let (_dir, repo) = init_repo();
  set_origin(&repo, "https://github.com/kbrdn1/gwm-cli");

  let slug = github::repo_slug(&repo).unwrap();

  assert_eq!(slug, "kbrdn1/gwm-cli");
}

#[test]
fn repo_slug_handles_trailing_slash_after_dot_git() {
  // Copilot PR #68 review: `https://…/repo.git/` previously left ".git"
  // in the slug because we stripped `.git` before trimming `/`. The fix
  // is to normalise trailing slashes first, then strip `.git`.
  let (_dir, repo) = init_repo();
  set_origin(&repo, "https://github.com/kbrdn1/gwm-cli.git/");

  let slug = github::repo_slug(&repo).unwrap();

  assert_eq!(slug, "kbrdn1/gwm-cli");
}

#[test]
fn repo_slug_handles_trailing_slash_without_dot_git() {
  let (_dir, repo) = init_repo();
  set_origin(&repo, "https://github.com/kbrdn1/gwm-cli/");

  let slug = github::repo_slug(&repo).unwrap();

  assert_eq!(slug, "kbrdn1/gwm-cli");
}

#[test]
fn repo_slug_errors_when_no_origin_remote() {
  let (_dir, repo) = init_repo();

  let err = github::repo_slug(&repo).unwrap_err();
  let msg = err.to_string();
  assert!(msg.contains("origin"), "error should mention origin remote: {}", msg);
}

#[test]
fn repo_slug_errors_when_origin_is_not_github() {
  let (_dir, repo) = init_repo();
  set_origin(&repo, "https://gitlab.com/kbrdn1/something.git");

  let err = github::repo_slug(&repo).unwrap_err();
  let msg = err.to_string();
  assert!(msg.contains("github"), "error should mention github: {}", msg);
}

// --- JSON parsing --------------------------------------------------------

#[test]
fn parse_issue_json_extracts_open_state_and_labels() {
  let json = r#"{
    "number": 42,
    "title": "TUI: fuzzy search",
    "state": "OPEN",
    "url": "https://github.com/kbrdn1/gwm-cli/issues/42",
    "labels": [
      {"name": "feature", "color": "0e8a16"},
      {"name": "tui", "color": "5319e7"}
    ],
    "updatedAt": "2026-05-19T10:00:00Z"
  }"#;

  let issue = parse_issue_json(json).unwrap();

  assert_eq!(issue.number, 42);
  assert_eq!(issue.title, "TUI: fuzzy search");
  assert_eq!(issue.state, IssueState::Open);
  assert_eq!(issue.url, "https://github.com/kbrdn1/gwm-cli/issues/42");
  assert_eq!(issue.labels, vec!["feature", "tui"]);
}

#[test]
fn parse_issue_json_handles_closed_state() {
  let json = r#"{
    "number": 7,
    "title": "old bug",
    "state": "CLOSED",
    "url": "https://github.com/x/y/issues/7",
    "labels": [],
    "updatedAt": "2025-01-01T00:00:00Z"
  }"#;

  let issue = parse_issue_json(json).unwrap();

  assert_eq!(issue.state, IssueState::Closed);
  assert!(issue.labels.is_empty());
}

#[test]
fn parse_pr_json_extracts_state_draft_and_checks() {
  // Mirror of `gh pr view <N> --json state,title,isDraft,url,statusCheckRollup,updatedAt`.
  let json = r#"{
    "number": 61,
    "title": "feat(tui): fuzzy search",
    "state": "OPEN",
    "isDraft": true,
    "url": "https://github.com/kbrdn1/gwm-cli/pull/61",
    "statusCheckRollup": [
      {"name": "ci", "status": "COMPLETED", "conclusion": "SUCCESS"},
      {"name": "lint", "status": "COMPLETED", "conclusion": "SUCCESS"},
      {"name": "fmt", "status": "IN_PROGRESS", "conclusion": null}
    ],
    "updatedAt": "2026-05-19T10:00:00Z"
  }"#;

  let pr = parse_pr_json(json).unwrap();

  assert_eq!(pr.number, 61);
  assert_eq!(pr.title, "feat(tui): fuzzy search");
  assert_eq!(pr.state, PrState::Draft);
  assert_eq!(pr.url, "https://github.com/kbrdn1/gwm-cli/pull/61");
  // 2 out of 3 checks completed (the IN_PROGRESS one is still running).
  assert_eq!(pr.checks_passed, 2);
  assert_eq!(pr.checks_total, 3);
}

#[test]
fn parse_pr_json_merged_state_overrides_open() {
  let json = r#"{
    "number": 61,
    "title": "feat(tui): fuzzy search",
    "state": "MERGED",
    "isDraft": false,
    "url": "https://github.com/kbrdn1/gwm-cli/pull/61",
    "statusCheckRollup": [],
    "updatedAt": "2026-05-19T10:00:00Z"
  }"#;

  let pr = parse_pr_json(json).unwrap();

  assert_eq!(pr.state, PrState::Merged);
  assert_eq!(pr.checks_total, 0);
}

#[test]
fn parse_pr_json_handles_missing_status_check_rollup() {
  let json = r#"{
    "number": 5,
    "title": "x",
    "state": "OPEN",
    "isDraft": false,
    "url": "https://github.com/x/y/pull/5",
    "updatedAt": "2026-05-19T10:00:00Z"
  }"#;

  let pr = parse_pr_json(json).unwrap();

  assert_eq!(pr.checks_total, 0);
  assert_eq!(pr.checks_passed, 0);
  assert_eq!(pr.state, PrState::Open);
}

// --- CI state derivation (issue #299) -----------------------------------

/// Build a minimal PR JSON body with the given `statusCheckRollup` array
/// literal so the CI-state tests stay focused on the rollup.
fn pr_json_with_rollup(rollup: &str) -> String {
  format!(
    r#"{{
      "number": 7,
      "title": "x",
      "state": "OPEN",
      "isDraft": false,
      "url": "https://github.com/x/y/pull/7",
      "statusCheckRollup": {rollup},
      "updatedAt": "2026-06-15T10:00:00Z"
    }}"#
  )
}

#[test]
fn ci_state_is_passing_when_all_checks_succeed() {
  let json = pr_json_with_rollup(
    r#"[
      {"name": "ci", "status": "COMPLETED", "conclusion": "SUCCESS"},
      {"name": "lint", "status": "COMPLETED", "conclusion": "SUCCESS"}
    ]"#,
  );
  assert_eq!(parse_pr_json(&json).unwrap().ci, CiState::Passing);
}

#[test]
fn ci_state_treats_neutral_and_skipped_as_passing() {
  let json = pr_json_with_rollup(
    r#"[
      {"name": "ci", "status": "COMPLETED", "conclusion": "SUCCESS"},
      {"name": "optional", "status": "COMPLETED", "conclusion": "NEUTRAL"},
      {"name": "deploy", "status": "COMPLETED", "conclusion": "SKIPPED"}
    ]"#,
  );
  assert_eq!(parse_pr_json(&json).unwrap().ci, CiState::Passing);
}

#[test]
fn ci_state_is_running_when_a_check_is_in_flight() {
  let json = pr_json_with_rollup(
    r#"[
      {"name": "ci", "status": "COMPLETED", "conclusion": "SUCCESS"},
      {"name": "fmt", "status": "IN_PROGRESS", "conclusion": null}
    ]"#,
  );
  assert_eq!(parse_pr_json(&json).unwrap().ci, CiState::Running);
}

#[test]
fn ci_state_treats_queued_and_pending_as_running() {
  let json = pr_json_with_rollup(
    r#"[
      {"name": "queued", "status": "QUEUED", "conclusion": null},
      {"name": "pending", "status": "PENDING", "conclusion": null}
    ]"#,
  );
  assert_eq!(parse_pr_json(&json).unwrap().ci, CiState::Running);
}

#[test]
fn ci_state_is_failing_on_any_failed_conclusion() {
  for conclusion in ["FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED"] {
    let json = pr_json_with_rollup(&format!(
      r#"[
        {{"name": "ci", "status": "COMPLETED", "conclusion": "SUCCESS"}},
        {{"name": "broken", "status": "COMPLETED", "conclusion": "{conclusion}"}}
      ]"#
    ));
    assert_eq!(
      parse_pr_json(&json).unwrap().ci,
      CiState::Failing,
      "conclusion {conclusion} must read as Failing"
    );
  }
}

#[test]
fn ci_state_failing_outranks_running() {
  // A red check must never hide behind a still-running one.
  let json = pr_json_with_rollup(
    r#"[
      {"name": "still-going", "status": "IN_PROGRESS", "conclusion": null},
      {"name": "broken", "status": "COMPLETED", "conclusion": "FAILURE"}
    ]"#,
  );
  assert_eq!(parse_pr_json(&json).unwrap().ci, CiState::Failing);
}

#[test]
fn ci_state_is_none_when_there_are_no_checks() {
  let json = pr_json_with_rollup("[]");
  assert_eq!(parse_pr_json(&json).unwrap().ci, CiState::None);
}

#[test]
fn ci_state_classifies_legacy_status_context_state() {
  // A `StatusContext` (legacy commit-status API) carries `state`, not
  // `status` / `conclusion`. A failed external CI status must read red, not
  // be mistaken for a still-running check (Codex review #302).
  let failing = pr_json_with_rollup(r#"[{"context": "ci/ext", "state": "FAILURE"}]"#);
  assert_eq!(parse_pr_json(&failing).unwrap().ci, CiState::Failing);

  let error = pr_json_with_rollup(r#"[{"context": "ci/ext", "state": "ERROR"}]"#);
  assert_eq!(parse_pr_json(&error).unwrap().ci, CiState::Failing);

  let success = pr_json_with_rollup(r#"[{"context": "ci/ext", "state": "SUCCESS"}]"#);
  assert_eq!(parse_pr_json(&success).unwrap().ci, CiState::Passing);

  let pending = pr_json_with_rollup(r#"[{"context": "ci/ext", "state": "PENDING"}]"#);
  assert_eq!(parse_pr_json(&pending).unwrap().ci, CiState::Running);
}

#[test]
fn ci_state_treats_non_success_terminal_conclusions_as_failing() {
  // A completed check whose conclusion is a terminal failure GitHub doesn't
  // list among the "common" four (e.g. STARTUP_FAILURE, STALE) must still
  // read red rather than fall through to green (Codex review #302).
  for conclusion in ["STARTUP_FAILURE", "STALE"] {
    let json = pr_json_with_rollup(&format!(
      r#"[{{"name": "broken", "status": "COMPLETED", "conclusion": "{conclusion}"}}]"#
    ));
    assert_eq!(
      parse_pr_json(&json).unwrap().ci,
      CiState::Failing,
      "conclusion {conclusion} must read as Failing"
    );
  }
}

#[test]
fn checks_passed_counts_accepted_terminals_so_count_matches_ci_label() {
  // The N/M shown next to the CI label must use the same accepted terminals
  // as the state, else a green rollup renders "passing 1/3" (Codex review #302).
  let json = pr_json_with_rollup(
    r#"[
      {"name": "ci", "status": "COMPLETED", "conclusion": "SUCCESS"},
      {"name": "optional", "status": "COMPLETED", "conclusion": "NEUTRAL"},
      {"name": "deploy", "status": "COMPLETED", "conclusion": "SKIPPED"}
    ]"#,
  );
  let pr = parse_pr_json(&json).unwrap();
  assert_eq!(pr.ci, CiState::Passing);
  assert_eq!(pr.checks_passed, 3);
  assert_eq!(pr.checks_total, 3);
}

// --- Labels: gh label list --json contract (issue #81) ------------------

#[test]
fn parse_labels_json_returns_remote_labels() {
  // Mirror of `gh label list --json name,color,description --limit 1000`
  // — a JSON array, even when there's only one entry.
  let json = r#"[
    {"name": "bug", "color": "d73a4a", "description": "Something isn't working"},
    {"name": "enhancement", "color": "a2eeef", "description": ""},
    {"name": "good first issue", "color": "7057ff", "description": "Good for newcomers"}
  ]"#;
  let labels = github::parse_labels_json(json).unwrap();
  assert_eq!(labels.len(), 3);
  assert_eq!(labels[0].name, "bug");
  assert_eq!(labels[0].color, "d73a4a");
  assert_eq!(labels[0].description.as_deref(), Some("Something isn't working"));
  // Empty description must round-trip as `Some("")` — the labels diff
  // module normalises empty == None on its own.
  assert_eq!(labels[1].description.as_deref(), Some(""));
  // Whitespace in name preserved verbatim.
  assert_eq!(labels[2].name, "good first issue");
}

#[test]
fn parse_labels_json_handles_empty_array() {
  let json = r#"[]"#;
  let labels = github::parse_labels_json(json).unwrap();
  assert!(labels.is_empty());
}

#[test]
fn parse_labels_json_tolerates_missing_description_field() {
  // gh sometimes returns the field as absent rather than empty.
  let json = r#"[{"name": "wip", "color": "ededed"}]"#;
  let labels = github::parse_labels_json(json).unwrap();
  assert_eq!(labels[0].name, "wip");
  assert_eq!(labels[0].description, None);
}

#[test]
fn parse_labels_json_rejects_malformed_payload() {
  let err = github::parse_labels_json("not json").unwrap_err();
  let msg = err.to_string();
  assert!(msg.contains("labels"), "should mention labels: {}", msg);
}

#[test]
fn parse_labels_json_normalises_uppercase_color() {
  // GitHub sometimes serialises colours uppercase. The parsed
  // `RemoteLabel.color` must already be lowercase 6-hex so callers
  // (diff engine, printer) can rely on the invariant without re-
  // normalising at each call site. Copilot review on PR #90.
  let json = r#"[{"name": "bug", "color": "D73A4A", "description": "broken"}]"#;
  let labels = github::parse_labels_json(json).unwrap();
  assert_eq!(labels[0].color, "d73a4a");
}

#[test]
fn parse_labels_json_rejects_missing_color_field() {
  // Defensive contract check: gh's documented schema always carries
  // a `color`. If a future version dropped the field, a silent
  // `#[serde(default)]` would turn it into an empty string and the
  // diff would flag every remote label as a colour mismatch. Better
  // to fail loud at parse time. Copilot review on PR #90.
  let json = r#"[{"name": "bug", "description": "broken"}]"#;
  let err = github::parse_labels_json(json).unwrap_err();
  let msg = err.to_string();
  assert!(
    msg.contains("color") || msg.contains("missing"),
    "error should mention the missing color field: {}",
    msg
  );
}

// --- Argv contract for gh label commands --------------------------------

#[test]
fn label_create_argv_carries_name_color_description_and_force() {
  // We don't shell out in tests, but the argv builder is the contract
  // surface: name, --color, --description (when present), --force.
  use gwm::labels::LabelSpec;
  let spec = LabelSpec {
    name: "good first issue".into(),
    description: Some("Good for newcomers".into()),
    color: "7057ff".into(),
  };
  let argv = github::label_create_argv("kbrdn1/gwm-cli", &spec);
  // Order is not asserted strictly, but the elements must be present.
  let joined = argv.join(" ");
  assert!(argv.contains(&"label".to_string()));
  assert!(argv.contains(&"create".to_string()));
  assert!(argv.contains(&"good first issue".to_string()));
  assert!(argv.contains(&"--force".to_string()));
  assert!(joined.contains("--color 7057ff"), "color flag missing in {}", joined);
  assert!(
    joined.contains("--description Good for newcomers"),
    "description flag missing in {}",
    joined
  );
  assert!(joined.contains("--repo kbrdn1/gwm-cli"));
}

#[test]
fn label_create_argv_omits_description_when_absent() {
  use gwm::labels::LabelSpec;
  let spec = LabelSpec {
    name: "wip".into(),
    description: None,
    color: "ededed".into(),
  };
  let argv = github::label_create_argv("kbrdn1/gwm-cli", &spec);
  assert!(
    !argv.iter().any(|a| a == "--description"),
    "no --description flag when desc absent, got {:?}",
    argv
  );
}

#[test]
fn label_delete_argv_carries_name_repo_and_yes() {
  let argv = github::label_delete_argv("kbrdn1/gwm-cli", "wontfix");
  assert!(argv.contains(&"label".to_string()));
  assert!(argv.contains(&"delete".to_string()));
  assert!(argv.contains(&"wontfix".to_string()));
  // --yes skips the destructive-confirm prompt; without it `gh` blocks
  // on a TTY read and gwm hangs.
  assert!(argv.contains(&"--yes".to_string()));
  assert!(argv.join(" ").contains("--repo kbrdn1/gwm-cli"));
}

// --- Milestones: gh api …/milestones contract (issue #82) --------------

#[test]
fn parse_milestones_json_returns_remote_milestones() {
  // Mirror of `gh api repos/:owner/:repo/milestones?state=all` — an
  // array of objects with `number`, `title`, `state`, optional
  // `description` and `due_on`.
  let json = r#"[
    {"number": 1, "title": "v0.7.0", "state": "open", "description": "Configurability sprint", "due_on": "2026-07-15T23:59:59Z"},
    {"number": 2, "title": "v0.6.0", "state": "closed", "description": "", "due_on": null},
    {"number": 3, "title": "Backlog", "state": "open"}
  ]"#;
  let milestones = github::parse_milestones_json(json).unwrap();
  assert_eq!(milestones.len(), 3);

  assert_eq!(milestones[0].number, 1);
  assert_eq!(milestones[0].title, "v0.7.0");
  assert_eq!(milestones[0].state, gwm::milestones::MilestoneState::Open);
  assert_eq!(milestones[0].description.as_deref(), Some("Configurability sprint"));
  assert_eq!(milestones[0].due_on.as_deref(), Some("2026-07-15T23:59:59Z"));

  assert_eq!(milestones[1].state, gwm::milestones::MilestoneState::Closed);
  // Empty description round-trips as Some("") — milestones diff
  // collapses it to None on its own (same as labels).
  assert_eq!(milestones[1].description.as_deref(), Some(""));
  // `due_on: null` reads as None.
  assert_eq!(milestones[1].due_on, None);

  assert_eq!(milestones[2].title, "Backlog");
  assert_eq!(milestones[2].description, None);
  assert_eq!(milestones[2].due_on, None);
}

#[test]
fn parse_milestones_json_handles_empty_array() {
  let json = r#"[]"#;
  let milestones = github::parse_milestones_json(json).unwrap();
  assert!(milestones.is_empty());
}

#[test]
fn parse_milestones_json_rejects_unknown_state() {
  // GitHub only emits `open` / `closed`; anything else means the
  // contract changed under us and we want to know loud.
  let json = r#"[{"number": 1, "title": "x", "state": "draft"}]"#;
  let err = github::parse_milestones_json(json).unwrap_err();
  let msg = err.to_string();
  assert!(
    msg.contains("draft") || msg.contains("state"),
    "should mention state: {}",
    msg
  );
}

#[test]
fn parse_milestones_json_rejects_malformed_payload() {
  let err = github::parse_milestones_json("not json").unwrap_err();
  let msg = err.to_string();
  assert!(msg.contains("milestones"), "should mention milestones: {}", msg);
}

// --- Argv contract for gh api milestones ---------------------------------

#[test]
fn milestone_list_argv_uses_repos_endpoint_with_state_all() {
  // `gh api --paginate repos/<slug>/milestones?state=all&per_page=100`
  // — `state=all` is the key bit: without it, closed milestones
  // disappear from the diff and `gwm milestones push --prune` thinks
  // they're already gone.
  let argv = github::milestone_list_argv("kbrdn1/gwm-cli");
  let joined = argv.join(" ");
  assert!(argv.contains(&"api".to_string()), "expected 'api', got {:?}", argv);
  assert!(
    joined.contains("repos/kbrdn1/gwm-cli/milestones"),
    "expected milestones endpoint, got {}",
    joined
  );
  assert!(joined.contains("state=all"), "expected state=all, got {}", joined);
}

#[test]
fn milestone_list_argv_uses_paginate_for_repos_with_many_milestones() {
  // GitHub's milestones list endpoint caps `per_page` at 100. Without
  // `--paginate`, repos with more than 100 milestones would diff
  // against a truncated remote set, leading to bogus creates and a
  // dangerously confusing `--prune` (Copilot review on PR #92).
  let argv = github::milestone_list_argv("kbrdn1/gwm-cli");
  assert!(
    argv.contains(&"--paginate".to_string()),
    "expected --paginate flag, got {:?}",
    argv
  );
}

#[test]
fn milestone_create_argv_uses_post_with_title_and_state() {
  use gwm::milestones::{MilestoneSpec, MilestoneState};
  let spec = MilestoneSpec {
    title: "v0.7.0".into(),
    description: Some("Configurability sprint".into()),
    due_on: Some("2026-07-15T23:59:59Z".into()),
    state: MilestoneState::Open,
  };
  let argv = github::milestone_create_argv("kbrdn1/gwm-cli", &spec);
  let joined = argv.join(" ");
  assert!(argv.contains(&"api".to_string()));
  assert!(argv.contains(&"-X".to_string()));
  assert!(argv.contains(&"POST".to_string()));
  assert!(
    joined.contains("repos/kbrdn1/gwm-cli/milestones"),
    "expected milestones endpoint, got {}",
    joined
  );
  // `-f title=…` is gh's form-encoded body syntax. The flag must
  // appear exactly once per field.
  assert!(joined.contains("title=v0.7.0"), "missing title=…: {}", joined);
  assert!(
    joined.contains("description=Configurability sprint"),
    "missing description=…: {}",
    joined
  );
  assert!(
    joined.contains("due_on=2026-07-15T23:59:59Z"),
    "missing due_on=…: {}",
    joined
  );
  assert!(joined.contains("state=open"), "missing state=…: {}", joined);
}

#[test]
fn milestone_create_argv_omits_description_and_due_on_when_absent() {
  // Same defensive contract as label_create: skip the flag entirely
  // rather than send empty, so the remote isn't wiped of a value the
  // user didn't intend to touch.
  use gwm::milestones::{MilestoneSpec, MilestoneState};
  let spec = MilestoneSpec {
    title: "Backlog".into(),
    description: None,
    due_on: None,
    state: MilestoneState::Open,
  };
  let argv = github::milestone_create_argv("kbrdn1/gwm-cli", &spec);
  let joined = argv.join(" ");
  assert!(
    !joined.contains("description="),
    "no description= flag when desc absent, got {}",
    joined
  );
  assert!(
    !joined.contains("due_on="),
    "no due_on= flag when due_on absent, got {}",
    joined
  );
  // title and state still present (state always known).
  assert!(joined.contains("title=Backlog"));
  assert!(joined.contains("state=open"));
}

#[test]
fn milestone_update_argv_uses_patch_with_number_in_path() {
  use gwm::milestones::{MilestoneSpec, MilestoneState};
  let spec = MilestoneSpec {
    title: "v0.7.0".into(),
    description: None,
    due_on: Some("2026-07-15T23:59:59Z".into()),
    state: MilestoneState::Closed,
  };
  let argv = github::milestone_update_argv("kbrdn1/gwm-cli", 42, &spec);
  let joined = argv.join(" ");
  assert!(argv.contains(&"-X".to_string()));
  assert!(argv.contains(&"PATCH".to_string()));
  assert!(
    joined.contains("repos/kbrdn1/gwm-cli/milestones/42"),
    "expected number in path, got {}",
    joined
  );
  assert!(joined.contains("state=closed"));
  assert!(joined.contains("due_on=2026-07-15T23:59:59Z"));
}

#[test]
fn milestone_delete_argv_uses_delete_with_number_in_path() {
  let argv = github::milestone_delete_argv("kbrdn1/gwm-cli", 7);
  let joined = argv.join(" ");
  assert!(argv.contains(&"-X".to_string()));
  assert!(argv.contains(&"DELETE".to_string()));
  assert!(
    joined.contains("repos/kbrdn1/gwm-cli/milestones/7"),
    "expected number in path, got {}",
    joined
  );
}

#[test]
fn branch_link_summary_renders_human_readable() {
  let link = BranchLink {
    issue: Some(42),
    pr: Some(61),
    issue_title: None,
    pr_title: None,
    issue_state: None,
    pr_state: None,
    issue_source: LinkSource::BranchName,
    pr_source: LinkSource::Explicit,
  };
  let s = link.summary();
  assert!(s.contains("#42"), "summary should mention issue #42: {}", s);
  assert!(s.contains("#61"), "summary should mention PR #61: {}", s);
}

// --- Issue #100: prune-path argv-injection guard ------------------------

#[test]
fn delete_label_refuses_dash_prefixed_remote_name_before_shelling_out() {
  // Companion to the declared-side `validate_label_name` guard. The
  // symmetric vector is the prune path: `gh label delete <name>`
  // takes the name positionally, so a remote label whose name starts
  // with `-` (planted by an attacker who controls the upstream label
  // set, or by a tool that predates the validator) would be parsed
  // as a flag — `-h` no-ops the delete with a help banner. The
  // validator runs BEFORE the shell-out so `delete_label` refuses
  // cleanly without ever invoking gh — meaning the test can rely on
  // the early return without needing `gh` on PATH.
  let err = github::delete_label("owner/repo", "-h").unwrap_err();
  let msg = format!("{}", err);
  assert!(
    msg.contains("labels (remote)"),
    "error must scope itself to the remote prune path; got: {}",
    msg
  );
  assert!(
    msg.contains("\"-h\"") || msg.contains("-h"),
    "error must name the offending label; got: {}",
    msg
  );
}

// --- PR auto-detection (issue #181) --------------------------------------

#[test]
fn apply_detected_pr_sets_pr_with_detected_source_when_none_linked() {
  // Branch carries an issue from its name but no PR link. Feeding a
  // detected PR number stamps it with the `Detected` provenance.
  let mut link = BranchLink {
    issue: Some(42),
    pr: None,
    issue_title: None,
    pr_title: None,
    issue_state: None,
    pr_state: None,
    issue_source: LinkSource::BranchName,
    pr_source: LinkSource::None,
  };

  github::apply_detected_pr(&mut link, Some(128));

  assert_eq!(link.pr, Some(128));
  assert_eq!(link.pr_source, LinkSource::Detected);
  // The issue side is left untouched.
  assert_eq!(link.issue, Some(42));
  assert_eq!(link.issue_source, LinkSource::BranchName);
}

#[test]
fn apply_detected_pr_leaves_explicit_pr_untouched() {
  // An explicit `gwm link --pr` always wins: detection must not clobber it.
  let mut link = BranchLink {
    issue: None,
    pr: Some(61),
    issue_title: None,
    pr_title: None,
    issue_state: None,
    pr_state: None,
    issue_source: LinkSource::None,
    pr_source: LinkSource::Explicit,
  };

  github::apply_detected_pr(&mut link, Some(128));

  assert_eq!(link.pr, Some(61));
  assert_eq!(link.pr_source, LinkSource::Explicit);
}

#[test]
fn apply_detected_pr_is_noop_when_nothing_detected() {
  let mut link = BranchLink::empty();

  github::apply_detected_pr(&mut link, None);

  assert_eq!(link.pr, None);
  assert_eq!(link.pr_source, LinkSource::None);
}

#[test]
fn detected_pr_renders_in_summary_like_any_pr() {
  let mut link = BranchLink::empty();
  github::apply_detected_pr(&mut link, Some(128));
  assert_eq!(link.summary(), "PR #128");
}

#[test]
fn find_pr_argv_pins_the_gh_pr_list_contract() {
  let argv = github::find_pr_argv("kbrdn1/gwm-cli", "feat/#181-auto-detect-pr");
  assert_eq!(
    argv,
    vec![
      "pr",
      "list",
      "--repo",
      "kbrdn1/gwm-cli",
      "--head",
      "feat/#181-auto-detect-pr",
      "--state",
      "all",
      "--json",
      "number",
      "--limit",
      "1",
    ]
  );
}

#[test]
fn parse_pr_list_number_returns_first_pr() {
  assert_eq!(github::parse_pr_list_number(r#"[{"number":128}]"#).unwrap(), Some(128));
}

#[test]
fn parse_pr_list_number_returns_none_for_empty_array() {
  assert_eq!(github::parse_pr_list_number("[]").unwrap(), None);
}

#[test]
fn parse_pr_list_number_errors_on_malformed_json() {
  assert!(github::parse_pr_list_number("not json").is_err());
}

#[test]
fn parse_pr_head_json_extracts_author_head_and_base() {
  // Issue #308: `gwm review` keys off the PR head ref (slug), the author
  // login (path component), and the base ref (diff base).
  let json = r#"{
    "number": 312,
    "author": { "login": "alice" },
    "headRefName": "feat/spike-x",
    "baseRefName": "main"
  }"#;
  let head = parse_pr_head_json(json).unwrap();
  assert_eq!(head.number, 312);
  assert_eq!(head.author, "alice");
  assert_eq!(head.head_ref_name, "feat/spike-x");
  assert_eq!(head.base_ref_name, "main");
}

#[test]
fn parse_pr_head_json_tolerates_a_null_author() {
  // A deleted GitHub account surfaces as `"author": null`; the default
  // keeps parsing from blowing up (the slug/branch fall back to empty).
  let json = r#"{ "number": 7, "author": null, "headRefName": "x", "baseRefName": "dev" }"#;
  let head = parse_pr_head_json(json).unwrap();
  assert_eq!(head.author, "");
  assert_eq!(head.base_ref_name, "dev");
}

#[test]
fn gh_command_line_uses_the_program_basename_and_joins_args() {
  use std::ffi::{OsStr, OsString};
  // Issue #226: the Command Logs transcript shows the resolved `gh <args…>`
  // (the user's chosen lazygit-style argv). A `GWM_GH` override pointing at
  // a full path must still read as `gh …`, not leak the path.
  let args: Vec<OsString> = ["issue", "view", "226", "--json", "title,body"]
    .iter()
    .map(OsString::from)
    .collect();
  assert_eq!(
    github::gh_command_line(OsStr::new("/opt/homebrew/bin/gh"), &args),
    "gh issue view 226 --json title,body"
  );
  // A bare program name is preserved as-is.
  assert_eq!(
    github::gh_command_line(OsStr::new("gh"), &args),
    "gh issue view 226 --json title,body"
  );
}