workmux 0.1.261

An opinionated workflow tool that orchestrates git worktrees and tmux
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
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
use anyhow::{Context, Result, anyhow};
use nix::fcntl::{Flock, FlockArg};
use serde::{Deserialize, Serialize};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::fs::OpenOptions;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::{Mutex, OnceLock};
use tracing::debug;

use crate::util::write_atomic;

#[derive(Debug, Deserialize)]
pub struct PrDetails {
    #[serde(rename = "headRefName")]
    pub head_ref_name: String,
    #[serde(rename = "headRepositoryOwner")]
    pub head_repository_owner: RepositoryOwner,
    pub state: String,
    #[serde(rename = "isDraft")]
    pub is_draft: bool,
    pub title: String,
    pub author: Author,
}

#[derive(Debug, Deserialize)]
pub struct RepositoryOwner {
    pub login: String,
}

#[derive(Debug, Deserialize)]
pub struct Author {
    pub login: String,
}

impl PrDetails {
    pub fn is_fork(&self, current_repo_owner: &str) -> bool {
        self.head_repository_owner.login != current_repo_owner
    }
}

/// Aggregated status of PR checks
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum CheckState {
    /// All checks passed
    Success,
    /// Some checks failed (passed/total)
    Failure { passed: u32, total: u32 },
    /// Checks still running (passed/total)
    Pending { passed: u32, total: u32 },
}

/// Summary of a PR found by head ref search
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PrSummary {
    pub number: u32,
    pub title: String,
    pub state: String,
    #[serde(rename = "isDraft")]
    pub is_draft: bool,
    /// Aggregated check status (None if no checks configured)
    #[serde(default)]
    pub checks: Option<CheckState>,
    /// Check timing and name metadata
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub check_meta: Option<CheckMeta>,
    /// PR URL for opening in browser
    #[serde(default)]
    pub url: Option<String>,
}

/// Metadata about PR checks (timing, names) separate from aggregated state
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq)]
pub struct CheckMeta {
    /// Earliest start time among pending/running checks (Unix timestamp).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub started_at: Option<u64>,
    /// Pre-computed total duration in seconds for completed check runs.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub duration_secs: Option<u64>,
    /// Name of the first failing check, if any
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub failing_name: Option<String>,
}

/// Aggregated checks for a GitHub commit.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CheckSummary {
    pub state: CheckState,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub meta: Option<CheckMeta>,
}

impl CheckSummary {
    pub fn should_display_for_branch(&self, branch: &str) -> bool {
        !matches!(branch, "main" | "master") || matches!(self.state, CheckState::Failure { .. })
    }
}

/// GitHub state associated with a branch.
#[derive(Debug, Clone, PartialEq)]
pub struct BranchSummary {
    pub pr: Option<PrSummary>,
    pub checks: Option<CheckSummary>,
}

/// One local repository's branches requested by the sidebar GitHub worker.
pub struct BranchQueryRequest {
    pub repo_key: PathBuf,
    pub repo_root: PathBuf,
    pub branches: Vec<String>,
}

/// Fresh branch results, plus the complete active branch set for cache merging.
pub struct BranchQueryOutcome {
    pub requested: HashSet<String>,
    pub answered: HashMap<String, BranchSummary>,
}

/// Handles both CheckRun (status/conclusion) and StatusContext (state) from GitHub API
#[derive(Debug, Deserialize)]
struct CheckRollupItem {
    #[serde(alias = "state")]
    status: Option<String>,
    conclusion: Option<String>,
    #[serde(default)]
    name: Option<String>,
    #[serde(default)]
    started_at: Option<String>,
}

/// Parse a GitHub ISO 8601 UTC timestamp (e.g., "2026-03-24T14:02:00Z") to Unix seconds.
fn parse_github_timestamp(s: &str) -> Option<u64> {
    // GitHub always returns UTC timestamps in format: YYYY-MM-DDTHH:MM:SSZ
    let s = s.trim();
    if s.len() < 20 || !s.ends_with('Z') {
        return None;
    }
    let b = s.as_bytes();
    if b[4] != b'-' || b[7] != b'-' || b[10] != b'T' || b[13] != b':' || b[16] != b':' {
        return None;
    }
    let year: u64 = s[0..4].parse().ok()?;
    let month: u64 = s[5..7].parse().ok()?;
    let day: u64 = s[8..10].parse().ok()?;
    let hour: u64 = s[11..13].parse().ok()?;
    let min: u64 = s[14..16].parse().ok()?;
    let sec: u64 = s[17..19].parse().ok()?;

    if !(1..=12).contains(&month) || !(1..=31).contains(&day) || hour > 23 || min > 59 || sec > 59 {
        return None;
    }

    // Days from year 0 to Unix epoch (1970-01-01)
    // Using a simplified days-since-epoch calculation
    let mut days: u64 = 0;
    for y in 1970..year {
        days += if is_leap_year(y) { 366 } else { 365 };
    }
    let month_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    for m in 1..month {
        days += month_days[(m - 1) as usize] as u64;
        if m == 2 && is_leap_year(year) {
            days += 1;
        }
    }
    days += day - 1;

    Some(days * 86400 + hour * 3600 + min * 60 + sec)
}

fn is_leap_year(y: u64) -> bool {
    (y.is_multiple_of(4) && !y.is_multiple_of(100)) || y.is_multiple_of(400)
}

/// Aggregate check results into a single CheckState with optional metadata
fn aggregate_checks(checks: &[CheckRollupItem]) -> (Option<CheckState>, Option<CheckMeta>) {
    if checks.is_empty() {
        return (None, None);
    }

    let mut passed = 0u32;
    let mut failed = 0u32;
    let mut pending = 0u32;
    let mut skipped = 0u32;
    let mut earliest_pending_start: Option<u64> = None;
    let mut earliest_any_start: Option<u64> = None;
    let mut latest_any_start: Option<u64> = None;
    let mut failing_name: Option<String> = None;

    for check in checks {
        let status = check.status.as_deref().unwrap_or("");
        let conclusion = check.conclusion.as_deref().unwrap_or("");
        let ts = check.started_at.as_deref().and_then(parse_github_timestamp);

        // Track global start time range
        if let Some(t) = ts {
            earliest_any_start = Some(earliest_any_start.map_or(t, |prev: u64| prev.min(t)));
            latest_any_start = Some(latest_any_start.map_or(t, |prev: u64| prev.max(t)));
        }

        match (status, conclusion) {
            // Success states
            (_, "SUCCESS") | ("SUCCESS", _) => passed += 1,
            // Failure states (expanded to catch all failure-like conclusions)
            (_, "FAILURE" | "CANCELLED" | "TIMED_OUT" | "STARTUP_FAILURE" | "ACTION_REQUIRED")
            | ("FAILURE" | "ERROR", _) => {
                failed += 1;
                if failing_name.is_none() {
                    failing_name = check.name.clone();
                }
            }
            // Neutral/skipped - track but don't count toward active total
            (_, "NEUTRAL" | "SKIPPED") => skipped += 1,
            // Pending states (expanded)
            ("IN_PROGRESS" | "QUEUED" | "PENDING" | "REQUESTED" | "WAITING", _) => {
                pending += 1;
                if let Some(t) = ts {
                    earliest_pending_start =
                        Some(earliest_pending_start.map_or(t, |prev: u64| prev.min(t)));
                }
            }
            _ => {}
        }
    }

    let total = passed + failed + pending;

    // If no active checks but some were skipped, treat as success (GitHub behavior)
    if total == 0 {
        return if skipped > 0 {
            (Some(CheckState::Success), None)
        } else {
            (None, None)
        };
    }

    let state = if failed > 0 {
        CheckState::Failure { passed, total }
    } else if pending > 0 {
        CheckState::Pending { passed, total }
    } else {
        CheckState::Success
    };

    // Build metadata
    let meta = if pending > 0 {
        // Use earliest pending start, fall back to earliest any start
        let started = earliest_pending_start.or(earliest_any_start);
        if started.is_some() || failing_name.is_some() {
            Some(CheckMeta {
                started_at: started,
                duration_secs: None,
                failing_name,
            })
        } else {
            None
        }
    } else if failed > 0 {
        // For failures, compute duration if we know when checks started
        let duration_secs = match (earliest_any_start, current_unix_timestamp()) {
            (Some(start), Some(now)) => Some(now.saturating_sub(start)),
            _ => None,
        };
        if failing_name.is_some() || duration_secs.is_some() {
            Some(CheckMeta {
                started_at: earliest_any_start,
                duration_secs,
                failing_name,
            })
        } else {
            None
        }
    } else {
        None
    };

    (Some(state), meta)
}

fn summarize_checks(checks: &[CheckRollupItem]) -> Option<CheckSummary> {
    let (state, meta) = aggregate_checks(checks);
    state.map(|state| CheckSummary { state, meta })
}

/// Get current Unix timestamp in seconds
fn current_unix_timestamp() -> Option<u64> {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()
        .map(|d| d.as_secs())
}

/// Internal struct for parsing PR list results with owner info
#[derive(Debug, Deserialize)]
struct PrListResult {
    pub number: u32,
    pub title: String,
    pub state: String,
    #[serde(rename = "isDraft")]
    pub is_draft: bool,
    #[serde(rename = "headRepositoryOwner")]
    pub head_repository_owner: RepositoryOwner,
    #[serde(default)]
    pub url: Option<String>,
}

/// Find a PR by its head ref (e.g., "owner:branch" format).
/// Returns None if no PR is found, or the first matching PR if found.
pub fn find_pr_by_head_ref(owner: &str, branch: &str) -> Result<Option<PrSummary>> {
    // gh pr list --head only matches branch name, not owner:branch format
    // So we query by branch and filter by owner in the results
    let output = Command::new("gh")
        .args([
            "pr",
            "list",
            "--head",
            branch,
            "--state",
            "all", // Include closed/merged PRs
            "--json",
            "number,title,state,isDraft,headRepositoryOwner,url",
            "--limit",
            "50", // Get enough results to handle common branch names
        ])
        .output();

    let output = match output {
        Ok(out) => out,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            debug!("github:gh CLI not found, skipping PR lookup");
            return Ok(None);
        }
        Err(e) => {
            return Err(e).context("Failed to execute gh command");
        }
    };

    if !output.status.success() {
        debug!(
            owner = owner,
            branch = branch,
            "github:pr list failed, treating as no PR found"
        );
        return Ok(None);
    }

    let json_str = String::from_utf8(output.stdout).context("gh output is not valid UTF-8")?;

    // gh pr list returns an array
    let prs: Vec<PrListResult> =
        serde_json::from_str(&json_str).context("Failed to parse gh JSON output")?;

    // Find the PR from the specified owner (case-insensitive, as GitHub usernames are case-insensitive)
    let matching_pr = prs
        .into_iter()
        .find(|pr| pr.head_repository_owner.login.eq_ignore_ascii_case(owner));

    Ok(matching_pr.map(|pr| PrSummary {
        number: pr.number,
        title: pr.title,
        state: pr.state,
        is_draft: pr.is_draft,
        checks: None,
        check_meta: None,
        url: pr.url,
    }))
}

/// An open PR entry for display in the add-worktree modal.
pub struct PrListEntry {
    pub number: u32,
    pub title: String,
    pub head_ref_name: String,
    pub author: String,
    pub is_draft: bool,
}

/// List open PRs for a repository using the GitHub CLI.
pub fn list_open_prs(repo_root: &Path) -> Result<Vec<PrListEntry>> {
    #[derive(Deserialize)]
    struct RawPr {
        number: u32,
        title: String,
        #[serde(rename = "headRefName")]
        head_ref_name: String,
        #[serde(rename = "isDraft")]
        is_draft: bool,
        author: Author,
    }

    let output = Command::new("gh")
        .current_dir(repo_root)
        .args([
            "pr",
            "list",
            "--state",
            "open",
            "--json",
            "number,title,headRefName,isDraft,author",
            "--limit",
            "100",
        ])
        .output();

    let output = match output {
        Ok(out) => out,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(anyhow!("GitHub CLI (gh) not found"));
        }
        Err(e) => return Err(e).context("Failed to execute gh command"),
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!("gh pr list failed: {}", stderr.trim()));
    }

    let raw: Vec<RawPr> =
        serde_json::from_slice(&output.stdout).context("Failed to parse gh pr list output")?;

    Ok(raw
        .into_iter()
        .map(|pr| PrListEntry {
            number: pr.number,
            title: pr.title,
            head_ref_name: pr.head_ref_name,
            author: pr.author.login,
            is_draft: pr.is_draft,
        })
        .collect())
}

/// Fetches pull request details using the GitHub CLI
pub fn get_pr_details(pr_number: u32) -> Result<PrDetails> {
    get_pr_details_in(None, pr_number)
}

/// Fetches pull request details using the GitHub CLI in a specific repository path
pub fn get_pr_details_in(repo_root: Option<&Path>, pr_number: u32) -> Result<PrDetails> {
    // Fetch PR details using gh CLI
    // Note: We don't pre-check with 'which' because it doesn't respect test PATH modifications
    let mut command = Command::new("gh");
    if let Some(path) = repo_root {
        command.current_dir(path);
    }
    let output = command
        .args([
            "pr",
            "view",
            &pr_number.to_string(),
            "--json",
            "headRefName,headRepositoryOwner,state,isDraft,title,author",
        ])
        .output();

    let output = match output {
        Ok(out) => out,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            debug!("github:gh CLI not found");
            return Err(anyhow!(
                "GitHub CLI (gh) is required for --pr. Install from https://cli.github.com"
            ));
        }
        Err(e) => {
            return Err(e).context("Failed to execute gh command");
        }
    };

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        debug!(pr = pr_number, stderr = %stderr, "github:pr view failed");
        return Err(anyhow!(
            "Failed to fetch PR #{}: {}",
            pr_number,
            stderr.trim()
        ));
    }

    let json_str = String::from_utf8(output.stdout).context("gh output is not valid UTF-8")?;

    let pr_details: PrDetails =
        serde_json::from_str(&json_str).context("Failed to parse gh JSON output")?;

    Ok(pr_details)
}

const PR_LIST_FIELDS_WITH_CHECKS: &str =
    "number,title,state,isDraft,headRefName,url,statusCheckRollup";
const PR_LIST_FIELDS: &str = "number,title,state,isDraft,headRefName,url";

fn run_pr_list(
    repo_root: Option<&Path>,
    args: &[&str],
    json_fields: &str,
) -> std::io::Result<std::process::Output> {
    let mut command = Command::new("gh");
    if let Some(path) = repo_root {
        command.current_dir(path);
    }
    command.args(args).args(["--json", json_fields]).output()
}

/// Internal struct for parsing batch PR list results
#[derive(Debug, Deserialize)]
struct PrBatchItem {
    number: u32,
    title: String,
    state: String,
    #[serde(rename = "isDraft")]
    is_draft: bool,
    #[serde(rename = "headRefName")]
    head_ref_name: String,
    url: String,
    #[serde(rename = "statusCheckRollup", default)]
    status_check_rollup: Vec<CheckRollupItem>,
}

/// Fetch all PRs for the repository containing `repo_root`.
pub fn list_prs_in(repo_root: Option<&Path>) -> Result<HashMap<String, PrSummary>> {
    let args = ["pr", "list", "--state", "all", "--limit", "200"];
    let output = run_pr_list(repo_root, &args, PR_LIST_FIELDS_WITH_CHECKS);

    let output = match output {
        Ok(out) if out.status.success() => out,
        Ok(out) => {
            let stderr = String::from_utf8_lossy(&out.stderr);
            debug!(stderr = %stderr, "github:pr list batch with checks failed, retrying without checks");
            match run_pr_list(repo_root, &args, PR_LIST_FIELDS) {
                Ok(retry) => retry,
                Err(e) => return Err(e).context("Failed to execute gh command"),
            }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            debug!("github:gh CLI not found, skipping PR lookup");
            return Ok(HashMap::new());
        }
        Err(e) => return Err(e).context("Failed to execute gh command"),
    };

    if !output.status.success() {
        debug!("github:pr list batch failed, treating as no PRs found");
        return Ok(HashMap::new());
    }

    let json_str = String::from_utf8(output.stdout).context("gh output is not valid UTF-8")?;

    let prs: Vec<PrBatchItem> =
        serde_json::from_str(&json_str).context("Failed to parse gh JSON output")?;

    let pr_map = prs
        .into_iter()
        .map(|pr| {
            (pr.head_ref_name, {
                let (checks, check_meta) = aggregate_checks(&pr.status_check_rollup);
                PrSummary {
                    number: pr.number,
                    title: pr.title,
                    state: pr.state,
                    is_draft: pr.is_draft,
                    checks,
                    check_meta,
                    url: Some(pr.url),
                }
            })
        })
        .collect();

    Ok(pr_map)
}

/// Fetch GitHub state for specific branches using a single GraphQL query.
/// Falls back to per-branch PR calls if GraphQL fails.
pub fn list_branch_summaries(
    repo_root: &Path,
    branches: &[String],
) -> Result<HashMap<String, BranchSummary>> {
    if branches.is_empty() {
        return Ok(HashMap::new());
    }

    match list_branch_summaries_graphql(repo_root, branches) {
        Ok(map) => Ok(map),
        Err(e) => {
            debug!("github:graphql batch failed, falling back to per-branch REST: {e}");
            list_prs_for_branches_rest(repo_root, branches).map(|prs| {
                prs.into_iter()
                    .map(|(branch, pr)| {
                        let checks = pr.checks.clone().map(|state| CheckSummary {
                            state,
                            meta: pr.check_meta.clone(),
                        });
                        (
                            branch,
                            BranchSummary {
                                pr: Some(pr),
                                checks,
                            },
                        )
                    })
                    .collect()
            })
        }
    }
}

#[derive(Debug, Deserialize)]
struct GraphqlError {
    message: String,
    #[serde(default)]
    path: Vec<serde_json::Value>,
}

#[derive(Debug, Deserialize)]
struct GraphqlPrConnection {
    nodes: Vec<GraphqlPrNode>,
}

#[derive(Debug, Deserialize)]
struct GraphqlBranchRef {
    target: Option<GraphqlCommit>,
}

#[derive(Debug, Deserialize)]
struct GraphqlPrNode {
    number: u32,
    title: String,
    state: String,
    #[serde(rename = "isDraft")]
    is_draft: bool,
    url: String,
    commits: GraphqlCommits,
}

#[derive(Debug, Deserialize)]
struct GraphqlCommits {
    nodes: Vec<GraphqlCommitNode>,
}

#[derive(Debug, Deserialize)]
struct GraphqlCommitNode {
    commit: GraphqlCommit,
}

#[derive(Debug, Deserialize)]
struct GraphqlCommit {
    #[serde(rename = "statusCheckRollup")]
    status_check_rollup: Option<GraphqlCheckRollup>,
}

fn check_items_for_commit(commit: &GraphqlCommit) -> Vec<CheckRollupItem> {
    commit
        .status_check_rollup
        .as_ref()
        .map(|rollup| {
            rollup
                .contexts
                .nodes
                .iter()
                .map(GraphqlCheckNode::to_rollup_item)
                .collect()
        })
        .unwrap_or_default()
}

#[derive(Debug, Deserialize)]
struct GraphqlCheckRollup {
    contexts: GraphqlCheckContexts,
}

#[derive(Debug, Deserialize)]
struct GraphqlCheckContexts {
    nodes: Vec<GraphqlCheckNode>,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "__typename")]
enum GraphqlCheckNode {
    CheckRun {
        name: Option<String>,
        status: Option<String>,
        conclusion: Option<String>,
        #[serde(rename = "startedAt")]
        started_at: Option<String>,
    },
    StatusContext {
        context: Option<String>,
        state: Option<String>,
        #[serde(rename = "createdAt")]
        created_at: Option<String>,
    },
}

impl GraphqlCheckNode {
    fn to_rollup_item(&self) -> CheckRollupItem {
        match self {
            GraphqlCheckNode::CheckRun {
                name,
                status,
                conclusion,
                started_at,
            } => CheckRollupItem {
                status: status.clone(),
                conclusion: conclusion.clone(),
                name: name.clone(),
                started_at: started_at.clone(),
            },
            GraphqlCheckNode::StatusContext {
                context,
                state,
                created_at,
            } => CheckRollupItem {
                status: state.clone(),
                conclusion: None,
                name: context.clone(),
                started_at: created_at.clone(),
            },
        }
    }
}

/// Repository context resolved by `gh`, matching its own repo detection logic
/// (respects `gh repo set-default`, fork conventions, GHES hosts).
#[derive(Debug, Deserialize)]
struct RepoContext {
    name: String,
    owner: RepositoryOwner,
    url: String,
}

type ResolvedRepoContext = (String, String, String);
static REPO_CONTEXT_CACHE: OnceLock<Mutex<HashMap<PathBuf, ResolvedRepoContext>>> = OnceLock::new();

fn repo_context_cache_key(repo_root: &Path) -> PathBuf {
    crate::git::get_git_common_dir_in(Some(repo_root))
        .ok()
        .and_then(|path| path.canonicalize().ok().or(Some(path)))
        .unwrap_or_else(|| repo_root.to_path_buf())
}

/// Get the repo owner, name, and API hostname using `gh repo view`.
/// This delegates repo resolution to `gh` so it works correctly with forks,
/// `gh repo set-default`, and GitHub Enterprise.
fn get_repo_context(repo_root: &Path) -> Result<ResolvedRepoContext> {
    let cache_key = repo_context_cache_key(repo_root);
    let cache = REPO_CONTEXT_CACHE.get_or_init(|| Mutex::new(HashMap::new()));
    if let Ok(cache) = cache.lock()
        && let Some(context) = cache.get(&cache_key)
    {
        return Ok(context.clone());
    }

    let output = Command::new("gh")
        .current_dir(repo_root)
        .args(["repo", "view", "--json", "owner,name,url"])
        .output()
        .context("Failed to run gh repo view")?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(anyhow!("gh repo view failed: {stderr}"));
    }

    let ctx: RepoContext =
        serde_json::from_slice(&output.stdout).context("Failed to parse gh repo view output")?;

    // Extract hostname from the repo URL for GHES support
    let hostname = ctx
        .url
        .strip_prefix("https://")
        .or_else(|| ctx.url.strip_prefix("http://"))
        .and_then(|s| s.split('/').next())
        .unwrap_or("github.com")
        .to_string();

    let context = (ctx.owner.login, ctx.name, hostname);
    if let Ok(mut cache) = cache.lock() {
        cache.insert(cache_key, context.clone());
    }
    Ok(context)
}

const MAX_BATCH_BRANCHES: usize = 32;
const MAX_BATCH_BODY_BYTES: usize = 64 * 1024;

struct LocalQuery {
    repo_key: PathBuf,
    branches: BTreeSet<String>,
}

struct RemoteQuery {
    hostname: String,
    owner: String,
    name: String,
    branches: Vec<String>,
    locals: Vec<LocalQuery>,
}

type RemoteQueryOutcome = HashMap<String, BranchSummary>;

#[derive(Debug, Deserialize)]
struct BatchGraphqlResponse {
    data: Option<HashMap<String, serde_json::Value>>,
    #[serde(default)]
    errors: Vec<GraphqlError>,
}

struct GraphqlCommandResponse {
    success: bool,
    response: BatchGraphqlResponse,
}

/// Fetch sidebar GitHub state with one bounded GraphQL query per hostname chunk.
pub fn list_branch_summaries_batch(
    requests: Vec<BranchQueryRequest>,
) -> HashMap<PathBuf, BranchQueryOutcome> {
    let mut remotes: BTreeMap<(String, String, String), RemoteQuery> = BTreeMap::new();

    for request in requests {
        let requested: BTreeSet<String> = request.branches.into_iter().collect();
        let Ok((owner, name, hostname)) = get_repo_context(&request.repo_root) else {
            continue;
        };
        let key = (
            hostname.to_ascii_lowercase(),
            owner.to_ascii_lowercase(),
            name.to_ascii_lowercase(),
        );
        let remote = remotes.entry(key).or_insert_with(|| RemoteQuery {
            hostname,
            owner,
            name,
            branches: Vec::new(),
            locals: Vec::new(),
        });
        remote.locals.push(LocalQuery {
            repo_key: request.repo_key,
            branches: requested.clone(),
        });
        remote.branches.extend(requested);
    }

    let mut by_host: BTreeMap<String, Vec<RemoteQuery>> = BTreeMap::new();
    for mut remote in remotes.into_values() {
        remote.branches.sort();
        remote.branches.dedup();
        by_host
            .entry(remote.hostname.to_ascii_lowercase())
            .or_default()
            .push(remote);
    }

    let mut outcomes = HashMap::new();
    for remotes in by_host.into_values() {
        for chunk in pack_remote_queries(remotes) {
            let remote_outcomes = execute_remote_chunk(&chunk);
            for (remote, remote_outcome) in chunk.into_iter().zip(remote_outcomes) {
                let Some(remote_outcome) = remote_outcome else {
                    continue;
                };
                for local in remote.locals {
                    let answered: HashMap<String, BranchSummary> = remote_outcome
                        .iter()
                        .filter(|(branch, _)| local.branches.contains(*branch))
                        .map(|(branch, summary)| (branch.clone(), summary.clone()))
                        .collect();
                    if !answered.is_empty() {
                        outcomes.insert(
                            local.repo_key,
                            BranchQueryOutcome {
                                requested: local.branches.into_iter().collect(),
                                answered,
                            },
                        );
                    }
                }
            }
        }
    }
    outcomes
}

fn pack_remote_queries(remotes: Vec<RemoteQuery>) -> Vec<Vec<RemoteQuery>> {
    let mut chunks = Vec::new();
    let mut chunk = Vec::new();
    let mut branch_count = 0usize;

    for remote in remotes {
        let remote_branches = remote.branches.len();
        chunk.push(remote);
        let candidate_bytes = build_batch_body(&chunk)
            .map(|body| body.len())
            .unwrap_or(usize::MAX);
        if chunk.len() > 1
            && (branch_count + remote_branches > MAX_BATCH_BRANCHES
                || candidate_bytes > MAX_BATCH_BODY_BYTES)
        {
            let remote = chunk.pop().expect("candidate was just pushed");
            chunks.push(std::mem::take(&mut chunk));
            branch_count = 0;
            chunk.push(remote);
        }
        branch_count += remote_branches;
    }
    if !chunk.is_empty() {
        chunks.push(chunk);
    }
    chunks
}

fn build_batch_body(remotes: &[RemoteQuery]) -> Result<Vec<u8>> {
    let mut declarations = Vec::new();
    let mut repositories = Vec::new();
    let mut variables = serde_json::Map::new();

    for (repo_index, remote) in remotes.iter().enumerate() {
        let owner_var = format!("owner_{repo_index}");
        let name_var = format!("name_{repo_index}");
        declarations.push(format!("${owner_var}: String!"));
        declarations.push(format!("${name_var}: String!"));
        variables.insert(owner_var.clone(), remote.owner.clone().into());
        variables.insert(name_var.clone(), remote.name.clone().into());

        let mut branches = Vec::new();
        for (branch_index, branch) in remote.branches.iter().enumerate() {
            let head_var = format!("head_{repo_index}_{branch_index}");
            let ref_var = format!("qualified_{repo_index}_{branch_index}");
            declarations.push(format!("${head_var}: String!"));
            declarations.push(format!("${ref_var}: String!"));
            variables.insert(head_var.clone(), branch.clone().into());
            variables.insert(ref_var.clone(), format!("refs/heads/{branch}").into());
            branches.push(format!(
                r#"    pr_r{repo_index}_b{branch_index}: pullRequests(headRefName: ${head_var}, first: 1, states: [OPEN, MERGED, CLOSED], orderBy: {{field: CREATED_AT, direction: DESC}}) {{
      nodes {{
        number title state isDraft url
        commits(last: 1) {{ nodes {{ commit {{ statusCheckRollup {{ contexts(first: 100) {{
          nodes {{ __typename ... on CheckRun {{ name status conclusion startedAt }} ... on StatusContext {{ context state createdAt }} }}
        }} }} }} }} }}
      }}
    }}
    ref_r{repo_index}_b{branch_index}: ref(qualifiedName: ${ref_var}) {{
      target {{ ... on Commit {{ statusCheckRollup {{ contexts(first: 100) {{
        nodes {{ __typename ... on CheckRun {{ name status conclusion startedAt }} ... on StatusContext {{ context state createdAt }} }}
      }} }} }} }}
    }}"#
            ));
        }
        repositories.push(format!(
            "  repo_{repo_index}: repository(owner: ${owner_var}, name: ${name_var}) {{\n{}\n  }}",
            branches.join("\n")
        ));
    }

    let query = format!(
        "query({}) {{\n{}\n}}",
        declarations.join(", "),
        repositories.join("\n")
    );
    serde_json::to_vec(&serde_json::json!({
        "query": query,
        "variables": variables,
    }))
    .context("JSON serialize")
}

fn run_graphql(hostname: &str, body: &[u8]) -> Result<GraphqlCommandResponse> {
    let mut child = Command::new("gh")
        .args(["api", "graphql", "--hostname", hostname, "--input", "-"])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .context("Failed to spawn gh api graphql")?;

    child
        .stdin
        .take()
        .expect("stdin was piped")
        .write_all(body)
        .context("Failed to write to gh stdin")?;
    let output = child
        .wait_with_output()
        .context("Failed to wait for gh api graphql")?;

    let response = serde_json::from_slice(&output.stdout).with_context(|| {
        format!(
            "gh api graphql returned invalid JSON with status {}",
            output.status
        )
    })?;
    Ok(GraphqlCommandResponse {
        success: output.status.success(),
        response,
    })
}

fn execute_remote_chunk(chunk: &[RemoteQuery]) -> Vec<Option<RemoteQueryOutcome>> {
    execute_remote_chunk_with(chunk, &mut run_graphql)
}

fn execute_remote_chunk_with(
    chunk: &[RemoteQuery],
    run: &mut impl FnMut(&str, &[u8]) -> Result<GraphqlCommandResponse>,
) -> Vec<Option<RemoteQueryOutcome>> {
    match execute_remote_chunk_once(chunk, run) {
        Ok(outcomes) => outcomes,
        Err(_) if chunk.len() > 1 => chunk
            .iter()
            .map(|remote| {
                execute_remote_chunk_once(std::slice::from_ref(remote), run)
                    .ok()
                    .and_then(|mut outcomes| outcomes.pop().flatten())
            })
            .collect(),
        Err(_) => vec![None],
    }
}

fn execute_remote_chunk_once(
    chunk: &[RemoteQuery],
    run: &mut impl FnMut(&str, &[u8]) -> Result<GraphqlCommandResponse>,
) -> Result<Vec<Option<RemoteQueryOutcome>>> {
    let body = build_batch_body(chunk)?;
    let response = run(&chunk[0].hostname, &body)?.response;
    let aliases: HashSet<String> = (0..chunk.len())
        .map(|index| format!("repo_{index}"))
        .collect();
    if response.errors.iter().any(|error| {
        error
            .path
            .first()
            .and_then(serde_json::Value::as_str)
            .is_none_or(|alias| !aliases.contains(alias))
    }) {
        return Err(anyhow!("GraphQL response contained an unscoped error"));
    }
    let data = response
        .data
        .ok_or_else(|| anyhow!("No data in GraphQL response"))?;
    Ok(chunk
        .iter()
        .enumerate()
        .map(|(repo_index, remote)| parse_remote_query(&data, &response.errors, repo_index, remote))
        .collect())
}

fn parse_remote_query(
    data: &HashMap<String, serde_json::Value>,
    errors: &[GraphqlError],
    repo_index: usize,
    remote: &RemoteQuery,
) -> Option<RemoteQueryOutcome> {
    let repo_alias = format!("repo_{repo_index}");
    let repo_value = data.get(&repo_alias)?;
    if repo_value.is_null()
        || errors.iter().any(|error| {
            error.path.len() == 1
                && error.path.first().and_then(serde_json::Value::as_str)
                    == Some(repo_alias.as_str())
        })
    {
        return None;
    }
    let repo = repo_value.as_object()?;
    let mut answered = HashMap::new();

    for (branch_index, branch) in remote.branches.iter().enumerate() {
        let pr_alias = format!("pr_r{repo_index}_b{branch_index}");
        let ref_alias = format!("ref_r{repo_index}_b{branch_index}");
        let branch_error = errors.iter().any(|error| {
            error.path.len() >= 2
                && error.path.first().and_then(serde_json::Value::as_str)
                    == Some(repo_alias.as_str())
                && error
                    .path
                    .get(1)
                    .and_then(serde_json::Value::as_str)
                    .is_some_and(|alias| alias == pr_alias || alias == ref_alias)
        });
        if branch_error {
            continue;
        }
        let (Some(pr_value), Some(ref_value)) = (repo.get(&pr_alias), repo.get(&ref_alias)) else {
            continue;
        };
        if let Ok(summary) = parse_branch_summary_values(pr_value.clone(), ref_value.clone()) {
            answered.insert(branch.clone(), summary);
        }
    }

    Some(answered)
}

fn parse_branch_summary_values(
    pr_value: serde_json::Value,
    ref_value: serde_json::Value,
) -> Result<BranchSummary> {
    let connection: GraphqlPrConnection =
        serde_json::from_value(pr_value).context("Failed to parse GraphQL PR data")?;
    let branch_ref: Option<GraphqlBranchRef> =
        serde_json::from_value(ref_value).context("Failed to parse GraphQL ref data")?;
    let pr = connection.nodes.into_iter().next().map(|node| {
        let check_items = node
            .commits
            .nodes
            .first()
            .map(|node| check_items_for_commit(&node.commit))
            .unwrap_or_default();
        let (checks, check_meta) = aggregate_checks(&check_items);
        PrSummary {
            number: node.number,
            title: node.title,
            state: node.state,
            is_draft: node.is_draft,
            checks,
            check_meta,
            url: Some(node.url),
        }
    });
    let branch_checks = branch_ref
        .and_then(|branch_ref| branch_ref.target)
        .and_then(|commit| summarize_checks(&check_items_for_commit(&commit)));
    let checks = pr
        .as_ref()
        .and_then(|pr| {
            pr.checks.clone().map(|state| CheckSummary {
                state,
                meta: pr.check_meta.clone(),
            })
        })
        .or(branch_checks);
    Ok(BranchSummary { pr, checks })
}

/// Fetch branch and PR status for multiple branches in one GraphQL API call.
fn list_branch_summaries_graphql(
    repo_root: &Path,
    branches: &[String],
) -> Result<HashMap<String, BranchSummary>> {
    let (owner, name, hostname) = get_repo_context(repo_root)?;
    let remote = RemoteQuery {
        hostname,
        owner,
        name,
        branches: branches.to_vec(),
        locals: Vec::new(),
    };
    let body = build_batch_body(std::slice::from_ref(&remote))?;
    let command = run_graphql(&remote.hostname, &body)?;
    if !command.success {
        return Err(anyhow!("gh api graphql failed"));
    }
    if !command.response.errors.is_empty() {
        let messages: Vec<&str> = command
            .response
            .errors
            .iter()
            .map(|error| error.message.as_str())
            .collect();
        return Err(anyhow!("GraphQL errors: {}", messages.join("; ")));
    }
    let data = command
        .response
        .data
        .ok_or_else(|| anyhow!("No data in GraphQL response"))?;
    let summaries = parse_remote_query(&data, &[], 0, &remote)
        .ok_or_else(|| anyhow!("Missing repository data in GraphQL response"))?;
    if branches
        .iter()
        .any(|branch| !summaries.contains_key(branch))
    {
        return Err(anyhow!("Missing branch data in GraphQL response"));
    }
    Ok(summaries)
}

/// Fallback: fetch PR status one branch at a time using REST-style gh pr list.
fn list_prs_for_branches_rest(
    repo_root: &Path,
    branches: &[String],
) -> Result<HashMap<String, PrSummary>> {
    let mut map = HashMap::new();

    for branch in branches {
        let args = [
            "pr", "list", "--head", branch, "--state", "all", "--limit", "1",
        ];
        let output = match run_pr_list(Some(repo_root), &args, PR_LIST_FIELDS_WITH_CHECKS) {
            Ok(output) if output.status.success() => output,
            Ok(output) => {
                let stderr = String::from_utf8_lossy(&output.stderr);
                debug!(branch = branch, stderr = %stderr, "github:branch pr list with checks failed, retrying without checks");
                match run_pr_list(Some(repo_root), &args, PR_LIST_FIELDS) {
                    Ok(output) => output,
                    Err(_) => continue,
                }
            }
            Err(_) => continue,
        };

        if !output.status.success() {
            continue;
        }

        let prs: Vec<PrBatchItem> = match serde_json::from_slice(&output.stdout) {
            Ok(prs) => prs,
            Err(_) => continue,
        };

        if let Some(pr) = prs.into_iter().next() {
            let (checks, check_meta) = aggregate_checks(&pr.status_check_rollup);
            map.insert(
                pr.head_ref_name,
                PrSummary {
                    number: pr.number,
                    title: pr.title,
                    state: pr.state,
                    is_draft: pr.is_draft,
                    checks,
                    check_meta,
                    url: Some(pr.url),
                },
            );
        }
    }

    Ok(map)
}

/// Get the path to the PR status cache file
fn get_pr_cache_path() -> Result<PathBuf> {
    let cache_dir = crate::xdg::cache_dir()?;
    std::fs::create_dir_all(&cache_dir)?;
    Ok(cache_dir.join("pr_status_cache.json"))
}

/// Load the PR status cache from disk
pub fn load_pr_cache() -> HashMap<PathBuf, HashMap<String, PrSummary>> {
    if let Ok(path) = get_pr_cache_path()
        && path.exists()
        && let Ok(content) = std::fs::read_to_string(&path)
    {
        return serde_json::from_str(&content).unwrap_or_default();
    }
    HashMap::new()
}

/// Save the PR status cache to disk
pub fn save_pr_cache(statuses: &HashMap<PathBuf, HashMap<String, PrSummary>>) {
    let Ok(path) = get_pr_cache_path() else {
        return;
    };
    let lock_path = path.with_extension("json.lock");
    let lock_file = match OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
    {
        Ok(file) => file,
        Err(_) => return,
    };
    let Ok(_lock) = Flock::lock(lock_file, FlockArg::LockExclusive).map_err(|(_file, errno)| errno)
    else {
        return;
    };

    let mut merged = load_pr_cache();
    for (repo, prs) in statuses {
        if prs.is_empty() {
            merged.remove(repo);
        } else {
            merged.insert(repo.clone(), prs.clone());
        }
    }
    let Ok(content) = serde_json::to_string(&merged) else {
        return;
    };
    let _ = write_atomic(&path, content.as_bytes());
}

fn get_check_cache_path() -> Result<PathBuf> {
    let cache_dir = crate::xdg::cache_dir()?;
    std::fs::create_dir_all(&cache_dir)?;
    Ok(cache_dir.join("check_status_cache.json"))
}

pub fn load_check_cache() -> HashMap<PathBuf, HashMap<String, CheckSummary>> {
    if let Ok(path) = get_check_cache_path()
        && path.exists()
        && let Ok(content) = std::fs::read_to_string(&path)
    {
        return serde_json::from_str(&content).unwrap_or_default();
    }
    HashMap::new()
}

pub fn save_check_cache(statuses: &HashMap<PathBuf, HashMap<String, CheckSummary>>) {
    let Ok(path) = get_check_cache_path() else {
        return;
    };
    let lock_path = path.with_extension("json.lock");
    let lock_file = match OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .truncate(false)
        .open(&lock_path)
    {
        Ok(file) => file,
        Err(_) => return,
    };
    let Ok(_lock) = Flock::lock(lock_file, FlockArg::LockExclusive).map_err(|(_file, errno)| errno)
    else {
        return;
    };

    let mut merged = load_check_cache();
    for (repo, checks) in statuses {
        if checks.is_empty() {
            merged.remove(repo);
        } else {
            merged.insert(repo.clone(), checks.clone());
        }
    }
    let Ok(content) = serde_json::to_string(&merged) else {
        return;
    };
    let _ = write_atomic(&path, content.as_bytes());
}

#[cfg(test)]
mod tests {
    use super::*;

    fn check_item(status: Option<&str>, conclusion: Option<&str>) -> CheckRollupItem {
        CheckRollupItem {
            status: status.map(String::from),
            conclusion: conclusion.map(String::from),
            name: None,
            started_at: None,
        }
    }

    #[test]
    fn aggregate_checks_empty() {
        assert_eq!(aggregate_checks(&[]).0, None);
    }

    #[test]
    fn aggregate_checks_all_success() {
        let checks = vec![
            check_item(Some("COMPLETED"), Some("SUCCESS")),
            check_item(Some("COMPLETED"), Some("SUCCESS")),
        ];
        assert_eq!(aggregate_checks(&checks).0, Some(CheckState::Success));
    }

    #[test]
    fn aggregate_checks_with_failure() {
        let checks = vec![
            check_item(Some("COMPLETED"), Some("SUCCESS")),
            check_item(Some("COMPLETED"), Some("FAILURE")),
        ];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Failure {
                passed: 1,
                total: 2
            })
        );
    }

    #[test]
    fn aggregate_checks_with_pending() {
        let checks = vec![
            check_item(Some("COMPLETED"), Some("SUCCESS")),
            check_item(Some("IN_PROGRESS"), None),
        ];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Pending {
                passed: 1,
                total: 2
            })
        );
    }

    #[test]
    fn aggregate_checks_failure_takes_priority_over_pending() {
        let checks = vec![
            check_item(Some("COMPLETED"), Some("SUCCESS")),
            check_item(Some("COMPLETED"), Some("FAILURE")),
            check_item(Some("IN_PROGRESS"), None),
        ];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Failure {
                passed: 1,
                total: 3
            })
        );
    }

    #[test]
    fn aggregate_checks_status_context_success() {
        // StatusContext uses "state" field (aliased to status) with values like SUCCESS
        let checks = vec![check_item(Some("SUCCESS"), None)];
        assert_eq!(aggregate_checks(&checks).0, Some(CheckState::Success));
    }

    #[test]
    fn aggregate_checks_status_context_pending() {
        let checks = vec![check_item(Some("PENDING"), None)];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Pending {
                passed: 0,
                total: 1
            })
        );
    }

    #[test]
    fn aggregate_checks_status_context_error() {
        let checks = vec![check_item(Some("ERROR"), None)];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Failure {
                passed: 0,
                total: 1
            })
        );
    }

    #[test]
    fn aggregate_checks_all_skipped_returns_success() {
        let checks = vec![
            check_item(Some("COMPLETED"), Some("SKIPPED")),
            check_item(Some("COMPLETED"), Some("NEUTRAL")),
        ];
        assert_eq!(aggregate_checks(&checks).0, Some(CheckState::Success));
    }

    #[test]
    fn aggregate_checks_skipped_not_counted_in_total() {
        let checks = vec![
            check_item(Some("COMPLETED"), Some("SUCCESS")),
            check_item(Some("COMPLETED"), Some("SKIPPED")),
            check_item(Some("IN_PROGRESS"), None),
        ];
        // Only SUCCESS and IN_PROGRESS count toward total (2), not SKIPPED
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Pending {
                passed: 1,
                total: 2
            })
        );
    }

    #[test]
    fn aggregate_checks_cancelled_is_failure() {
        let checks = vec![check_item(Some("COMPLETED"), Some("CANCELLED"))];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Failure {
                passed: 0,
                total: 1
            })
        );
    }

    #[test]
    fn aggregate_checks_timed_out_is_failure() {
        let checks = vec![check_item(Some("COMPLETED"), Some("TIMED_OUT"))];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Failure {
                passed: 0,
                total: 1
            })
        );
    }

    #[test]
    fn aggregate_checks_mixed_check_types() {
        // Mix of CheckRun (status/conclusion) and StatusContext (state only)
        let checks = vec![
            check_item(Some("COMPLETED"), Some("SUCCESS")), // CheckRun success
            check_item(Some("IN_PROGRESS"), None),          // CheckRun pending
            check_item(Some("SUCCESS"), None),              // StatusContext success
        ];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Pending {
                passed: 2,
                total: 3
            })
        );
    }

    #[test]
    fn aggregate_checks_queued_is_pending() {
        let checks = vec![check_item(Some("QUEUED"), None)];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Pending {
                passed: 0,
                total: 1
            })
        );
    }

    #[test]
    fn aggregate_checks_waiting_is_pending() {
        let checks = vec![check_item(Some("WAITING"), None)];
        assert_eq!(
            aggregate_checks(&checks).0,
            Some(CheckState::Pending {
                passed: 0,
                total: 1
            })
        );
    }

    #[test]
    fn graphql_check_node_to_rollup_item_check_run() {
        let node = GraphqlCheckNode::CheckRun {
            name: Some("build".to_string()),
            status: Some("COMPLETED".to_string()),
            conclusion: Some("SUCCESS".to_string()),
            started_at: Some("2026-03-24T14:00:00Z".to_string()),
        };
        let item = node.to_rollup_item();
        assert_eq!(item.status.as_deref(), Some("COMPLETED"));
        assert_eq!(item.conclusion.as_deref(), Some("SUCCESS"));
        assert_eq!(item.name.as_deref(), Some("build"));
        assert_eq!(item.started_at.as_deref(), Some("2026-03-24T14:00:00Z"));
    }

    #[test]
    fn graphql_check_node_to_rollup_item_status_context() {
        let node = GraphqlCheckNode::StatusContext {
            context: Some("ci/circleci".to_string()),
            state: Some("PENDING".to_string()),
            created_at: Some("2026-03-24T14:00:00Z".to_string()),
        };
        let item = node.to_rollup_item();
        assert_eq!(item.status.as_deref(), Some("PENDING"));
        assert_eq!(item.conclusion, None);
        assert_eq!(item.name.as_deref(), Some("ci/circleci"));
        assert_eq!(item.started_at.as_deref(), Some("2026-03-24T14:00:00Z"));
    }

    #[test]
    fn main_branch_checks_only_display_failures() {
        let success = CheckSummary {
            state: CheckState::Success,
            meta: None,
        };
        let pending = CheckSummary {
            state: CheckState::Pending {
                passed: 1,
                total: 2,
            },
            meta: None,
        };
        let failure = CheckSummary {
            state: CheckState::Failure {
                passed: 1,
                total: 2,
            },
            meta: None,
        };

        assert!(!success.should_display_for_branch("main"));
        assert!(!pending.should_display_for_branch("main"));
        assert!(failure.should_display_for_branch("main"));
        assert!(!success.should_display_for_branch("master"));
        assert!(success.should_display_for_branch("feature"));
        assert!(pending.should_display_for_branch("feature"));
    }

    #[test]
    fn parses_branch_checks_without_pr() {
        let repository = serde_json::from_value(serde_json::json!({
            "pr_br0_feature": { "nodes": [] },
            "ref_br0_feature": {
                "target": {
                    "statusCheckRollup": {
                        "contexts": {
                            "nodes": [
                                {
                                    "__typename": "CheckRun",
                                    "name": "build",
                                    "status": "COMPLETED",
                                    "conclusion": "SUCCESS",
                                    "startedAt": "2026-03-24T14:00:00Z"
                                }
                            ]
                        }
                    }
                }
            }
        }))
        .unwrap();

        let mut repository: HashMap<String, serde_json::Value> = repository;
        let summary = parse_branch_summary_values(
            repository.remove("pr_br0_feature").unwrap(),
            repository.remove("ref_br0_feature").unwrap(),
        )
        .unwrap();

        assert!(summary.pr.is_none());
        assert_eq!(
            summary.checks.as_ref().map(|checks| &checks.state),
            Some(&CheckState::Success)
        );
    }

    #[test]
    fn pr_checks_take_precedence_over_branch_checks() {
        let repository = serde_json::from_value(serde_json::json!({
            "pr_br0_feature": {
                "nodes": [{
                    "number": 42,
                    "title": "Feature",
                    "state": "OPEN",
                    "isDraft": false,
                    "url": "https://github.com/owner/repo/pull/42",
                    "commits": {
                        "nodes": [{
                            "commit": {
                                "statusCheckRollup": {
                                    "contexts": {
                                        "nodes": [{
                                            "__typename": "CheckRun",
                                            "name": "test",
                                            "status": "COMPLETED",
                                            "conclusion": "FAILURE",
                                            "startedAt": null
                                        }]
                                    }
                                }
                            }
                        }]
                    }
                }]
            },
            "ref_br0_feature": {
                "target": {
                    "statusCheckRollup": {
                        "contexts": {
                            "nodes": [{
                                "__typename": "CheckRun",
                                "name": "build",
                                "status": "COMPLETED",
                                "conclusion": "SUCCESS",
                                "startedAt": null
                            }]
                        }
                    }
                }
            }
        }))
        .unwrap();

        let mut repository: HashMap<String, serde_json::Value> = repository;
        let summary = parse_branch_summary_values(
            repository.remove("pr_br0_feature").unwrap(),
            repository.remove("ref_br0_feature").unwrap(),
        )
        .unwrap();

        assert_eq!(summary.pr.as_ref().map(|pr| pr.number), Some(42));
        assert_eq!(
            summary.checks.as_ref().map(|checks| &checks.state),
            Some(&CheckState::Failure {
                passed: 0,
                total: 1,
            })
        );
    }

    #[test]
    fn parse_github_timestamp_valid() {
        assert_eq!(
            parse_github_timestamp("2026-03-24T14:02:00Z"),
            Some(1774360920)
        );
        // Unix epoch
        assert_eq!(parse_github_timestamp("1970-01-01T00:00:00Z"), Some(0));
    }

    #[test]
    fn parse_github_timestamp_invalid() {
        assert_eq!(parse_github_timestamp(""), None);
        assert_eq!(parse_github_timestamp("not a date"), None);
        assert_eq!(parse_github_timestamp("2026-13-01T00:00:00Z"), None);
    }

    #[test]
    fn aggregate_checks_captures_failing_name() {
        let checks = vec![
            CheckRollupItem {
                status: Some("COMPLETED".into()),
                conclusion: Some("SUCCESS".into()),
                name: Some("build".into()),
                started_at: None,
            },
            CheckRollupItem {
                status: Some("COMPLETED".into()),
                conclusion: Some("FAILURE".into()),
                name: Some("lint-check".into()),
                started_at: None,
            },
        ];
        let (state, meta) = aggregate_checks(&checks);
        assert_eq!(
            state,
            Some(CheckState::Failure {
                passed: 1,
                total: 2
            })
        );
        assert_eq!(
            meta.as_ref().and_then(|m| m.failing_name.as_deref()),
            Some("lint-check")
        );
    }

    fn remote_query(name: &str, branches: Vec<String>) -> RemoteQuery {
        RemoteQuery {
            hostname: "github.com".to_string(),
            owner: "owner".to_string(),
            name: name.to_string(),
            branches,
            locals: Vec::new(),
        }
    }

    #[test]
    fn batch_query_uses_variables_for_repository_and_branch_values() {
        let branch = "feat/quote-\"-line\n-unicode-雪".to_string();
        let body = build_batch_body(&[remote_query("repo", vec![branch.clone()])]).unwrap();
        let body: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let query = body["query"].as_str().unwrap();

        assert!(!query.contains(&branch));
        assert_eq!(body["variables"]["head_0_0"], branch);
        assert_eq!(
            body["variables"]["qualified_0_0"],
            "refs/heads/feat/quote-\"-line\n-unicode-雪"
        );
    }

    #[test]
    fn batch_packing_limits_total_branches() {
        let remotes = (0..33)
            .map(|index| remote_query(&format!("repo-{index}"), vec!["main".to_string()]))
            .collect();
        let chunks = pack_remote_queries(remotes);

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].len(), 32);
        assert_eq!(chunks[1].len(), 1);
    }

    #[test]
    fn batch_packing_keeps_oversized_repository_atomic() {
        let branches = (0..(MAX_BATCH_BRANCHES + 8))
            .map(|index| format!("branch-{index}"))
            .collect();
        let chunks = pack_remote_queries(vec![
            remote_query("large", branches),
            remote_query("next", vec!["main".to_string()]),
        ]);

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].len(), 1);
        assert_eq!(chunks[0][0].branches.len(), MAX_BATCH_BRANCHES + 8);
        assert_eq!(chunks[1][0].name, "next");
    }

    #[test]
    fn batch_packing_limits_serialized_body_size() {
        let long_branch = "x".repeat(MAX_BATCH_BODY_BYTES);
        let chunks = pack_remote_queries(vec![
            remote_query("first", vec![long_branch.clone()]),
            remote_query("second", vec![long_branch]),
        ]);

        assert_eq!(chunks.len(), 2);
        assert_eq!(chunks[0].len(), 1);
        assert_eq!(chunks[1].len(), 1);
    }

    #[test]
    fn unscoped_batch_failure_retries_each_repository_once() {
        let remotes = vec![
            remote_query("one", vec!["main".to_string()]),
            remote_query("two", vec!["main".to_string()]),
            remote_query("three", vec!["main".to_string()]),
        ];
        let mut calls = 0;
        let outcomes = execute_remote_chunk_with(&remotes, &mut |_hostname, body| {
            calls += 1;
            if calls == 1 {
                return Ok(GraphqlCommandResponse {
                    success: false,
                    response: BatchGraphqlResponse {
                        data: None,
                        errors: vec![GraphqlError {
                            message: "unscoped".to_string(),
                            path: Vec::new(),
                        }],
                    },
                });
            }
            let request: serde_json::Value = serde_json::from_slice(body).unwrap();
            assert_eq!(
                request["variables"]
                    .as_object()
                    .unwrap()
                    .keys()
                    .filter(|key| key.starts_with("owner_"))
                    .count(),
                1
            );
            Ok(GraphqlCommandResponse {
                success: true,
                response: BatchGraphqlResponse {
                    data: Some(HashMap::from([(
                        "repo_0".to_string(),
                        serde_json::json!({
                            "pr_r0_b0": { "nodes": [] },
                            "ref_r0_b0": null
                        }),
                    )])),
                    errors: Vec::new(),
                },
            })
        });

        assert_eq!(calls, 4);
        assert_eq!(outcomes.len(), 3);
        assert!(
            outcomes
                .into_iter()
                .all(|outcome| { outcome.is_some_and(|outcome| outcome.contains_key("main")) })
        );
    }

    #[test]
    fn batch_parser_accepts_sibling_data_on_unsuccessful_command() {
        let response: BatchGraphqlResponse = serde_json::from_value(serde_json::json!({
            "data": {
                "repo_0": null,
                "repo_1": {
                    "pr_r1_b0": { "nodes": [] },
                    "ref_r1_b0": null
                }
            },
            "errors": [
                { "message": "hidden", "path": ["repo_0"] }
            ]
        }))
        .unwrap();
        let remotes = [
            remote_query("hidden", vec!["main".to_string()]),
            remote_query("visible", vec!["feature".to_string()]),
        ];
        let mut response = Some(response);
        let outcomes = execute_remote_chunk_with(&remotes, &mut |_hostname, _body| {
            Ok(GraphqlCommandResponse {
                success: false,
                response: response.take().unwrap(),
            })
        });

        assert!(outcomes[0].is_none());
        assert_eq!(
            outcomes[1].as_ref().unwrap().get("feature"),
            Some(&BranchSummary {
                pr: None,
                checks: None,
            })
        );
    }

    #[test]
    fn batch_parser_leaves_nested_failed_branch_unanswered_and_keeps_siblings() {
        let successful_commit = serde_json::json!({
            "statusCheckRollup": {
                "contexts": {
                    "nodes": [{
                        "__typename": "CheckRun",
                        "name": "test",
                        "status": "COMPLETED",
                        "conclusion": "SUCCESS",
                        "startedAt": null
                    }]
                }
            }
        });
        for failed_alias in ["pr_r0_b0", "ref_r0_b0"] {
            let failed_commit = serde_json::json!({ "statusCheckRollup": null });
            let (pr_commit, ref_commit, path) = if failed_alias == "pr_r0_b0" {
                (
                    &failed_commit,
                    &successful_commit,
                    serde_json::json!([
                        "repo_0",
                        failed_alias,
                        "nodes",
                        0,
                        "commits",
                        "nodes",
                        0,
                        "commit",
                        "statusCheckRollup"
                    ]),
                )
            } else {
                (
                    &successful_commit,
                    &failed_commit,
                    serde_json::json!(["repo_0", failed_alias, "target", "statusCheckRollup"]),
                )
            };
            let response: BatchGraphqlResponse = serde_json::from_value(serde_json::json!({
                "data": {
                    "repo_0": {
                        "pr_r0_b0": { "nodes": [{
                            "number": 42,
                            "title": "Feature",
                            "state": "OPEN",
                            "isDraft": false,
                            "url": "https://github.com/owner/repo/pull/42",
                            "commits": { "nodes": [{ "commit": pr_commit }] }
                        }] },
                        "ref_r0_b0": { "target": ref_commit },
                        "pr_r0_b1": { "nodes": [] },
                        "ref_r0_b1": null
                    },
                    "repo_1": {
                        "pr_r1_b0": { "nodes": [] },
                        "ref_r1_b0": null
                    }
                },
                "errors": [{ "message": "rollup resolver failed", "path": path }]
            }))
            .unwrap();
            let remotes = [
                remote_query("one", vec!["failed".to_string(), "healthy".to_string()]),
                remote_query("two", vec!["healthy".to_string()]),
            ];
            let mut response = Some(response);
            let outcomes = execute_remote_chunk_with(&remotes, &mut |_, _| {
                Ok(GraphqlCommandResponse {
                    success: false,
                    response: response.take().unwrap(),
                })
            });

            let first = outcomes[0].as_ref().unwrap();
            assert!(!first.contains_key("failed"), "{failed_alias}: {first:?}");
            let healthy = BranchSummary {
                pr: None,
                checks: None,
            };
            assert_eq!(first.get("healthy"), Some(&healthy));
            assert_eq!(outcomes[1].as_ref().unwrap().get("healthy"), Some(&healthy));
        }
    }

    #[test]
    fn batch_parser_leaves_directly_failed_branch_unanswered() {
        let response: BatchGraphqlResponse = serde_json::from_value(serde_json::json!({
            "data": {
                "repo_0": {
                    "pr_r0_b0": null,
                    "ref_r0_b0": null
                }
            },
            "errors": [
                { "message": "field failed", "path": ["repo_0", "pr_r0_b0"] }
            ]
        }))
        .unwrap();
        let remote = remote_query("repo", vec!["feature".to_string()]);
        let outcome =
            parse_remote_query(&response.data.unwrap(), &response.errors, 0, &remote).unwrap();

        assert!(outcome.is_empty());
    }

    #[test]
    fn aggregate_checks_captures_pending_started_at() {
        let checks = vec![
            CheckRollupItem {
                status: Some("COMPLETED".into()),
                conclusion: Some("SUCCESS".into()),
                name: Some("build".into()),
                started_at: Some("2026-03-24T14:00:00Z".into()),
            },
            CheckRollupItem {
                status: Some("IN_PROGRESS".into()),
                conclusion: None,
                name: Some("test".into()),
                started_at: Some("2026-03-24T14:05:00Z".into()),
            },
        ];
        let (_state, meta) = aggregate_checks(&checks);
        let meta = meta.unwrap();
        // started_at should be the pending check's time (2026-03-24T14:05:00Z)
        assert_eq!(meta.started_at, Some(1774361100));
    }
}