gwm-cli 1.6.1

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
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
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
//! Issue ↔ PR ↔ branch link storage, and the **GitHub backend** for the
//! [`crate::forge::Forge`] trait (via the `gh` CLI).
//!
//! Storage lives in git branch config: `branch.<name>.gwm-issue` and
//! `branch.<name>.gwm-pr`. Issue numbers are auto-detected from the
//! `<type>/#<N>-<slug>` branch convention when no explicit override is set.
//! Those `branch.<x>.gwm-*` keys are **forge-neutral** and deliberately stay
//! shared rather than moving behind the trait (issue #419): a GitLab worktree
//! reads and writes exactly the same keys.
//!
//! Fetch shells out to `gh` and parses its JSON output. The parsing functions
//! (`parse_issue_json`, `parse_pr_json`) are exposed publicly so tests can
//! cover the JSON contract without depending on a real `gh` binary.

use crate::error::{GwmError, Result};
use crate::forge::{self, Forge, ForgeKind};
use crate::labels::{LabelSpec, RemoteLabel};
use crate::milestones::{MilestoneSpec, MilestoneState, RemoteMilestone};
use crate::naming::BranchParser;
use git2::Repository;
use serde::Deserialize;
use std::ffi::{OsStr, OsString};
use std::sync::LazyLock;

// The parsed shapes are forge-agnostic and now live in `forge`; re-exported
// here so the many `github::PrStatus` / `github::CiState` imports across the
// TUI and CLI keep resolving unchanged.
pub use crate::forge::{cli_command_line as gh_command_line, repo_slug};
pub use crate::forge::{
  CheckOutcome, CiState, CreatedIssue, CreatedPr, IssueCreateRequest, IssueState, IssueStatus, PrCheck,
  PrCreateRequest, PrHead, PrState, PrStatus,
};

static ISSUE_URL_RE: LazyLock<regex::Regex> =
  LazyLock::new(|| regex::Regex::new(r"/issues/(\d+)(?:\b|$)").expect("static issue URL regex compiles"));
static PR_URL_RE: LazyLock<regex::Regex> =
  LazyLock::new(|| regex::Regex::new(r"/pull/(\d+)(?:\b|$)").expect("static PR URL regex compiles"));

const ISSUE_CONFIG_KEY: &str = "gwm-issue";
const PR_CONFIG_KEY: &str = "gwm-pr";
/// Persisted home of an auto-detected PR (issue #283). Kept distinct from
/// the explicit [`PR_CONFIG_KEY`] so [`read_link`] can resolve it as
/// [`LinkSource::Detected`] (not `Explicit`) — the pane needs that
/// distinction for its `detected` badge, and the explicit override must
/// still win.
const DETECTED_PR_CONFIG_KEY: &str = "gwm-pr-detected";
/// The forge instance a persisted link belongs to, as `<host>/<path>`
/// taken from `origin` at write time (Codex review #458).
///
/// The link keys themselves are deliberately forge-neutral — that was
/// the point of keeping them out of the [`crate::forge::Forge`] trait in
/// issue #419 — but the *numbers* they hold are not. PR #128 on
/// github.com and MR !128 on gitlab.com are unrelated objects, so once
/// the forge became switchable a stored number could be reinterpreted
/// against a different instance and silently link the worktree to a
/// stranger's merge request. Stamping the origin lets [`read_link`]
/// recognise a number that came from somewhere else and ignore it.
const LINK_ORIGIN_CONFIG_KEY: &str = "gwm-link-origin";
/// The backend half of the same guard. Per branch, like every other key
/// here: `.gwm.toml` is a versioned file, so two worktrees of one repo
/// legitimately resolve different backends, and a repo-level record made
/// each of them wipe the other's links. See [`reconcile_link_forge`].
const LINK_FORGE_CONFIG_KEY: &str = "gwm-link-forge";
/// What an absent [`LINK_FORGE_CONFIG_KEY`] means. Not "whatever is
/// resolving now" — pre-#419 gwm rejected every origin that was not
/// `github.com`, so nothing else can have written those numbers.
const LINK_FORGE_BEFORE_THE_KEY: &str = "github";
const ISSUE_TITLE_CONFIG_KEY: &str = "gwm-issue-title";
const PR_TITLE_CONFIG_KEY: &str = "gwm-pr-title";
const DETECTED_PR_TITLE_CONFIG_KEY: &str = "gwm-pr-detected-title";
const ISSUE_STATE_CONFIG_KEY: &str = "gwm-issue-state";
const PR_STATE_CONFIG_KEY: &str = "gwm-pr-state";
const DETECTED_PR_STATE_CONFIG_KEY: &str = "gwm-pr-detected-state";
/// Manual agent-session pin (issue #408 US4): the session id the user
/// attached to this branch's worktree with `gwm agents attach`. One pin per
/// worktree; auto-detection stays the default and the pin only adds.
const AGENT_PIN_CONFIG_KEY: &str = "gwm-agent-pin";

/// Where the issue or PR number came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinkSource {
  /// No link known (no branch-name match and no explicit override).
  None,
  /// Inferred from a branch following `<type>/#<N>-<slug>`.
  BranchName,
  /// Explicit override set via `gwm link …` (lives in git branch config).
  Explicit,
  /// Auto-detected from GitHub: a PR whose head ref is this branch was
  /// found via `gh pr list --head <branch>` (issue #181). May be persisted
  /// to the `gwm-pr-detected` branch-config key (issue #283) so the
  /// no-fetch table read path surfaces it on every row; an explicit
  /// `gwm link --pr` still always wins on the next read.
  Detected,
}

/// Resolved link for one branch: which issue (if any), which PR (if any),
/// and where each number came from.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BranchLink {
  pub issue: Option<u64>,
  pub pr: Option<u64>,
  pub issue_title: Option<String>,
  pub pr_title: Option<String>,
  pub issue_state: Option<IssueState>,
  pub pr_state: Option<PrState>,
  pub issue_source: LinkSource,
  pub pr_source: LinkSource,
}

impl BranchLink {
  pub fn empty() -> Self {
    Self {
      issue: None,
      pr: None,
      issue_title: None,
      pr_title: None,
      issue_state: None,
      pr_state: None,
      issue_source: LinkSource::None,
      pr_source: LinkSource::None,
    }
  }

  /// One-line human-readable rendering for the CLI / TUI status bar.
  ///
  /// `pr_noun` comes from [`crate::forge::Forge::pr_noun`] — "PR" on
  /// GitHub, "MR" on GitLab (issue #419). Passed in rather than read from
  /// a global so `BranchLink` stays a plain data struct.
  pub fn summary(&self, pr_noun: &str) -> String {
    match (self.issue, self.pr) {
      (None, None) => "no link".into(),
      (Some(i), None) => format!("issue #{i}"),
      (None, Some(p)) => format!("{pr_noun} #{p}"),
      (Some(i), Some(p)) => format!("issue #{i} · {pr_noun} #{p}"),
    }
  }
}

/// Read the link for `branch`. Explicit overrides win over branch-name auto-detect.
///
/// The branch-name half is read with a parser compiled from this repo's own
/// `worktree.branch_pattern` (issue #417), which is what keeps auto-linking
/// alive in a repo that customised it. Deriving the parser reads `.gwm.toml`
/// and compiles a regex, so anything looping over branches should hoist that
/// out and call [`read_link_with`] instead.
pub fn read_link(repo: &Repository, branch: &str) -> Result<BranchLink> {
  read_link_with(repo, branch, &BranchParser::for_repo(repo))
}

/// [`read_link`] with the branch parser supplied by the caller, for loops that
/// would otherwise re-read `.gwm.toml` once per branch.
pub fn read_link_with(repo: &Repository, branch: &str, parser: &BranchParser) -> Result<BranchLink> {
  // Numbers stamped against another instance are dropped before they are
  // resolved (Codex review #458). Only the *persisted* values go: the
  // issue parsed out of the branch name is the user's own naming and
  // stays valid wherever the repo now points.
  let foreign = match read_branch_string(repo, branch, LINK_ORIGIN_CONFIG_KEY)? {
    Some(stored) => link_origin_is_foreign(repo)(&stored),
    // No stamp means the link predates the key. Invalidating those would
    // wipe every existing link on upgrade, so they are adopted by the
    // origin the repo has right now — which is almost always the one
    // that wrote them, and makes a *later* move invalidate properly
    // instead of leaving them unscoped forever (Codex review #458).
    //
    // Adoption is a one-time write per branch, guarded on there being
    // something to adopt, so the per-row read path does not touch git
    // config on every listing. Best-effort: read-only repos keep working
    // and simply stay unstamped.
    None => {
      // Any persisted link value, not just the numbers: an issue derived
      // from the branch name stores no number at all, only a cached
      // title and state, and keying adoption on numbers left those
      // branches unstamped forever (Codex review #458).
      let mut has_link = false;
      for key in [
        ISSUE_CONFIG_KEY,
        PR_CONFIG_KEY,
        DETECTED_PR_CONFIG_KEY,
        ISSUE_TITLE_CONFIG_KEY,
        ISSUE_STATE_CONFIG_KEY,
        PR_TITLE_CONFIG_KEY,
        PR_STATE_CONFIG_KEY,
        DETECTED_PR_TITLE_CONFIG_KEY,
        DETECTED_PR_STATE_CONFIG_KEY,
      ] {
        if read_branch_string(repo, branch, key)?.is_some() {
          has_link = true;
          break;
        }
      }
      if has_link {
        if let Some(id) = origin_identity(repo) {
          let _ = write_branch_string(repo, branch, LINK_ORIGIN_CONFIG_KEY, &id);
        }
      }
      false
    }
  };
  let explicit_issue = if foreign {
    None
  } else {
    read_branch_u64(repo, branch, ISSUE_CONFIG_KEY)?
  };
  let explicit_pr = if foreign {
    None
  } else {
    read_branch_u64(repo, branch, PR_CONFIG_KEY)?
  };

  let (issue, issue_source) = match explicit_issue {
    Some(n) => (Some(n), LinkSource::Explicit),
    None => match parser.parse(branch).and_then(|s| s.issue.parse::<u64>().ok()) {
      Some(n) => (Some(n), LinkSource::BranchName),
      None => (None, LinkSource::None),
    },
  };

  // PR resolution order (issue #283): an explicit `gwm link --pr` wins,
  // then a persisted auto-detection (`gwm-pr-detected`), then nothing. The
  // persisted-detected branch is what lets the no-fetch table read path
  // colour the PR pastille on every row without a per-row `gh` shell-out.
  let (pr, pr_source) = match explicit_pr {
    Some(n) => (Some(n), LinkSource::Explicit),
    None if foreign => (None, LinkSource::None),
    None => match read_branch_u64(repo, branch, DETECTED_PR_CONFIG_KEY)? {
      Some(n) => (Some(n), LinkSource::Detected),
      None => (None, LinkSource::None),
    },
  };
  // The cached title and state are as instance-scoped as the numbers.
  // The issue survives a foreign stamp when the branch name carries it,
  // and reading the previous tenant's metadata onto that number showed
  // one instance's issue under the other's title until the next write
  // purged it — which offline or read-only never comes (Codex review
  // #458).
  let issue_title = match issue {
    Some(_) if !foreign => read_branch_string(repo, branch, ISSUE_TITLE_CONFIG_KEY)?,
    _ => None,
  };
  let issue_state = match issue {
    Some(_) if !foreign => read_branch_issue_state(repo, branch)?,
    _ => None,
  };
  let pr_title = match pr_source {
    LinkSource::Explicit => read_branch_string(repo, branch, PR_TITLE_CONFIG_KEY)?,
    LinkSource::Detected => read_branch_string(repo, branch, DETECTED_PR_TITLE_CONFIG_KEY)?,
    LinkSource::BranchName | LinkSource::None => None,
  };
  let pr_state = match pr_source {
    LinkSource::Explicit => read_branch_pr_state(repo, branch, PR_STATE_CONFIG_KEY)?,
    LinkSource::Detected => read_branch_pr_state(repo, branch, DETECTED_PR_STATE_CONFIG_KEY)?,
    LinkSource::BranchName | LinkSource::None => None,
  };

  Ok(BranchLink {
    issue,
    pr,
    issue_title,
    pr_title,
    issue_state,
    pr_state,
    issue_source,
    pr_source,
  })
}

/// Stamp an auto-detected PR number onto `link` when no PR is already
/// linked. Pure helper (issue #181): the caller supplies the detection
/// result — typically `find_pr_for_branch(slug, branch).ok().flatten()` —
/// and this decides whether to apply it.
///
/// An explicit (or previously-detected) PR always wins: when `link.pr`
/// is already `Some`, this is a no-op so a `gwm link --pr` override is
/// never clobbered. The applied number is marked [`LinkSource::Detected`].
/// This function only mutates the in-memory [`BranchLink`]; call
/// [`persist_detected_pr`] separately to write it to the git config so the
/// table read path (issue #283) picks it up.
pub fn apply_detected_pr(link: &mut BranchLink, detected: Option<u64>) {
  if link.pr.is_none() {
    if let Some(n) = detected {
      link.pr = Some(n);
      link.pr_source = LinkSource::Detected;
      link.pr_title = None;
      link.pr_state = None;
    }
  }
}

/// Resolve the link for `branch` and, unless a PR is *explicitly* linked,
/// auto-detect the branch's PR from GitHub via `gh` (issue #181). The
/// detected PR is marked [`LinkSource::Detected`].
///
/// A persisted auto-detection (`gwm-pr-detected`, issue #283) does NOT pin
/// the result here: this is the live-detection path (`gwm status` /
/// `gwm list --detect-pr`), so it re-runs `gh pr list` to reflect a PR that
/// was opened / closed / replaced since the last detection, rather than
/// echoing a stale stored number (Codex review #284). Only an explicit
/// `gwm link --pr` short-circuits the probe.
///
/// On a successful probe this also **reconciles the persisted cache**
/// (`gwm-pr-detected`): it rewrites the stored number to the fresh result,
/// or clears it when the PR vanished, so the no-fetch consumers (`read_link`,
/// the TUI table at startup, `gwm open pr`) don't resurrect a stale number
/// after this path saw it change (Codex review #284). The cache write is
/// best-effort — a read-only repo must not turn `gwm status` into an error.
///
/// Detection is best-effort: a `gh` failure (not installed, no network)
/// leaves the link untouched — a persisted detection survives the failed
/// probe rather than being wiped — and the local link is still returned.
/// This shells out, so callers on hot paths (per-worktree listing) must opt
/// in deliberately rather than route every read through here.
pub fn read_link_with_pr_detection(repo: &Repository, branch: &str, forge: &dyn Forge) -> Result<BranchLink> {
  let mut link = read_link(repo, branch)?;
  if link.pr_source != LinkSource::Explicit {
    // Re-resolve live. On success, the fresh result replaces any persisted
    // detection (a vanished PR clears it); on a CLI failure, keep whatever
    // `read_link` already resolved (possibly a persisted detection).
    if let Ok(detected) = forge.find_pr_for_branch(branch) {
      let previous_pr = link.pr;
      let previous_pr_source = link.pr_source;
      let previous_pr_title = link.pr_title.clone();
      let previous_pr_state = link.pr_state;
      link.pr = detected;
      link.pr_source = match detected {
        Some(_) => LinkSource::Detected,
        None => LinkSource::None,
      };
      link.pr_title = if previous_pr_source == LinkSource::Detected && detected == previous_pr {
        previous_pr_title
      } else {
        None
      };
      link.pr_state = if previous_pr_source == LinkSource::Detected && detected == previous_pr {
        previous_pr_state
      } else {
        None
      };
      // Reconcile the persisted cache (issue #283 / Codex review #284) so the
      // no-fetch consumers (`read_link`, the TUI table at startup,
      // `gwm open pr`) don't resurrect a stale number after this live path
      // saw it change or vanish. Best-effort: a read-only repo must not turn
      // `gwm status` into an error, so a write failure is discarded.
      let _ = match detected {
        Some(n) => persist_detected_pr(repo, branch, n),
        None => clear_persisted_detected_pr(repo, branch),
      };
    }
  }
  Ok(link)
}

/// `<web origin>/<path>` of the repo's `origin`, or `None` when there is
/// no origin or it does not parse. A local-only repo therefore stamps
/// nothing and is never invalidated — there is no second instance for
/// its numbers to be confused with.
///
/// Covers a change of *instance*, not a change of *backend*: flipping
/// `forge = "gitlab"` in `.gwm.toml` over an unchanged remote leaves
/// this identity untouched, so existing numbers are reinterpreted by
/// the other backend (Codex review #458). Catching it means threading
/// the resolved forge through `link_issue` / `link_pr` /
/// `persist_detected_pr` and into `read_link`, which has no `Config` —
/// deferred as churn out of proportion to a case that needs the backend
/// switched on a remote that did not move.
///
/// The web origin rather than the bare host, because it carries the
/// scheme and the port: two self-hosted instances on one hostname behind
/// different ports are different instances, and `host/path` collapsed
/// them into one stamp (Codex review #458). It also keeps `ssh://` and
/// `https://` spellings of the same repo on the same stamp, so switching
/// remote protocol does not throw the links away.
fn origin_identity(repo: &Repository) -> Option<String> {
  let remote = repo.find_remote("origin").ok()?;
  let parsed = forge::parse_remote_url(remote.url().ok()?).ok()?;
  Some(format!("{}/{}", parsed.web_origin, parsed.path))
}

/// Stamp the current origin on the branch's links, dropping anything the
/// previous origin left behind.
///
/// The eager purge is what makes the stamp trustworthy. One stamp covers
/// the issue, the explicit PR and the detected PR, so writing just one of
/// them after a move would rewrite the stamp and silently re-bless the
/// other two — and the lazy check in [`read_link`] would never fire
/// again, because the stamp now matches (Codex review #458).
///
/// Best-effort throughout: a read-only repo must not turn a successful
/// `gwm pr` into an error.
fn stamp_link_origin(repo: &Repository, branch: &str) {
  let Some(id) = origin_identity(repo) else { return };
  if let Ok(Some(stored)) = read_branch_string(repo, branch, LINK_ORIGIN_CONFIG_KEY) {
    if stored != id && drop_branch_links(repo, branch).is_err() {
      // Same rule as `reconcile_link_forge`: no purge, no new stamp.
      return;
    }
  }
  let _ = write_branch_string(repo, branch, LINK_ORIGIN_CONFIG_KEY, &id);
}

/// Every number, title and state the link layer persists for `branch`.
/// One list, because a purge that forgets a key silently re-blesses it.
fn drop_branch_links(repo: &Repository, branch: &str) -> Result<()> {
  for key in [
    ISSUE_CONFIG_KEY,
    ISSUE_TITLE_CONFIG_KEY,
    ISSUE_STATE_CONFIG_KEY,
    PR_CONFIG_KEY,
    PR_TITLE_CONFIG_KEY,
    PR_STATE_CONFIG_KEY,
    DETECTED_PR_CONFIG_KEY,
    DETECTED_PR_TITLE_CONFIG_KEY,
    DETECTED_PR_STATE_CONFIG_KEY,
  ] {
    remove_branch_key(repo, branch, key)?;
  }
  Ok(())
}

/// Drop every persisted link when the repo changes **backend**.
///
/// [`origin_identity`] covers a change of instance and cannot cover this
/// one: flipping `forge = "gitlab"` in `.gwm.toml` leaves the remote,
/// and therefore `<web origin>/<path>`, exactly as it was. The numbers
/// survive and the other backend reads them as its own — issue #42
/// resurfaces as merge request !42, a real page and the wrong one
/// (Codex review #458).
///
/// Called from [`crate::forge::resolve`] rather than from the readers.
/// The busiest reader is [`crate::worktree::list`], which has no
/// `Config` and is threaded through most of the test suite; `resolve` is
/// the single place that decides a repo's backend and already holds
/// both halves. The cost in the steady state is one config read.
///
/// An absent record **adopts**: links written before this key existed
/// must survive the upgrade that introduces it, exactly as an absent
/// origin stamp is not treated as a mismatch.
///
/// # Two invariants, and where every caller sits against them
///
/// **Atomicity — the marker only advances when the purge fully
/// succeeded.** Advancing it after a failed removal re-blesses the old
/// numbers *permanently*: the mismatch never fires again and the other
/// backend reads them as its own. Same rule [`stamp_link_origin`]
/// states for the origin stamp. The removals and the marker write share
/// one config lock, so they fail together anyway — the guard is what
/// makes that a property of the code rather than a coincidence.
///
/// **Scope — one branch, the one at HEAD.** The marker started
/// repo-level, on the reasoning that a backend is a property of a repo.
/// It is not: `.gwm.toml` is versioned, so two worktrees of one repo
/// legitimately carry different `forge` values, and the purge swept
/// *every* local branch — running gwm in each in turn wiped the other's
/// links, both ways, forever (Codex review #458). Repo-wide data loss
/// out of a per-worktree setting. Per-branch is also the scope every
/// other key here already uses.
///
/// The cost of that scoping, named: `gwm open --worktree <other>`
/// reconciles the branch at HEAD rather than the target's, so the
/// target keeps a stale number for that one command. Same class as the
/// `worktree::list` gap below — a stale read, never a wrong write.
///
/// **Ordering — every link read or write happens *after* a reconcile,
/// never before.** Read too early and the stale number is served one
/// more time; write too early and the write lands under the outgoing
/// marker, so the next reconcile deletes what the user just did. Both
/// happened (Codex review #458), which is why the whole surface is
/// enumerated here rather than fixed one call site per round:
///
/// | site | reconciles | why |
/// |---|---|---|
/// | `cli::cmd_open` | resolves, then reads | fixed: it resolved after `read_link` |
/// | `cli::cmd_status` | resolves, then reads | already correct |
/// | `cli::cmd_link` | [`crate::forge::reconcile_links`] | fixed: it never resolved |
/// | `cli::cmd_unlink` | no | removes keys; a later purge takes no more than it would |
/// | `cli::cmd_pr` | `resolve_or_default` before `link_pr` | already correct |
/// | `cli::cmd_review` | `resolve` before `review::materialize` | already correct |
/// | `tui::GitHubFetch::reread_link` | resolves, then reads | fixed: it read first |
/// | `tui::App` link prompt | via `reread_link` on selection | already correct |
/// | [`crate::worktree::list`] | **no** | no `Config`; display only, and it self-heals on the next resolve |
///
/// `worktree::list` is the one deliberate gap: it is a pure reader with
/// no `Config`, so a flip leaves its badges stale until any command or
/// TUI selection resolves. Nothing is written from there, so a stale
/// badge is the whole of the damage.
///
/// Best-effort throughout — a read-only repo must not turn a resolve
/// into an error.
pub(crate) fn reconcile_link_forge(repo: &Repository, kind: crate::forge::ForgeKind) {
  let now = kind.as_str();
  let Ok(head) = repo.head() else { return };
  let Some(branch) = pinnable_branch(head.shorthand().ok()).map(str::to_string) else {
    return;
  };
  // An absent record is not "adopt whatever is resolving now": pre-#419
  // gwm rejected every origin that was not `github.com`, so any number
  // already on the branch is a GitHub number. Reading absent as
  // adoption re-blessed all of them as GitLab iids on the first resolve
  // after an upgrade (Codex review #458).
  let stored = read_branch_string(repo, &branch, LINK_FORGE_CONFIG_KEY)
    .ok()
    .flatten()
    .unwrap_or_else(|| LINK_FORGE_BEFORE_THE_KEY.to_string());
  if stored == now {
    return;
  }
  if drop_branch_links(repo, &branch).is_err() || remove_branch_key(repo, &branch, LINK_ORIGIN_CONFIG_KEY).is_err() {
    return;
  }
  let _ = write_branch_string(repo, &branch, LINK_FORGE_CONFIG_KEY, now);
}

/// `true` when persisted numbers on this branch were written against a
/// different origin than the repo has now.
///
/// An absent stamp is **not** a mismatch: links written before this key
/// existed, and links in local-only repos, stay readable.
fn link_origin_is_foreign(repo: &Repository) -> impl Fn(&str) -> bool + '_ {
  let current = origin_identity(repo);
  move |stored: &str| match &current {
    Some(now) => stored != now,
    None => false,
  }
}

pub fn link_issue(repo: &Repository, branch: &str, number: u64) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_u64(repo, branch, ISSUE_CONFIG_KEY, number)?;
  remove_branch_key(repo, branch, ISSUE_TITLE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, ISSUE_STATE_CONFIG_KEY)
}

pub fn link_pr(repo: &Repository, branch: &str, number: u64) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_u64(repo, branch, PR_CONFIG_KEY, number)?;
  remove_branch_key(repo, branch, PR_TITLE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, PR_STATE_CONFIG_KEY)
}

pub fn unlink_issue(repo: &Repository, branch: &str) -> Result<()> {
  remove_branch_key(repo, branch, ISSUE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, ISSUE_TITLE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, ISSUE_STATE_CONFIG_KEY)
}

pub fn unlink_pr(repo: &Repository, branch: &str) -> Result<()> {
  // Drop both the explicit link and any persisted auto-detection (#283),
  // otherwise unlinking would leave a stale `gwm-pr-detected` number that
  // `read_link` would resurface as a `Detected` PR on the next read.
  remove_branch_key(repo, branch, PR_CONFIG_KEY)?;
  remove_branch_key(repo, branch, PR_TITLE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, PR_STATE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, DETECTED_PR_CONFIG_KEY)?;
  remove_branch_key(repo, branch, DETECTED_PR_TITLE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, DETECTED_PR_STATE_CONFIG_KEY)
}

/// Persist an auto-detected PR number to its own branch-config key
/// (`gwm-pr-detected`, issue #283), distinct from the explicit `gwm-pr`.
/// This lets the no-fetch table read path surface the detected PR on every
/// row without a per-row `gh` shell-out, while keeping the
/// detected/explicit distinction the pane badge needs. An explicit
/// `gwm link --pr` still wins in [`read_link`]. Re-detection overwrites the
/// stored value and clears a cached title only when the detected number
/// actually changed.
pub fn persist_detected_pr(repo: &Repository, branch: &str, number: u64) -> Result<()> {
  stamp_link_origin(repo, branch);
  let previous = read_branch_u64(repo, branch, DETECTED_PR_CONFIG_KEY)?;
  write_branch_u64(repo, branch, DETECTED_PR_CONFIG_KEY, number)?;
  if previous == Some(number) {
    Ok(())
  } else {
    remove_branch_key(repo, branch, DETECTED_PR_TITLE_CONFIG_KEY)?;
    remove_branch_key(repo, branch, DETECTED_PR_STATE_CONFIG_KEY)
  }
}

/// Drop a persisted auto-detection (issue #283). A no-op when no detected
/// PR was stored. Used when a detection no longer holds (the branch's PR
/// went away) so a stale number doesn't linger in the config.
pub fn clear_persisted_detected_pr(repo: &Repository, branch: &str) -> Result<()> {
  remove_branch_key(repo, branch, DETECTED_PR_CONFIG_KEY)?;
  remove_branch_key(repo, branch, DETECTED_PR_TITLE_CONFIG_KEY)?;
  remove_branch_key(repo, branch, DETECTED_PR_STATE_CONFIG_KEY)
}

// Every one of these stamps first. They persist metadata fetched from
// the origin the repo has *now*, and `read_link` suppresses anything the
// stamp says came from somewhere else — so writing without stamping left
// a fresh title permanently suppressed. It only shows on the path where
// the number comes from the branch name rather than from config, because
// nothing else re-links it and no other writer restamps (Codex review
// #458). `persist_detected_pr` stamped from the start; these did not.

pub fn persist_issue_title(repo: &Repository, branch: &str, title: &str) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_string(repo, branch, ISSUE_TITLE_CONFIG_KEY, title)
}

pub fn persist_pr_title(repo: &Repository, branch: &str, title: &str) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_string(repo, branch, PR_TITLE_CONFIG_KEY, title)
}

pub fn persist_detected_pr_title(repo: &Repository, branch: &str, title: &str) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_string(repo, branch, DETECTED_PR_TITLE_CONFIG_KEY, title)
}

pub fn persist_issue_state(repo: &Repository, branch: &str, state: IssueState) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_string(repo, branch, ISSUE_STATE_CONFIG_KEY, issue_state_config_value(state))
}

pub fn persist_pr_state(repo: &Repository, branch: &str, state: PrState) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_string(repo, branch, PR_STATE_CONFIG_KEY, pr_state_config_value(state))
}

pub fn persist_detected_pr_state(repo: &Repository, branch: &str, state: PrState) -> Result<()> {
  stamp_link_origin(repo, branch);
  write_branch_string(repo, branch, DETECTED_PR_STATE_CONFIG_KEY, pr_state_config_value(state))
}

fn config_key(branch: &str, leaf: &str) -> String {
  format!("branch.{}.{}", branch, leaf)
}

fn read_branch_u64(repo: &Repository, branch: &str, leaf: &str) -> Result<Option<u64>> {
  let cfg = repo.config()?;
  let key = config_key(branch, leaf);
  match cfg.get_string(&key) {
    Ok(s) => s
      .trim()
      .parse::<u64>()
      .map(Some)
      .map_err(|_| GwmError::Other(format!("config '{}' is not a valid number: {}", key, s))),
    Err(e) if e.code() == git2::ErrorCode::NotFound => Ok(None),
    Err(e) => Err(GwmError::Git(e)),
  }
}

fn read_branch_string(repo: &Repository, branch: &str, leaf: &str) -> Result<Option<String>> {
  let cfg = repo.config()?;
  let key = config_key(branch, leaf);
  match cfg.get_string(&key) {
    Ok(s) => Ok(Some(s)),
    Err(e) if e.code() == git2::ErrorCode::NotFound => Ok(None),
    Err(e) => Err(GwmError::Git(e)),
  }
}

fn read_branch_issue_state(repo: &Repository, branch: &str) -> Result<Option<IssueState>> {
  Ok(
    read_branch_string(repo, branch, ISSUE_STATE_CONFIG_KEY)?
      .as_deref()
      .and_then(parse_issue_state_config_value),
  )
}

fn read_branch_pr_state(repo: &Repository, branch: &str, leaf: &str) -> Result<Option<PrState>> {
  Ok(
    read_branch_string(repo, branch, leaf)?
      .as_deref()
      .and_then(parse_pr_state_config_value),
  )
}

fn parse_issue_state_config_value(value: &str) -> Option<IssueState> {
  match value.trim().to_ascii_lowercase().as_str() {
    "open" => Some(IssueState::Open),
    "closed" => Some(IssueState::Closed),
    _ => None,
  }
}

fn parse_pr_state_config_value(value: &str) -> Option<PrState> {
  match value.trim().to_ascii_lowercase().as_str() {
    "open" => Some(PrState::Open),
    "draft" => Some(PrState::Draft),
    "closed" => Some(PrState::Closed),
    "merged" => Some(PrState::Merged),
    _ => None,
  }
}

fn issue_state_config_value(state: IssueState) -> &'static str {
  match state {
    IssueState::Open => "open",
    IssueState::Closed => "closed",
  }
}

fn pr_state_config_value(state: PrState) -> &'static str {
  match state {
    PrState::Open => "open",
    PrState::Draft => "draft",
    PrState::Closed => "closed",
    PrState::Merged => "merged",
  }
}

fn write_branch_u64(repo: &Repository, branch: &str, leaf: &str, value: u64) -> Result<()> {
  let mut cfg = repo.config()?;
  cfg.set_str(&config_key(branch, leaf), &value.to_string())?;
  Ok(())
}

fn write_branch_string(repo: &Repository, branch: &str, leaf: &str, value: &str) -> Result<()> {
  let mut cfg = repo.config()?;
  cfg.set_str(&config_key(branch, leaf), value)?;
  Ok(())
}

/// Normalise a worktree's branch for pin storage (issue #408): libgit2
/// surfaces a detached HEAD either as `None` or as the literal `"HEAD"`
/// (the same trap the statusline handles), and a `branch.HEAD.*` config key
/// would silently share one pin across every detached worktree. Every pin
/// read/write goes through this guard.
pub fn pinnable_branch(branch: Option<&str>) -> Option<&str> {
  match branch {
    None | Some("HEAD") => None,
    other => other,
  }
}

/// Every manual agent-session pin on `branch` (issue #408 US4). The key is
/// **multi-valued** (user feedback 2026-07-22): several agents can work one
/// worktree at once, so attach accumulates instead of replacing.
pub fn agent_pins(repo: &Repository, branch: &str) -> Result<Vec<String>> {
  let cfg = repo.config()?;
  let key = config_key(branch, AGENT_PIN_CONFIG_KEY);
  let mut out = Vec::new();
  let result = match cfg.multivar(&key, None) {
    Ok(entries) => {
      entries
        .for_each(|e| {
          if let Ok(v) = e.value() {
            out.push(v.to_string());
          }
        })
        .map_err(GwmError::Git)?;
      Ok(out)
    }
    Err(e) if e.code() == git2::ErrorCode::NotFound => Ok(out),
    Err(e) => Err(GwmError::Git(e)),
  };
  result
}

/// Pin `session_id` to `branch`'s worktree (`gwm agents attach`). Appends
/// to the multi-valued key; re-attaching an already-pinned id is a no-op.
pub fn add_agent_pin(repo: &Repository, branch: &str, session_id: &str) -> Result<()> {
  if agent_pins(repo, branch)?.iter().any(|p| p == session_id) {
    return Ok(());
  }
  let mut cfg = repo.config()?;
  // The never-matching regex makes libgit2 append a new value instead of
  // replacing an existing one (the documented multivar-append idiom).
  cfg.set_multivar(&config_key(branch, AGENT_PIN_CONFIG_KEY), "^$", session_id)?;
  Ok(())
}

/// Remove exactly the `session_id` pin (`gwm agents detach <wt> <id>` / `d`
/// on a pinned row). Returns whether it was present; absent is not an error.
pub fn remove_agent_pin(repo: &Repository, branch: &str, session_id: &str) -> Result<bool> {
  if !agent_pins(repo, branch)?.iter().any(|p| p == session_id) {
    return Ok(false);
  }
  let mut cfg = repo.config()?;
  // Escape regex metacharacters so an id is matched literally, anchored.
  let escaped: String = session_id
    .chars()
    .flat_map(|c| {
      if c.is_ascii_alphanumeric() {
        vec![c]
      } else {
        vec!['\\', c]
      }
    })
    .collect();
  cfg.remove_multivar(&config_key(branch, AGENT_PIN_CONFIG_KEY), &format!("^{escaped}$"))?;
  Ok(true)
}

/// Remove every pin on `branch` (bare `gwm agents detach <wt>`). A no-op
/// when none is set.
pub fn clear_agent_pins(repo: &Repository, branch: &str) -> Result<()> {
  let mut cfg = repo.config()?;
  match cfg.remove_multivar(&config_key(branch, AGENT_PIN_CONFIG_KEY), ".*") {
    Ok(()) => Ok(()),
    Err(e) if e.code() == git2::ErrorCode::NotFound => Ok(()),
    Err(e) => Err(GwmError::Git(e)),
  }
}

fn remove_branch_key(repo: &Repository, branch: &str, leaf: &str) -> Result<()> {
  let mut cfg = repo.config()?;
  let key = config_key(branch, leaf);
  match cfg.remove(&key) {
    Ok(_) => Ok(()),
    Err(e) if e.code() == git2::ErrorCode::NotFound => Ok(()),
    Err(e) => Err(GwmError::Git(e)),
  }
}

// ---- Issue / PR status ---------------------------------------------------

#[derive(Deserialize)]
struct RawIssue {
  number: u64,
  title: String,
  state: String,
  url: String,
  #[serde(default)]
  labels: Vec<RawLabel>,
  #[serde(rename = "updatedAt", default)]
  updated_at: String,
}

#[derive(Deserialize)]
struct RawLabel {
  name: String,
}

#[derive(Deserialize)]
struct RawPr {
  number: u64,
  title: String,
  state: String,
  #[serde(rename = "isDraft", default)]
  is_draft: bool,
  url: String,
  #[serde(rename = "updatedAt", default)]
  updated_at: String,
  #[serde(rename = "statusCheckRollup", default)]
  status_check_rollup: Vec<RawCheck>,
}

/// One `statusCheckRollup` entry. GitHub returns two shapes here: a
/// `CheckRun` (the Checks API — carries `status` + `conclusion`) and a
/// legacy `StatusContext` (the commit-status API — carries `state`). We
/// deserialize all three so both shapes classify correctly.
#[derive(Deserialize)]
struct RawCheck {
  #[serde(default)]
  status: String,
  #[serde(default)]
  conclusion: Option<String>,
  #[serde(default)]
  state: String,
  // Per-check identity + link, kept for the CI checks overlay (issue #436).
  // `name` + `detailsUrl` on the `CheckRun` shape; `context` + `targetUrl`
  // on the legacy `StatusContext` shape.
  #[serde(default)]
  name: String,
  #[serde(rename = "detailsUrl", default)]
  details_url: Option<String>,
  #[serde(default)]
  context: String,
  #[serde(rename = "targetUrl", default)]
  target_url: Option<String>,
  // Run metadata (CheckRun shape), kept for the overlay's detail column.
  #[serde(rename = "workflowName", default)]
  workflow_name: Option<String>,
  #[serde(rename = "startedAt", default)]
  started_at: Option<String>,
  #[serde(rename = "completedAt", default)]
  completed_at: Option<String>,
}

pub fn parse_issue_json(s: &str) -> Result<IssueStatus> {
  let raw: RawIssue = serde_json::from_str(s).map_err(|e| GwmError::GhJsonParse {
    kind: "issue",
    source: e,
  })?;
  let state = match raw.state.as_str() {
    "OPEN" | "open" => IssueState::Open,
    "CLOSED" | "closed" => IssueState::Closed,
    other => return Err(GwmError::Other(format!("unknown issue state '{}'", other))),
  };
  Ok(IssueStatus {
    number: raw.number,
    title: raw.title,
    state,
    url: raw.url,
    labels: raw.labels.into_iter().map(|l| l.name).collect(),
    updated_at: raw.updated_at,
  })
}

pub fn parse_pr_json(s: &str) -> Result<PrStatus> {
  let raw: RawPr = serde_json::from_str(s).map_err(|e| GwmError::GhJsonParse { kind: "pr", source: e })?;
  let state = match (raw.state.as_str(), raw.is_draft) {
    ("MERGED" | "merged", _) => PrState::Merged,
    ("CLOSED" | "closed", _) => PrState::Closed,
    ("OPEN" | "open", true) => PrState::Draft,
    ("OPEN" | "open", false) => PrState::Open,
    (other, _) => return Err(GwmError::Other(format!("unknown PR state '{}'", other))),
  };
  let checks_total = raw.status_check_rollup.len() as u32;
  // Count the same "accepted" terminals the CI state treats as green, so the
  // `N/M` shown next to the indicator stays consistent with its label — a
  // rollup of SUCCESS + NEUTRAL + SKIPPED reads "passing 3/3", not "1/3"
  // (Codex review #302).
  let checks_passed = raw
    .status_check_rollup
    .iter()
    .filter(|c| matches!(classify_check(c), CheckOutcome::Passing))
    .count() as u32;
  let ci = derive_ci_state(&raw.status_check_rollup);
  let checks = raw
    .status_check_rollup
    .iter()
    .map(|c| PrCheck {
      name: if c.name.is_empty() {
        c.context.clone()
      } else {
        c.name.clone()
      },
      outcome: classify_check(c),
      url: c.details_url.clone().or_else(|| c.target_url.clone()),
      workflow_name: c.workflow_name.clone(),
      started_at: c.started_at.clone(),
      completed_at: c.completed_at.clone(),
    })
    .collect();
  Ok(PrStatus {
    number: raw.number,
    title: raw.title,
    state,
    url: raw.url,
    updated_at: raw.updated_at,
    checks_passed,
    checks_total,
    ci,
    checks,
  })
}

/// Classify one rollup entry, handling both the `CheckRun` shape
/// (`status` + `conclusion`) and the legacy `StatusContext` shape
/// (`state`). A `CheckRun` is only green for an *accepted* terminal
/// conclusion (SUCCESS / NEUTRAL / SKIPPED, or a completed check with no
/// conclusion); every other terminal conclusion — FAILURE, CANCELLED,
/// TIMED_OUT, ACTION_REQUIRED, STARTUP_FAILURE, STALE, … — reads as failing
/// rather than silently falling through to green (Codex review #302).
fn classify_check(c: &RawCheck) -> CheckOutcome {
  // `CheckRun`: `status` is populated (QUEUED / IN_PROGRESS / COMPLETED).
  if !c.status.is_empty() {
    if !c.status.eq_ignore_ascii_case("COMPLETED") {
      return CheckOutcome::Running;
    }
    return match c.conclusion.as_deref() {
      Some(s) if is_accepted_conclusion(s) => CheckOutcome::Passing,
      // A completed check with no conclusion is treated leniently (green) so
      // missing data never paints a false red.
      None => CheckOutcome::Passing,
      Some(_) => CheckOutcome::Failing,
    };
  }
  // Legacy `StatusContext`: classify by `state`.
  match c.state.to_ascii_uppercase().as_str() {
    "SUCCESS" => CheckOutcome::Passing,
    "FAILURE" | "ERROR" => CheckOutcome::Failing,
    // PENDING / EXPECTED / unknown — not yet conclusive.
    _ => CheckOutcome::Running,
  }
}

/// Terminal `CheckRun` conclusions that count as green.
fn is_accepted_conclusion(conclusion: &str) -> bool {
  matches!(
    conclusion.to_ascii_uppercase().as_str(),
    "SUCCESS" | "NEUTRAL" | "SKIPPED"
  )
}

/// Collapse a `statusCheckRollup` into a single [`CiState`]. The
/// aggregation rule itself is shared with the GitLab backend since #419 —
/// see [`forge::aggregate_ci_state`].
fn derive_ci_state(checks: &[RawCheck]) -> CiState {
  forge::aggregate_ci_state(checks.iter().map(classify_check))
}

// ---- gh CLI invocation ---------------------------------------------------

const ISSUE_JSON_FIELDS: &str = "number,title,state,url,labels,updatedAt";
const PR_JSON_FIELDS: &str = "number,title,state,isDraft,url,updatedAt,statusCheckRollup";

/// Run `gh issue view <n> --repo <slug> --json …` and parse the result.
pub fn fetch_issue(slug: &str, number: u64) -> Result<IssueStatus> {
  fetch_issue_with(&gh_program(), slug, number)
}

/// [`fetch_issue`] with an explicitly resolved `gh` program path. Used by
/// the TUI's off-thread fetch (issue #217): the program is resolved on the
/// main thread via [`gh_program`] and handed to the worker thread, so the
/// thread never touches `GWM_GH` / the process environment concurrently
/// with env-mutating callers.
pub fn fetch_issue_with(program: &OsStr, slug: &str, number: u64) -> Result<IssueStatus> {
  parse_issue_json(&run_gh_with(program, issue_view_argv(slug, number))?)
}

/// `--repo <slug>`, or nothing when the slug is empty.
///
/// Mirrors [`crate::gitlab::repo_flag`]. An empty slug is the caller
/// asking `gh` to resolve the repository from the directory it is
/// spawned in, which is also where it infers the host from.
fn repo_flag(slug: &str) -> Vec<String> {
  if slug.is_empty() {
    Vec::new()
  } else {
    vec!["--repo".into(), slug.into()]
  }
}

/// `repos/<slug>` for a REST path, or `repos/{owner}/{repo}` when the
/// slug is empty.
///
/// `gh api` documents `{owner}`, `{repo}` and `{branch}` as placeholders
/// "replaced with values from the repository of the current directory".
/// This is the counterpart to glab's `projects/:fullpath`, and round 16
/// of the #458 review asserted — wrongly, from a stale code comment
/// rather than the docs — that no such thing existed.
fn repo_api_path(slug: &str) -> String {
  if slug.is_empty() {
    "repos/{owner}/{repo}".to_string()
  } else {
    format!("repos/{slug}")
  }
}

/// Argv for `gh issue view <n> --repo <slug> --json …`.
pub fn issue_view_argv(slug: &str, number: u64) -> Vec<String> {
  let mut argv: Vec<String> = vec!["issue".into(), "view".into(), number.to_string()];
  argv.extend(repo_flag(slug));
  argv.extend(["--json".into(), ISSUE_JSON_FIELDS.into()]);
  argv
}

/// Resolve the `gh` program to invoke: `$GWM_GH` when set (test / override
/// hook), else `gh` on `PATH`. Read once on the calling thread so off-thread
/// fetches can capture it without re-reading the environment.
pub fn gh_program() -> OsString {
  std::env::var_os("GWM_GH").unwrap_or_else(|| "gh".into())
}

pub fn create_issue(slug: &str, req: &IssueCreateRequest<'_>) -> Result<CreatedIssue> {
  parse_created_issue(&run_gh(issue_create_argv(slug, req))?)
}

/// Argv for `gh issue create …`.
pub fn issue_create_argv(slug: &str, req: &IssueCreateRequest<'_>) -> Vec<OsString> {
  let mut args: Vec<OsString> = Vec::with_capacity(8 + 2 * req.labels.len());
  args.push("issue".into());
  args.push("create".into());
  args.push("--title".into());
  args.push(req.title.into());
  args.push("--body-file".into());
  args.push(req.body_file.as_os_str().to_owned());
  for label in req.labels {
    args.push("--label".into());
    args.push(label.into());
  }
  // An empty slug means `origin` was unresolvable; `gh` then infers the
  // repo from the local git context, which is the pre-#419 behaviour this
  // path has always relied on.
  if !slug.is_empty() {
    args.push("--repo".into());
    args.push(slug.into());
  }
  args
}

/// Recover the created issue from the URL `gh issue create` prints.
pub fn parse_created_issue(stdout: &str) -> Result<CreatedIssue> {
  let stdout = stdout.trim().to_string();
  let Some(caps) = ISSUE_URL_RE.captures(&stdout) else {
    return Err(GwmError::CommandFailed(format!(
      "gh issue create did not print an issue URL containing a number: {}",
      stdout
    )));
  };
  let number = caps
    .get(1)
    .and_then(|m| m.as_str().parse::<u64>().ok())
    .ok_or_else(|| GwmError::CommandFailed(format!("failed to parse issue number from gh output: {}", stdout)))?;
  Ok(CreatedIssue { number, url: stdout })
}

/// Shell out to `gh pr create` with a body file already rendered by
/// [`crate::pr_templates::render_pr_body`]. Parses the URL printed by
/// gh on success to extract the PR number.
pub fn create_pr(slug: &str, req: &PrCreateRequest<'_>) -> Result<CreatedPr> {
  parse_created_pr(&run_gh(pr_create_argv(slug, req))?)
}

/// Argv for `gh pr create …`.
pub fn pr_create_argv(slug: &str, req: &PrCreateRequest<'_>) -> Vec<OsString> {
  let mut args: Vec<OsString> =
    Vec::with_capacity(10 + if req.draft { 1 } else { 0 } + if req.base.is_some() { 2 } else { 0 });
  args.push("pr".into());
  args.push("create".into());
  args.push("--title".into());
  args.push(req.title.into());
  args.push("--body-file".into());
  args.push(req.body_file.as_os_str().to_owned());
  args.push("--head".into());
  args.push(req.head.into());
  if let Some(base) = req.base {
    args.push("--base".into());
    args.push(base.into());
  }
  if req.draft {
    args.push("--draft".into());
  }
  // An empty slug means `origin` was unresolvable; `gh` then infers the
  // repo from the local git context, which is the pre-#419 behaviour this
  // path has always relied on.
  if !slug.is_empty() {
    args.push("--repo".into());
    args.push(slug.into());
  }
  args
}

/// Recover the created PR from the URL `gh pr create` prints.
pub fn parse_created_pr(stdout: &str) -> Result<CreatedPr> {
  let stdout = stdout.trim().to_string();
  let Some(caps) = PR_URL_RE.captures(&stdout) else {
    return Err(GwmError::CommandFailed(format!(
      "gh pr create did not print a PR URL containing a number: {}",
      stdout
    )));
  };
  let number = caps
    .get(1)
    .and_then(|m| m.as_str().parse::<u64>().ok())
    .ok_or_else(|| GwmError::CommandFailed(format!("failed to parse PR number from gh output: {}", stdout)))?;
  Ok(CreatedPr { number, url: stdout })
}

/// Run `gh pr view <n> --repo <slug> --json …` and parse the result.
pub fn fetch_pr(slug: &str, number: u64) -> Result<PrStatus> {
  fetch_pr_with(&gh_program(), slug, number)
}

/// [`fetch_pr`] with an explicitly resolved `gh` program path — PR-side
/// counterpart to [`fetch_issue_with`], used by the TUI off-thread fetch
/// (issue #217).
pub fn fetch_pr_with(program: &OsStr, slug: &str, number: u64) -> Result<PrStatus> {
  parse_pr_json(&run_gh_with(program, pr_view_argv(slug, number))?)
}

/// Argv for `gh pr view <n> --repo <slug> --json …`.
pub fn pr_view_argv(slug: &str, number: u64) -> Vec<String> {
  let mut argv: Vec<String> = vec!["pr".into(), "view".into(), number.to_string()];
  argv.extend(repo_flag(slug));
  argv.extend(["--json".into(), PR_JSON_FIELDS.into()]);
  argv
}

#[derive(Deserialize)]
struct RawPrHead {
  number: u64,
  // `Option` (not just `#[serde(default)]`) so an explicit `"author": null`
  // — a deleted GitHub account — deserialises to `None` instead of erroring;
  // `default` alone only covers a *missing* key.
  #[serde(default)]
  author: Option<RawAuthor>,
  #[serde(rename = "headRefName", default)]
  head_ref_name: String,
  #[serde(rename = "baseRefName", default)]
  base_ref_name: String,
}

#[derive(Deserialize, Default)]
struct RawAuthor {
  #[serde(default)]
  login: String,
}

const PR_HEAD_JSON_FIELDS: &str = "number,author,headRefName,baseRefName";

/// Parse the JSON from `gh pr view <n> --json number,author,headRefName,baseRefName`.
/// Kept pure + `pub` so its shape is unit-testable without spawning `gh`.
pub fn parse_pr_head_json(s: &str) -> Result<PrHead> {
  let raw: RawPrHead = serde_json::from_str(s).map_err(|e| GwmError::GhJsonParse {
    kind: "pr head",
    source: e,
  })?;
  Ok(PrHead {
    number: raw.number,
    author: raw.author.unwrap_or_default().login,
    head_ref_name: raw.head_ref_name,
    base_ref_name: raw.base_ref_name,
  })
}

/// Run `gh pr view <n> --repo <slug> --json …` and parse the head metadata
/// `gwm review` needs (author / head ref / base ref). Works for PRs in any
/// state — open, draft, closed, or merged.
pub fn fetch_pr_head(slug: &str, number: u64) -> Result<PrHead> {
  parse_pr_head_json(&run_gh(pr_head_argv(slug, number))?)
}

/// Argv for `gh pr view <n> --repo <slug> --json number,author,headRefName,baseRefName`.
pub fn pr_head_argv(slug: &str, number: u64) -> Vec<String> {
  let mut argv: Vec<String> = vec!["pr".into(), "view".into(), number.to_string()];
  argv.extend(repo_flag(slug));
  argv.extend(["--json".into(), PR_HEAD_JSON_FIELDS.into()]);
  argv
}

/// Find the most recent PR opened from `branch` (head ref) on the given
/// repo, regardless of state. Returns `Ok(Some(N))` if at least one PR
/// exists (open, draft, closed, or merged — `gh pr list --state all`),
/// `Ok(None)` otherwise. Callers that need state-aware filtering should
/// pair this with `fetch_pr` to inspect `PrState` afterwards.
pub fn find_pr_for_branch(slug: &str, branch: &str) -> Result<Option<u64>> {
  let stdout = run_gh(find_pr_argv(slug, branch))?;
  parse_pr_list_number(&stdout)
}

/// Argv for `gh pr list --repo <slug> --head <branch> --state all --json
/// number --limit 1`. Extracted so the test suite can pin the `gh`
/// contract without shelling out; [`find_pr_for_branch`] is the caller
/// that actually invokes it. `--state all` is the load-bearing bit: a
/// closed or merged PR for the branch is still detected (its `PrState`
/// is resolved later via [`fetch_pr`]).
pub fn find_pr_argv(slug: &str, branch: &str) -> Vec<String> {
  let mut argv: Vec<String> = vec!["pr".into(), "list".into()];
  argv.extend(repo_flag(slug));
  argv.extend([
    "--head".into(),
    branch.into(),
    "--state".into(),
    "all".into(),
    "--json".into(),
    // `isCrossRepository` is GitHub's own marker for "opened from a
    // fork"; `parse_pr_list_number` ranks on it (Codex review #458).
    "number,isCrossRepository".into(),
    // More than one row on purpose: `--head` matches the branch NAME
    // only, so a fork carrying the same name can appear.
    "--limit".into(),
    "20".into(),
  ]);
  argv
}

/// Parse the JSON array printed by `gh pr list --json number --limit 1`,
/// returning the first PR number if any. Exposed for unit tests so the
/// parse contract is covered without a `gh` shell-out.
pub fn parse_pr_list_number(s: &str) -> Result<Option<u64>> {
  #[derive(Deserialize)]
  struct PrRef {
    number: u64,
    /// GitHub's marker for a PR opened from a fork. `--head <branch>`
    /// matches the branch NAME only, so a fork sharing the name lands in
    /// the same list — and its number would be persisted as this
    /// branch's detected PR (Codex review #458). Absent is treated as
    /// same-repo so an older payload still detects.
    #[serde(rename = "isCrossRepository", default)]
    is_cross_repository: Option<bool>,
  }
  let arr: Vec<PrRef> = serde_json::from_str(s).map_err(|e| GwmError::GhJsonParse {
    kind: "pr list",
    source: e,
  })?;
  // Prefer a same-repo PR; fall back to a fork's rather than reporting
  // nothing. Filtering forks out entirely also removed the standard
  // contributor workflow — branch locally, push to your own fork, open
  // the PR against upstream — which is cross-repository by definition
  // and had been detected before (Codex review #458).
  //
  // What is left ambiguous: no same-repo PR *and* a fork PR that might
  // not be yours. Resolving that needs `headRepositoryOwner` matched
  // against the repo's configured remotes, which is new machinery in
  // round 27 of a review — filed as issue #461. Until then this is
  // still strictly better than the pre-filter behaviour, which took the
  // first row whatever it was.
  Ok(
    arr
      .iter()
      .find(|p| !p.is_cross_repository.unwrap_or(false))
      .or_else(|| arr.first())
      .map(|p| p.number),
  )
}

fn run_gh<I, S>(args: I) -> Result<String>
where
  I: IntoIterator<Item = S>,
  S: AsRef<OsStr>,
{
  run_gh_with(&gh_program(), args)
}

/// [`run_gh`] against an explicitly resolved `gh` program. Lets callers on
/// a worker thread (issue #217) avoid re-reading `GWM_GH` / the process
/// environment concurrently with env-mutating code on other threads. The
/// spawn + logging + error shape is shared with the GitLab backend since
/// #419 — see [`forge::run_cli`].
fn run_gh_with<I, S>(program: &OsStr, args: I) -> Result<String>
where
  I: IntoIterator<Item = S>,
  S: AsRef<OsStr>,
{
  forge::run_cli(program, args)
}

// ---- Labels (issue #81) -------------------------------------------------

const LABEL_JSON_FIELDS: &str = "name,color,description";
const LABEL_LIST_LIMIT: &str = "1000";

#[derive(Deserialize)]
struct RawLabel2 {
  name: String,
  /// `color` is a documented gh-CLI invariant — every label always
  /// carries one. We deliberately do NOT mark this `#[serde(default)]`:
  /// if a future gh contract change drops the field, we want a hard
  /// parse error rather than a silent empty-string that would flag
  /// every remote label as a colour mismatch in the diff. (Copilot
  /// review on PR #90.)
  color: String,
  #[serde(default)]
  description: Option<String>,
}

/// Parse the JSON returned by `gh label list --json name,color,description`.
/// Exposed publicly so unit tests can cover the contract without
/// shelling out. Two normalisations happen here so callers get a
/// uniformly-shaped `RemoteLabel`:
///
/// - **`color`** is lowercased. GitHub serialises hex colours in
///   either case; the diff engine expects the lowercase form, and
///   normalising at the parse boundary means downstream code never
///   has to think about it.
/// - **`description`** is left as-is. An empty `""` from GitHub
///   round-trips as `Some("")`; the labels-diff module collapses
///   empty strings to `None` on its own.
pub fn parse_labels_json(s: &str) -> Result<Vec<RemoteLabel>> {
  let raw: Vec<RawLabel2> = serde_json::from_str(s).map_err(|e| GwmError::GhJsonParse {
    kind: "labels",
    source: e,
  })?;
  Ok(
    raw
      .into_iter()
      .map(|r| RemoteLabel {
        name: r.name,
        description: r.description,
        color: r.color.to_ascii_lowercase(),
      })
      .collect(),
  )
}

/// Argv for `gh label list --repo <slug> --json name,color,description --limit 1000`.
/// Extracted so the test suite can pin the contract; callers should
/// prefer `fetch_remote_labels` which actually shells out.
pub fn label_list_argv(slug: &str) -> Vec<String> {
  let mut argv: Vec<String> = vec!["label".into(), "list".into()];
  argv.extend(repo_flag(slug));
  argv.extend([
    "--json".into(),
    LABEL_JSON_FIELDS.into(),
    "--limit".into(),
    LABEL_LIST_LIMIT.into(),
  ]);
  argv
}

/// Argv for `gh label create <name> --color <hex> [--description <desc>] --force --repo <slug>`.
/// The `--force` flag is the key contract bit: GitHub's CLI uses it
/// to mean "create OR update", which is exactly what `gwm labels
/// push` needs (no separate "edit" call). When `description` is
/// `None` we omit the flag entirely rather than pass `""` — gh would
/// otherwise wipe an existing description that the user didn't intend
/// to touch.
pub fn label_create_argv(slug: &str, spec: &LabelSpec) -> Vec<String> {
  let mut argv: Vec<String> = vec!["label".into(), "create".into(), spec.name.clone()];
  argv.extend(repo_flag(slug));
  argv.extend(["--color".into(), spec.color.clone(), "--force".into()]);
  if let Some(desc) = spec.description.as_ref().filter(|s| !s.is_empty()) {
    argv.push("--description".into());
    argv.push(desc.clone());
  }
  argv
}

/// Argv for `gh label delete <name> --repo <slug> --yes`. The `--yes`
/// flag bypasses the interactive confirm prompt; without it gh blocks
/// on a TTY read and `gwm labels push --prune` hangs.
pub fn label_delete_argv(slug: &str, name: &str) -> Vec<String> {
  let mut argv: Vec<String> = vec!["label".into(), "delete".into(), name.into()];
  argv.extend(repo_flag(slug));
  argv.push("--yes".into());
  argv
}

/// Run `gh label list --repo <slug> --json …` and parse the result.
/// Returns an empty vec when the remote has no labels (which is
/// distinct from "gh not installed" — that surfaces as
/// `CommandFailed`).
pub fn fetch_remote_labels(slug: &str) -> Result<Vec<RemoteLabel>> {
  let argv = label_list_argv(slug);
  let args: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
  let stdout = run_gh(&args)?;
  parse_labels_json(&stdout)
}

/// Push one label upstream via `gh label create --force`. Returns
/// `Ok(())` on success; the caller is responsible for tracking which
/// label was created vs. updated (the diff already knows).
pub fn push_label(slug: &str, spec: &LabelSpec) -> Result<()> {
  let argv = label_create_argv(slug, spec);
  let args: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
  run_gh(&args)?;
  Ok(())
}

/// Delete one label on the remote via `gh label delete --yes`. Used
/// by `gwm labels push --prune` for labels declared on the remote but
/// not in `.gwm.toml`.
///
/// Validates `name` through [`crate::labels::validate_label_name`]
/// BEFORE shelling out (issue #100). The argv-injection vector that
/// motivates `validate_label_name` for declared labels (config side)
/// applies equally to the prune path: `gh label delete <name>` takes
/// the name positionally, so a remote label whose name starts with
/// `-` (planted by an attacker who can edit the upstream label set,
/// or by an unrelated tool predating the validator) would be parsed
/// as a flag — `-h` no-ops the delete with a help banner, `--repo
/// other/repo` retargets the operation. We refuse the prune with a
/// scoped error instead of running the risky argv.
pub fn delete_label(slug: &str, name: &str) -> Result<()> {
  validate_remote_label_name(name)?;
  let argv = label_delete_argv(slug, name);
  let args: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
  run_gh(&args)?;
  Ok(())
}

/// Refuse a hostile remote label name before it reaches an argv slot
/// (issue #100). `gh label delete <name>` takes the name positionally, so
/// a remote label starting with `-` would be parsed as a flag: `-h` no-ops
/// the delete with a help banner, `--repo other/repo` retargets it.
fn validate_remote_label_name(name: &str) -> Result<()> {
  crate::labels::validate_label_name(name).map_err(|e| {
    let inner = match e {
      GwmError::Config(msg) => msg,
      other => other.to_string(),
    };
    GwmError::Config(format!(
      "labels (remote): {} — refusing to delete via `gh label delete`",
      inner
    ))
  })
}

// ---- Milestones (issue #82) ---------------------------------------------

const MILESTONE_PER_PAGE: &str = "100";

#[derive(Deserialize)]
struct RawMilestone {
  number: u64,
  title: String,
  /// Always present in the documented schema. Like `RawLabel2.color`
  /// for labels, we deliberately do NOT mark this `#[serde(default)]`:
  /// a contract change would surface as a hard parse error rather than
  /// silently flagging every remote milestone as a state mismatch.
  state: String,
  #[serde(default)]
  description: Option<String>,
  #[serde(default)]
  due_on: Option<String>,
}

/// Parse the JSON returned by `gh api repos/:owner/:repo/milestones?state=all`.
/// Exposed publicly so unit tests can cover the contract without
/// shelling out. The `state` field is mapped to the strict
/// `MilestoneState` enum — an unknown value is a hard error rather
/// than a silent third state on the diff side.
pub fn parse_milestones_json(s: &str) -> Result<Vec<RemoteMilestone>> {
  let raw: Vec<RawMilestone> = serde_json::from_str(s).map_err(|e| GwmError::GhJsonParse {
    kind: "milestones",
    source: e,
  })?;
  raw
    .into_iter()
    .map(|r| {
      let state = match r.state.as_str() {
        "open" => MilestoneState::Open,
        "closed" => MilestoneState::Closed,
        other => {
          return Err(GwmError::Other(format!(
            "milestone '{}' has unknown state '{}': expected 'open' or 'closed'",
            r.title, other
          )))
        }
      };
      Ok(RemoteMilestone {
        number: r.number,
        title: r.title,
        description: r.description,
        due_on: r.due_on,
        state,
      })
    })
    .collect()
}

/// Argv for `gh api --paginate repos/<slug>/milestones?state=all&per_page=100`.
///
/// Two contract bits worth pinning:
/// - `state=all` — without it, the default endpoint only lists `open`
///   milestones and `gwm milestones push --prune` would silently
///   leave closed ones in place.
/// - `--paginate` — GitHub caps `per_page` at 100. Without paginating
///   we'd diff against a truncated remote set for repos with more
///   than 100 milestones, leading to bogus `create` rows and a
///   dangerously confusing `--prune` (Copilot review on PR #92).
pub fn milestone_list_argv(slug: &str) -> Vec<String> {
  vec![
    "api".into(),
    "--paginate".into(),
    format!(
      "{}/milestones?state=all&per_page={}",
      repo_api_path(slug),
      MILESTONE_PER_PAGE
    ),
  ]
}

/// Argv for `gh api -X POST repos/<slug>/milestones -f title=… [-f
/// description=…] [-f due_on=…] -f state=…`. Each optional field is
/// omitted entirely when absent — `gh` would otherwise wipe the
/// existing remote value.
pub fn milestone_create_argv(slug: &str, spec: &MilestoneSpec) -> Vec<String> {
  let mut argv = vec![
    "api".into(),
    "-X".into(),
    "POST".into(),
    format!("{}/milestones", repo_api_path(slug)),
    "-f".into(),
    format!("title={}", spec.title),
    "-f".into(),
    format!("state={}", spec.state.as_str()),
  ];
  if let Some(desc) = spec.description.as_ref().filter(|s| !s.is_empty()) {
    argv.push("-f".into());
    argv.push(format!("description={}", desc));
  }
  if let Some(due) = spec.due_on.as_ref().filter(|s| !s.is_empty()) {
    argv.push("-f".into());
    argv.push(format!("due_on={}", due));
  }
  argv
}

/// Argv for `gh api -X PATCH repos/<slug>/milestones/<number> -f …`.
/// Same omission rules as `milestone_create_argv`: absent optionals
/// are skipped so the remote value isn't wiped.
pub fn milestone_update_argv(slug: &str, number: u64, spec: &MilestoneSpec) -> Vec<String> {
  let mut argv = vec![
    "api".into(),
    "-X".into(),
    "PATCH".into(),
    format!("{}/milestones/{}", repo_api_path(slug), number),
    "-f".into(),
    format!("title={}", spec.title),
    "-f".into(),
    format!("state={}", spec.state.as_str()),
  ];
  if let Some(desc) = spec.description.as_ref().filter(|s| !s.is_empty()) {
    argv.push("-f".into());
    argv.push(format!("description={}", desc));
  }
  if let Some(due) = spec.due_on.as_ref().filter(|s| !s.is_empty()) {
    argv.push("-f".into());
    argv.push(format!("due_on={}", due));
  }
  argv
}

/// Argv for `gh api -X DELETE repos/<slug>/milestones/<number>`.
/// `gh api -X DELETE` is non-interactive by construction (no TTY
/// confirm), so there's no `--yes` equivalent to add.
pub fn milestone_delete_argv(slug: &str, number: u64) -> Vec<String> {
  vec![
    "api".into(),
    "-X".into(),
    "DELETE".into(),
    format!("{}/milestones/{}", repo_api_path(slug), number),
  ]
}

/// Run `gh api repos/<slug>/milestones?state=all` and parse the
/// result. Returns an empty vec when the remote has no milestones.
pub fn fetch_remote_milestones(slug: &str) -> Result<Vec<RemoteMilestone>> {
  let argv = milestone_list_argv(slug);
  let args: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
  let stdout = run_gh(&args)?;
  parse_milestones_json(&stdout)
}

/// Create one milestone upstream via `gh api -X POST`. Returns
/// `Ok(())` — the caller already has the spec; we don't bother
/// parsing the response back into a `RemoteMilestone`.
pub fn create_milestone(slug: &str, spec: &MilestoneSpec) -> Result<()> {
  let argv = milestone_create_argv(slug, spec);
  let args: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
  run_gh(&args)?;
  Ok(())
}

/// Update one milestone upstream via `gh api -X PATCH`. `number` is
/// the GitHub-issued identifier carried through `MilestoneUpdate`.
pub fn update_milestone(slug: &str, number: u64, spec: &MilestoneSpec) -> Result<()> {
  let argv = milestone_update_argv(slug, number, spec);
  let args: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
  run_gh(&args)?;
  Ok(())
}

/// Delete one milestone on the remote via `gh api -X DELETE`. Used
/// by `gwm milestones push --prune` for milestones declared on the
/// remote but not in `.gwm.toml`.
pub fn delete_milestone(slug: &str, number: u64) -> Result<()> {
  let argv = milestone_delete_argv(slug, number);
  let args: Vec<&str> = argv.iter().map(|s| s.as_str()).collect();
  run_gh(&args)?;
  Ok(())
}

// ---- The Forge backend (issue #419) -------------------------------------

/// GitHub implementation of [`Forge`], shelling out to `gh`.
///
/// A thin binding over the free functions above rather than a rewrite:
/// they were already the GitHub backend in all but name, and keeping them
/// `pub` means the extraction reads as a no-op for the existing tests
/// that pin the `gh` argv contract.
#[derive(Debug, Clone)]
pub struct GitHubForge {
  origin: forge::RemoteRef,
  program: OsString,
  env: Vec<(String, String)>,
  env_remove: Vec<&'static str>,
  workdir: Option<std::path::PathBuf>,
}

impl GitHubForge {
  /// Resolves `$GWM_GH` **now**, on the calling thread, so a forge handed
  /// to the TUI's fetch worker never re-reads the process environment
  /// concurrently with env-mutating code (issue #217).
  pub fn new(origin: forge::RemoteRef, workdir: Option<std::path::PathBuf>) -> Self {
    Self {
      env: gh_env(&origin),
      env_remove: gh_env_remove(&origin, workdir.is_some()),
      origin,
      program: gh_program(),
      workdir,
    }
  }

  fn run<I, S>(&self, args: I) -> Result<String>
  where
    I: IntoIterator<Item = S>,
    S: AsRef<OsStr>,
  {
    forge::run_cli_with(
      &self.program,
      args,
      &forge::CliSpawn {
        env: &self.env,
        cwd: self.workdir.as_deref(),
        env_remove: &self.env_remove,
        redact_after: &[],
        redact_output: false,
        // `gh` takes bodies via `--body-file`, so nothing sensitive ever
        // needs stdin on this backend (contrast `glab`, issue #459).
        stdin: None,
      },
    )
  }
}

/// Environment pinned on every `gh` spawn (Codex review #458).
///
/// `$GH_HOST` selects the GitHub instance. Before #419 the slug parser
/// rejected anything that was not github.com, so a GitHub Enterprise host
/// could not reach this code at all; host-agnostic parsing opened that
/// door, and without the pin `gh` would silently target github.com and
/// could read a same-named repo on the wrong tenant.
///
/// github.com is pinned like any other host, deliberately: the child
/// inherits gwm's environment, so a user's ambient `GH_HOST` — routine for
/// enterprise users — would otherwise retarget a github.com repo, since
/// the argv only ever carries `--repo owner/repo` and never a hostname
/// (Codex review #458, round 3).
///
/// The host is pinned whenever a slug is known — including github.com,
/// and including a **guessed** (SSH) origin. Both were exempted at some
/// point and both exemptions were wrong (Codex review #458):
///
/// - The child inherits gwm's environment, so an ambient `GH_HOST` —
///   routine for enterprise users — retargets every call, since the argv
///   only ever carries `--repo owner/repo` and never a hostname. Knowing
///   the repo is on github.com, gwm says so rather than letting the
///   environment decide.
/// - `gh` cannot be steered any other way: `gh api repos/<slug>/…` bakes
///   the slug into the request path, so unlike `glab` it has no working
///   directory to fall back to. This is the one place the two backends
///   diverge — see [`crate::gitlab::glab_env`], where a guessed origin is
///   deliberately left alone because a distinct SSH hostname *is* a
///   documented GitLab pattern.
///
/// Nothing is pinned only when the slug is empty: that is the caller
/// asking `gh` to infer the project locally.
/// Inherited variables that would redirect `gh` at another repository.
///
/// `$GH_REPO` names a whole `[HOST/]OWNER/REPO` and wins over both the
/// working directory and any inference, so an exported one silently
/// retargets every call. It is cleared whenever gwm supplies a project
/// of its own — a slug, or a repo to spawn the child inside.
///
/// It is **not** cleared when gwm supplies neither. That case is real
/// and is the one `$GH_REPO` exists for: `resolve_or_default` builds a
/// forge for a repo with no `origin`, deliberately passing no slug and
/// carrying no workdir, so `gwm new` / `gwm pr` still work there. gh
/// cannot infer a project either, and taking the variable away left the
/// user no way to name one (Codex review #458). Tier 1's premise —
/// "gwm always knows the project" — was false in exactly that spot.
///
/// The rule this applies, shared with [`crate::gitlab::glab_env_remove`]
/// and stated once so it stops being rediscovered one variable per
/// review round:
///
/// 1. **Project selectors are cleared when gwm supplies a project.**
///    A slug, or a working directory for the CLI to infer from.
/// 2. **Host overrides are cleared only when gwm has an authoritative
///    value to replace them with.** gwm sometimes knows the host.
/// 3. **Authentication and config location are never touched.** gwm
///    never knows better than the user which identity they meant to use
///    or where they keep their credentials.
///
/// Tier 3 raises the obvious objection — gwm pins a host read from
/// `origin` and leaves the global tokens in place, so a repo whose
/// remote points at a hostile server gets a bearer token sent to it.
///
/// An earlier revision of this comment answered "unchanged by any of
/// this, the pin carries the host `gh` would have resolved unaided".
/// That was **false**, and it is recorded rather than deleted because
/// the same mistake produced the `$GITLAB_API_HOST` cycle in
/// [`crate::gitlab::glab_env_remove`]. Before this PR
/// `github::repo_slug` accepted `git@github.com:` and
/// `https://github.com/` and nothing else — every other origin was
/// rejected with "is not a github URL", so gwm never made an
/// authenticated call against an arbitrary host at all. Verifying the
/// mechanism is not verifying the baseline.
///
/// Closed where it is actually opened: [`crate::forge::resolve`] no
/// longer treats an unrecognised host as GitHub by default. The
/// residual hole is stated there.
///
/// Audited against gh's documented environment. Tier 1: `$GH_REPO`.
/// Tier 2: none — `$GH_HOST` is pinned by [`gh_env`] and gh publishes
/// neither an alias for it nor a separate API endpoint override, so
/// there is nothing to close behind the pin (unlike `glab`). Tier 3:
/// `$GH_TOKEN` / `$GITHUB_TOKEN`, `$GH_ENTERPRISE_TOKEN` /
/// `$GITHUB_ENTERPRISE_TOKEN`, `$GH_CONFIG_DIR`. Everything else gh
/// reads is presentation (`$GH_PAGER`, `$GH_EDITOR`, `$GH_BROWSER`,
/// `$GH_FORCE_TTY`, `$GH_MDWIDTH`, `$NO_COLOR`), diagnostics
/// (`$GH_DEBUG`), or telemetry — none of it can retarget a call.
pub fn gh_env_remove(origin: &forge::RemoteRef, has_workdir: bool) -> Vec<&'static str> {
  if origin.path.is_empty() && !has_workdir {
    return Vec::new();
  }
  vec!["GH_REPO"]
}

pub fn gh_env(origin: &forge::RemoteRef) -> Vec<(String, String)> {
  // Same rule as [`crate::gitlab::glab_env`]. An SSH remote carries no
  // web scheme or port, so `https://<ssh-host>` is a guess, and pinning
  // it as `$GH_HOST` broke a GHE whose SSH endpoint is not its API host.
  //
  // Rounds 4, 5 and 7 pinned harder each time, to stop an ambient
  // `$GH_HOST` retargeting the call; round 16 refused to stop, on the
  // claim that `gh api` had no way to resolve a repo from the working
  // directory. That claim was read off a stale code comment and is
  // wrong. gh documents `{owner}` / `{repo}` as endpoint placeholders
  // "replaced with values from the repository of the current directory",
  // and documents `$GH_HOST` as applying only "where a hostname has not
  // been provided, or cannot be inferred from the context of a local Git
  // repository". The child is spawned inside the repo, so delegating
  // closes the retargeting hazard rather than reopening it — the slug
  // goes away with the pin (see `repo_selector` and `repo_api_path`).
  //
  // `$GH_HOST` also cannot carry everything a remote URL can. gh's own
  // `HostnameValidator` rejects any hostname containing `:`, and
  // `RESTPrefix` / `GraphQLEndpoint` always build `https://` for
  // anything but the hardcoded `github.localhost`
  // (`internal/ghinstance/host.go`). So a non-default port and a plain
  // http origin are both inexpressible — and mis-pinning them is worse
  // than a 404, because `IsEnterprise` means "not github.com":
  // `GH_HOST=github.com:443` reads as Enterprise, so gh picks
  // `$GH_ENTERPRISE_TOKEN` and sends it to github.com while calling
  // `/api/v3/`. Round 2 flagged the port as undocumented and passed it
  // anyway; the answer is no (Codex review #458). Where gwm cannot
  // express the origin it pins nothing and delegates, which is the same
  // path a guessed origin already takes.
  if origin.trust != forge::OriginTrust::FromUrl || origin.path.is_empty() {
    return Vec::new();
  }
  let Some(host) = gh_pinnable_host(origin) else {
    return Vec::new();
  };
  vec![("GH_HOST".to_string(), host)]
}

/// The origin as a hostname gh will accept, or `None` when it cannot be
/// expressed. A default port is dropped rather than disqualifying —
/// `github.com:443` and `github.com` are the same endpoint, and only the
/// first one reads as Enterprise.
fn gh_pinnable_host(origin: &forge::RemoteRef) -> Option<String> {
  let (scheme, rest) = origin.web_origin.split_once("://")?;
  if !scheme.eq_ignore_ascii_case("https") {
    return None;
  }
  let authority = rest.trim_end_matches('/');
  match authority.rsplit_once(':') {
    Some((h, "443")) => Some(h.to_string()),
    Some(_) => None,
    None => Some(authority.to_string()),
  }
}

impl Forge for GitHubForge {
  fn kind(&self) -> ForgeKind {
    ForgeKind::GitHub
  }

  fn slug(&self) -> &str {
    // Identity, not the CLI selector: this feeds display and URLs, which
    // need the real path even when `repo_selector` deliberately returns
    // nothing. Same as the GitLab backend.
    &self.origin.path
  }

  fn web_origin(&self) -> &str {
    &self.origin.web_origin
  }

  fn workdir(&self) -> Option<&std::path::Path> {
    self.workdir.as_deref()
  }

  fn origin_is_authoritative(&self) -> bool {
    self.origin.trust == forge::OriginTrust::FromUrl
  }

  /// Always the slug: `gh` is pinned by `$GH_HOST` even for a guessed
  /// origin (see [`gh_env`]), so there is no ambiguity to defer to the
  /// working directory — and `gh api repos/<slug>/…` could not defer
  /// anyway, the slug being part of the request path.
  fn repo_selector(&self) -> &str {
    // The slug and the host pin move together, or the slug resolves
    // against the wrong instance. Two ways to have no pin: a guessed
    // origin (round 18), and — since round 27 — an origin `gh` cannot
    // express, a non-default port or plain http. The second was missed,
    // so `--repo owner/repo` went out with no `$GH_HOST` and `gh`
    // resolved it against github.com or an ambient one: a same-named
    // repo on another tenant, read and pruned (Codex review #458).
    //
    // `github.com` is the exception that needs no pin, being gh's own
    // default instance.
    let pinned = !gh_env(&self.origin).is_empty() || self.origin.host.eq_ignore_ascii_case("github.com");
    if !pinned && self.workdir.is_some() {
      return "";
    }
    &self.origin.path
  }

  fn issue_url(&self, number: u64) -> String {
    format!("{}/{}/issues/{}", self.origin.web_origin, self.origin.path, number)
  }

  fn pr_url(&self, number: u64) -> String {
    format!("{}/{}/pull/{}", self.origin.web_origin, self.origin.path, number)
  }

  fn pr_head_refspec(&self, number: u64) -> String {
    format!("pull/{number}/head")
  }

  // Every method below goes through `self.run`, never the free functions,
  // so `$GH_HOST` reaches the child (Codex review #458). The free functions
  // stay for the argv/parse contract the test suite pins.

  fn fetch_issue(&self, number: u64) -> Result<IssueStatus> {
    parse_issue_json(&self.run(issue_view_argv(self.repo_selector(), number))?)
  }

  fn fetch_pr(&self, number: u64) -> Result<PrStatus> {
    parse_pr_json(&self.run(pr_view_argv(self.repo_selector(), number))?)
  }

  fn fetch_pr_head(&self, number: u64) -> Result<PrHead> {
    parse_pr_head_json(&self.run(pr_head_argv(self.repo_selector(), number))?)
  }

  fn find_pr_for_branch(&self, branch: &str) -> Result<Option<u64>> {
    parse_pr_list_number(&self.run(find_pr_argv(self.repo_selector(), branch))?)
  }

  fn create_issue(&self, req: &IssueCreateRequest<'_>) -> Result<CreatedIssue> {
    parse_created_issue(&self.run(issue_create_argv(self.repo_selector(), req))?)
  }

  fn create_pr(&self, req: &PrCreateRequest<'_>) -> Result<CreatedPr> {
    parse_created_pr(&self.run(pr_create_argv(self.repo_selector(), req))?)
  }

  fn fetch_remote_labels(&self) -> Result<Vec<RemoteLabel>> {
    parse_labels_json(&self.run(label_list_argv(self.repo_selector()))?)
  }

  fn create_label(&self, spec: &LabelSpec) -> Result<()> {
    // `gh label create --force` means "create OR update", so both halves
    // of the trait's create/update split land on the same call here. The
    // split exists for GitLab, which has no such flag.
    self.run(label_create_argv(self.repo_selector(), spec))?;
    Ok(())
  }

  fn update_label(&self, spec: &LabelSpec) -> Result<()> {
    self.create_label(spec)
  }

  fn delete_label(&self, name: &str) -> Result<()> {
    validate_remote_label_name(name)?;
    self.run(label_delete_argv(self.repo_selector(), name))?;
    Ok(())
  }

  fn fetch_remote_milestones(&self) -> Result<Vec<RemoteMilestone>> {
    parse_milestones_json(&self.run(milestone_list_argv(self.repo_selector()))?)
  }

  fn create_milestone(&self, spec: &MilestoneSpec) -> Result<()> {
    self.run(milestone_create_argv(self.repo_selector(), spec))?;
    Ok(())
  }

  fn update_milestone(&self, number: u64, spec: &MilestoneSpec) -> Result<()> {
    self.run(milestone_update_argv(self.repo_selector(), number, spec))?;
    Ok(())
  }

  fn delete_milestone(&self, number: u64) -> Result<()> {
    self.run(milestone_delete_argv(self.repo_selector(), number))?;
    Ok(())
  }
}