omni-dev 0.39.0

AI-powered git commit rewriter, PR generator, and MCP server for Jira, Confluence, and Datadog.
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
//! GitHub PR check-badge resolution for the worktrees tree (#1337).
//!
//! The engine half of the PR badge, mirroring the [`crate::worktrees`] registry /
//! [`crate::daemon::services::worktrees`] adapter split: this module is pure
//! resolution — build a query, run `gh`, reduce the reply, cache the result — and
//! knows nothing about the daemon, the socket, or the tray. The adapter owns the
//! poll loop and the change-notify.
//!
//! # Why this lives in the daemon
//!
//! Badges were resolved extension-side ([ADR-0050]), which made cost scale with
//! the number of open VS Code windows and — the actual bug — meant nothing ever
//! re-asked GitHub after a badge was first computed. Resolving once in the daemon
//! and fanning the answer out over the existing subscribe stream makes cost
//! invariant to window count and lets an unfocused window show live CI state.
//!
//! # No credential enters the daemon
//!
//! Resolution shells out to `gh api graphql`, so the GitHub token stays inside
//! `gh` where the user already put it — exactly as ADR-0050 wanted, and following
//! ADR-0003's "shell out to `gh`/`git` for GitHub operations". This is why moving
//! resolution daemon-side does **not** widen the worktrees service's no-credential
//! posture (ADR-0040): the daemon never sees a token.
//!
//! # Why one query for everything
//!
//! `repository(owner:,name:)` and `ref(qualifiedName:)` take no `first:`/`last:`
//! argument, so neither is a GraphQL *connection* and neither contributes to the
//! query's cost. Aliasing them is free: one query covering every (repo, branch)
//! pair the tree knows about costs **1 point** against the 5,000/hour budget,
//! independent of how many repos, worktrees, or windows are open. Measured against
//! `rust-works/omni-dev`: cost 1 up to ~50 branches, 2 at 100, 4 at 200.
//!
//! Two shapes are deliberately avoided:
//!
//! - `gh pr list --json statusCheckRollup`, which the extension used, is an alias
//!   for a `commits(last:1)` connection — it adds one request per PR and costs 2.
//! - `checkSuites { checkRuns { totalCount } }` is a third-level connection and
//!   costs **11**.
//!
//! # The explicit negative (#1370)
//!
//! Resolution is tri-state per target, not binary. "No open PR heads this branch"
//! is a *successful* answer ([`PrResolution::NoPr`]), distinct from "never
//! resolved" (absent from the cache). Absence used to carry both meanings, which
//! left a client unable to tell "checked, none" from "old daemon that never
//! checked" — so every window's degraded `gh pr list` fallback re-fired per
//! window × repo × 60s forever, burning the very GraphQL budget this module
//! exists to protect. A **failed** poll still reports nothing: negatives are only
//! ever minted from a successfully parsed reply.
//!
//! [ADR-0050]: ../../docs/adrs/adr-0050.md

use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, PoisonError};

use anyhow::{bail, Context, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Environment override for the `gh` binary, for when the daemon runs under
/// launchd/systemd with a minimal `PATH` that does not contain it. Mirrors
/// `OMNI_DEV_VSCODE_BIN` for the tray's `code` launcher, and the companion
/// extension's override of the same name (`editors/vscode/src/gh.ts`).
const GH_BIN_ENV: &str = "OMNI_DEV_GH_BIN";

/// Absolute paths probed for `gh` when [`GH_BIN_ENV`] is unset, in order. The
/// daemon cannot rely on `PATH`: launchd hands it a minimal one.
const GH_BINARY_CANDIDATES: &[&str] = &[
    "/opt/homebrew/bin/gh",
    "/usr/local/bin/gh",
    "/home/linuxbrew/.linuxbrew/bin/gh",
    "/usr/bin/gh",
];

/// GitHub check conclusions / status-context states that mean **failed**. Values
/// are upper-cased before lookup, so these are the canonical GraphQL enum names.
const FAILURE_STATES: &[&str] = &[
    "FAILURE",
    "ERROR",
    "CANCELLED",
    "TIMED_OUT",
    "ACTION_REQUIRED",
    "STARTUP_FAILURE",
    "STALE",
];

/// States that count as **passing**. A skipped/neutral check is non-blocking, so
/// it passes — matching how `gh pr checks` treats "skipping".
const SUCCESS_STATES: &[&str] = &["SUCCESS", "NEUTRAL", "SKIPPED"];

/// The rolled-up CI verdict for a pull request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PrCheckState {
    /// Every reported check passed (or was skipped/neutral).
    Success,
    /// At least one check failed — failure dominates every other state.
    Failure,
    /// At least one check is still running, or reported a state we do not
    /// recognise. Never a false pass.
    Pending,
    /// No checks reported at all. Renders no badge.
    None,
}

/// The PR badge shown on a worktree row: which PR heads this branch and how its
/// CI is doing.
///
/// `isDraft` is **camelCase on the wire** — the extension's `PrBadge` inherited
/// the name from `gh`'s JSON output before badges moved daemon-side, and every
/// consumer already reads that key. Renaming it to match the payload's otherwise
/// snake_case convention would silently drop the draft marker.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PrBadge {
    /// The PR number, e.g. `1337`.
    pub number: u64,
    /// Whether the PR is a draft.
    #[serde(rename = "isDraft")]
    pub is_draft: bool,
    /// The rolled-up CI verdict.
    pub checks: PrCheckState,
    /// The PR's web URL, for the open action.
    pub url: String,
    /// The commit on the remote branch that [`checks`](Self::checks) describes.
    ///
    /// **Not on the wire** — it exists so the snapshot fold can tell a verdict
    /// computed for *some* commit from one computed for the commit the worktree
    /// actually has checked out. Without it a badge cannot know it is out of date,
    /// and the previous head's verdict stands until the next poll (#1337). See
    /// [`is_stale_for`](Self::is_stale_for).
    #[serde(skip)]
    pub head_oid: String,
}

impl PrBadge {
    /// Whether this verdict describes a commit other than `head_sha`.
    ///
    /// The check is deliberately "different", not "older": we cannot order two
    /// commits without a walk, and every way they can differ means the same thing —
    /// **this verdict is not about the commit in front of you**. You pushed and CI
    /// has not reported yet; you have unpushed work; you are behind the remote.
    ///
    /// This is what makes a push invalidate the badge *immediately*, with no network
    /// call: the cache still holds the previous commit's oid, so the mismatch is
    /// visible on the very next snapshot. A `None` head (an unborn HEAD) is not
    /// stale — there is nothing to compare, and such a worktree has no branch and so
    /// no badge anyway.
    #[must_use]
    pub fn is_stale_for(&self, head_sha: Option<&str>) -> bool {
        head_sha.is_some_and(|sha| sha != self.head_oid)
    }
}

/// One (repo, branch) pair to resolve a badge for. Derived from the tree — a repo
/// contributes a target per worktree that has a branch.
///
/// `Serialize`/`Deserialize` so the daemon can persist the resolved badge cache
/// across restarts (#1389, fix 4); on the tree wire the target is implicit in the
/// worktree row, so this shape appears only in that `0600` cache file.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct PrTarget {
    /// The GitHub owner, e.g. `rust-works`.
    pub owner: String,
    /// The GitHub repo name, e.g. `omni-dev`.
    pub name: String,
    /// The branch checked out in the worktree.
    pub branch: String,
}

/// The outcome for one **successfully checked** target (#1370).
///
/// [`NoPr`](Self::NoPr) deliberately carries no `head_oid`: a negative has no
/// verdict to be stale against, and carrying the remote head would turn every
/// push into a `NoPr(a) → NoPr(b)` map change — spuriously bumping the
/// change-notify that [`PrStatusCache::replace`] exists to gate. A negative that
/// *is* out of date (a PR was just opened) is corrected by the poller's
/// `moved`-triggered immediate re-poll instead.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PrResolution {
    /// An open PR heads the branch; here is its badge.
    Pr(PrBadge),
    /// The branch was checked against GitHub and **no open PR** heads it —
    /// including a branch never pushed. Serialized as `pr_none: true` on the
    /// tree wire, so a client can tell "checked, none" from "not resolved" and
    /// keep its degraded fallback quiet.
    NoPr,
}

/// How a **single** rollup entry classifies.
///
/// Deliberately narrower than [`PrCheckState`]: an individual check is always
/// failing, running, or passing. "No checks" is a property of the rollup as a
/// whole, never of an entry — so rather than carry an impossible `None` case as an
/// unreachable match arm (as the TypeScript this was ported from did), it simply is
/// not representable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum EntryState {
    Failure,
    Pending,
    Success,
}

/// Classifies one `statusCheckRollup` entry.
///
/// A `CheckRun` that has not `COMPLETED` is pending regardless of its (null)
/// conclusion; otherwise the `conclusion` (a `CheckRun`) or `state` (a legacy
/// `StatusContext`) decides. Anything unrecognised is pending, so a still-resolving
/// or unknown check never reads as passing.
fn check_entry_state(entry: &Value) -> EntryState {
    let status = entry.get("status").and_then(Value::as_str).unwrap_or("");
    if !status.is_empty() && !status.eq_ignore_ascii_case("COMPLETED") {
        return EntryState::Pending;
    }
    // `conclusion` then `state`, each ignored when empty — a completed CheckRun
    // carries `conclusion`, a StatusContext carries `state`, and neither is set on
    // an entry still resolving.
    let raw = entry
        .get("conclusion")
        .and_then(Value::as_str)
        .filter(|s| !s.is_empty())
        .or_else(|| {
            entry
                .get("state")
                .and_then(Value::as_str)
                .filter(|s| !s.is_empty())
        })
        .unwrap_or("")
        .to_ascii_uppercase();
    if FAILURE_STATES.contains(&raw.as_str()) {
        return EntryState::Failure;
    }
    if SUCCESS_STATES.contains(&raw.as_str()) {
        return EntryState::Success;
    }
    EntryState::Pending
}

/// Reduces a PR's rollup contexts to one verdict: any failing check dominates
/// (`failure`); else any still-running one (`pending`); else `success`. An empty
/// rollup means no checks (`none`) — the only way `none` arises, since every entry
/// classifies as one of the three.
fn rollup_check_state(contexts: &[Value]) -> PrCheckState {
    if contexts.is_empty() {
        return PrCheckState::None;
    }
    let mut saw_pending = false;
    for entry in contexts {
        match check_entry_state(entry) {
            EntryState::Failure => return PrCheckState::Failure,
            EntryState::Pending => saw_pending = true,
            EntryState::Success => {}
        }
    }
    if saw_pending {
        return PrCheckState::Pending;
    }
    // Every check *that exists* has passed — but more may still be coming, so this
    // is not yet a pass. See [`suite_still_running`].
    if contexts.iter().any(suite_still_running) {
        return PrCheckState::Pending;
    }
    // Non-empty, nothing failing, nothing running, every suite terminal ⇒ passed.
    // (The TypeScript tracked a `sawSuccess` flag here; it could never be false at
    // this point, so the branch it guarded was dead.)
    PrCheckState::Success
}

/// Whether the check **suite** backing this entry is still running.
///
/// This is what catches the `needs:`-gate false green. GitHub does not create a
/// gated job's check run until its dependency completes, so in the window between
/// the gate passing and the fan-out appearing, every check run that *exists* is
/// green and the rollup reduces to `success` — GitHub's own aggregate `state` says
/// `SUCCESS` too. Only the suite knows more jobs are coming.
///
/// Reading the suite off a **`CheckRun` in the rollup** (rather than querying
/// `checkSuites` on the commit) is what makes this safe as well as free. A suite
/// only appears here by way of a check run it owns, so a suite with **zero** runs —
/// e.g. codecov leaves one `QUEUED` on every PR, observed still queued after 3.7
/// days — is never seen and cannot pin a badge yellow forever. No age heuristic, no
/// app denylist, and no third-level `checkRuns { totalCount }` connection (which
/// would cost 11 points instead of 1).
fn suite_still_running(entry: &Value) -> bool {
    entry
        .get("checkSuite")
        .and_then(|suite| suite.get("status"))
        .and_then(Value::as_str)
        .is_some_and(|status| !status.is_empty() && !status.eq_ignore_ascii_case("COMPLETED"))
}

/// The `statusCheckRollup` sub-selection shared by the badge fragment
/// ([`branch_fragment`]) and the merge-eligibility fragment
/// ([`merge_branch_fragment`]): every check context, reduced to a verdict by
/// [`rollup_check_state`]. Factored out so the two fragments cannot drift; kept to a
/// single third-level connection so the query stays at 1 point (see the module docs).
const ROLLUP_FRAGMENT: &str = "statusCheckRollup{ contexts(first:100){ nodes{
          __typename
          ...on CheckRun{ status conclusion checkSuite{ status } }
          ...on StatusContext{ state }
        } } }";

/// The GraphQL fragment resolving one branch: its head OID, the rollup contexts
/// the verdict is reduced from, and the open PR that heads it.
///
/// `associatedPullRequests` is read off the **`Ref`**, filtered to `OPEN`, not off
/// the `Commit`. On a `Commit` it returns whatever PR introduced that commit — on
/// `main` that is the last *merged* PR, from an unrelated branch, which would paint
/// a false badge. On a `Ref` it matches on **head**, reproducing the extension's
/// "first open PR whose `headRefName` is this branch" rule (verified: `main` is the
/// base of many open PRs and correctly resolves to nothing).
fn branch_fragment(alias: &str, branch: &str) -> String {
    // JSON string escaping is valid GraphQL string escaping, so this is safe for
    // any branch name git permits.
    let qualified = Value::String(format!("refs/heads/{branch}"));
    format!(
        r"{alias}: ref(qualifiedName:{qualified}){{
      target{{ ...on Commit{{ oid
        {ROLLUP_FRAGMENT}
      }} }}
      associatedPullRequests(first:1, states:OPEN){{ nodes{{ number isDraft url }} }}
    }}"
    )
}

/// The GraphQL fragment resolving one branch for **merge-queue eligibility** (#1401).
///
/// A superset of [`branch_fragment`]'s PR selection: on top of the shared
/// [`ROLLUP_FRAGMENT`] (for the CI gate) it fetches the fields `enqueuePullRequest`
/// and the eligibility gates need but the badge cache never carries — the PR's
/// GraphQL node `id` (the mutation input), `headRefOid` (compared to the local head
/// to catch a stale UI), `mergeStateStatus` (the conflict gate), and
/// `mergeQueueEntry` (already-queued ⇒ idempotent success). Kept **out** of the
/// hot-path badge poll deliberately: this runs only for the handful of worktrees a
/// user explicitly selects to enqueue, and the op needs fresh data anyway.
fn merge_branch_fragment(alias: &str, branch: &str) -> String {
    let qualified = Value::String(format!("refs/heads/{branch}"));
    format!(
        r"{alias}: ref(qualifiedName:{qualified}){{
      target{{ ...on Commit{{ oid
        {ROLLUP_FRAGMENT}
      }} }}
      associatedPullRequests(first:1, states:OPEN){{ nodes{{
        id number isDraft url headRefOid mergeStateStatus
        mergeQueueEntry{{ state }}
      }} }}
    }}"
    )
}

/// Maps a query's `(repo alias index, branch alias index)` back to the target it
/// was built for, so the reply can be read without re-deriving the aliasing.
type QueryIndex = HashMap<(usize, usize), PrTarget>;

/// Builds the single aliased query for every target, plus the alias→target index
/// needed to read the reply back. Targets are grouped by repo so each repo appears
/// once. Returns `None` when there is nothing to ask.
fn build_query(targets: &[PrTarget]) -> Option<(String, QueryIndex)> {
    if targets.is_empty() {
        return None;
    }
    // BTreeMap so aliases are assigned deterministically — the query text is then
    // stable for a stable target set, which keeps it testable.
    let mut by_repo: BTreeMap<(&str, &str), Vec<&PrTarget>> = BTreeMap::new();
    for t in targets {
        by_repo
            .entry((t.owner.as_str(), t.name.as_str()))
            .or_default()
            .push(t);
    }
    let mut index = HashMap::new();
    let mut repos = Vec::new();
    for (ri, ((owner, name), branches)) in by_repo.iter().enumerate() {
        let mut frags = Vec::new();
        for (bi, target) in branches.iter().enumerate() {
            frags.push(branch_fragment(&format!("b{bi}"), &target.branch));
            index.insert((ri, bi), (*target).clone());
        }
        let owner = Value::String((*owner).to_string());
        let name = Value::String((*name).to_string());
        repos.push(format!(
            "r{ri}: repository(owner:{owner}, name:{name}){{\n{}\n}}",
            frags.join("\n")
        ));
    }
    // Fold the graphql budget into every poll (#1389, fix 8): `rateLimit` is a
    // meta-field GitHub answers for free (it does not add to the query's own
    // `cost`), so each PR poll doubles as a live budget reading — and its `cost`
    // reveals the actual per-call point price, verifying the "1 point" assumption at
    // scale instead of taking it on faith.
    Some((
        format!(
            "query{{\nrateLimit{{ limit cost remaining used resetAt }}\n{}\n}}",
            repos.join("\n")
        ),
        index,
    ))
}

/// The `rateLimit` block folded into every PR-poll reply (#1389, fix 8).
///
/// Carries the query's own point `cost` plus the live graphql budget. Every field
/// is what GitHub's `rateLimit` object reports; `reset` is `resetAt` (ISO-8601)
/// parsed to a Unix epoch so it drops straight into a
/// [`RateLimitResource`](crate::github_rate_limit::RateLimitResource).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QueryRateLimit {
    /// The point cost GitHub charged for *this* query.
    pub cost: u64,
    /// Points spent in the current graphql window.
    pub used: u64,
    /// The window ceiling (5,000/hour today).
    pub limit: u64,
    /// Points remaining in the window.
    pub remaining: u64,
    /// When the window resets, as a Unix epoch (seconds); `0` if `resetAt` was
    /// absent or unparseable.
    pub reset: i64,
}

/// Reads the `rateLimit` block from a poll reply, or `None` when it is absent
/// (an older query shape, or a reply that carried none). Best-effort: a partial
/// block missing any of `cost`/`used`/`limit`/`remaining` yields `None` rather
/// than a half-populated reading.
fn parse_rate_limit(body: &Value) -> Option<QueryRateLimit> {
    let rl = body.get("data")?.get("rateLimit")?;
    let reset = rl
        .get("resetAt")
        .and_then(Value::as_str)
        .and_then(|s| chrono::DateTime::parse_from_rfc3339(s).ok())
        .map_or(0, |dt| dt.timestamp());
    Some(QueryRateLimit {
        cost: rl.get("cost")?.as_u64()?,
        used: rl.get("used")?.as_u64()?,
        limit: rl.get("limit")?.as_u64()?,
        remaining: rl.get("remaining")?.as_u64()?,
        reset,
    })
}

/// Reads one resolved `ref` node into a badge. `None` for a node without a
/// readable open PR; [`resolution_from_ref`] decides whether that means "no PR"
/// (an explicit negative) or "malformed" (unresolved) before delegating here.
fn badge_from_ref(node: &Value) -> Option<PrBadge> {
    let pr = node
        .get("associatedPullRequests")?
        .get("nodes")?
        .as_array()?
        .first()?;
    let contexts = node
        .get("target")
        .and_then(|t| t.get("statusCheckRollup"))
        .and_then(|r| r.get("contexts"))
        .and_then(|c| c.get("nodes"))
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    Some(PrBadge {
        number: pr.get("number").and_then(Value::as_u64)?,
        is_draft: pr.get("isDraft").and_then(Value::as_bool).unwrap_or(false),
        checks: rollup_check_state(&contexts),
        url: pr
            .get("url")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string(),
        // The commit this verdict is about — the remote branch head the rollup was
        // read from, not the PR's own `headRefOid` (the same commit, one fewer field
        // to ask for).
        head_oid: node
            .get("target")
            .and_then(|t| t.get("oid"))
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string(),
    })
}

/// Reads one **non-null** `ref` node into a resolution: [`PrResolution::NoPr`]
/// when the PR list is present and empty, a badge for an open PR, and `None` —
/// *unresolved*, never a negative — for a malformed node. A false negative would
/// silence the client fallback for a branch that may well have a PR, so anything
/// we cannot positively read stays unresolved (#1370).
fn resolution_from_ref(node: &Value) -> Option<PrResolution> {
    let prs = node
        .get("associatedPullRequests")?
        .get("nodes")?
        .as_array()?;
    if prs.is_empty() {
        return Some(PrResolution::NoPr);
    }
    badge_from_ref(node).map(PrResolution::Pr)
}

/// Reads the GraphQL reply back into resolutions, keyed by target.
///
/// Tri-state per target (#1370): an open PR yields its badge, a checked branch
/// with none — including one never pushed, whose aliased `ref` comes back null —
/// yields [`PrResolution::NoPr`], and a target whose part of the reply is missing
/// or malformed is simply **absent** (unresolved). Best-effort per branch: one
/// bad node never sinks the whole poll, and never mints a negative.
fn parse_response(body: &Value, index: &QueryIndex) -> HashMap<PrTarget, PrResolution> {
    let mut out = HashMap::new();
    let Some(data) = body.get("data") else {
        return out;
    };
    for ((ri, bi), target) in index {
        // A repo alias absent or null (a repo-level failure) is unresolved — only
        // an answer *about the ref* may mint a negative.
        let Some(repo) = data.get(format!("r{ri}")).filter(|r| !r.is_null()) else {
            continue;
        };
        let Some(node) = repo.get(format!("b{bi}")) else {
            continue;
        };
        // A null ref is a branch that does not exist on the remote (never
        // pushed): checked, and definitively PR-less.
        if node.is_null() {
            out.insert(target.clone(), PrResolution::NoPr);
            continue;
        }
        if let Some(resolution) = resolution_from_ref(node) {
            out.insert(target.clone(), resolution);
        }
    }
    out
}

/// Resolves `gh`, preferring [`GH_BIN_ENV`], then the first existing well-known
/// absolute path, then bare `gh` on `PATH`.
///
/// Callers should do this **once** (the poller resolves it at spawn) and pass the
/// result to [`resolve_with`], rather than re-reading the environment per poll.
#[must_use]
pub fn resolve_gh_binary() -> PathBuf {
    resolve_gh_binary_from(std::env::var_os(GH_BIN_ENV), GH_BINARY_CANDIDATES)
}

/// The testable core of [`resolve_gh_binary`]. Split so the probe order can be
/// unit-tested without mutating the process environment.
fn resolve_gh_binary_from(
    env_override: Option<std::ffi::OsString>,
    candidates: &[&str],
) -> PathBuf {
    if let Some(path) = env_override.filter(|p| !p.is_empty()) {
        return PathBuf::from(path);
    }
    for candidate in candidates {
        let path = Path::new(candidate);
        if path.exists() {
            return path.to_path_buf();
        }
    }
    PathBuf::from("gh")
}

/// Runs one `gh api graphql` call against `bin`. **Blocking** — callers must be on
/// a blocking thread, never an async worker.
fn run_gh_graphql(bin: &Path, query: &str) -> Result<Value> {
    let query_arg = format!("query={query}");
    let output = crate::github_metrics::run_gh(
        bin,
        ["api", "graphql", "-f", query_arg.as_str()],
        "api graphql",
        None,
    )
    .with_context(|| {
        format!(
            "failed to run {} (is the GitHub CLI installed?)",
            bin.display()
        )
    })?;
    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        bail!("gh api graphql failed: {}", stderr.trim());
    }
    serde_json::from_slice(&output.stdout).context("gh api graphql returned invalid JSON")
}

/// Resolves every target in **one** `gh api graphql` call, using the `gh` at
/// `bin`.
///
/// The binary is a parameter rather than resolved here so callers read the
/// environment **once** (the poller does it at spawn, like its interval) and so
/// tests inject a stub without mutating the process environment — two parallel
/// tests pointing one global env var at different fakes race, and the project is
/// migrating away from test env locks toward injection (#1030).
///
/// **Blocking** — run on a blocking thread. Every target that was successfully
/// checked appears in the map: [`PrResolution::Pr`] for an open PR,
/// [`PrResolution::NoPr`] for a branch — pushed or not — with none (#1370). A
/// target is *absent* only when its part of the reply was missing or malformed,
/// and a failed call (`Err`, including a GraphQL 200 carrying `errors`) yields no
/// map at all — so a failed poll can never manufacture negatives.
pub fn resolve_with(bin: &Path, targets: &[PrTarget]) -> Result<HashMap<PrTarget, PrResolution>> {
    resolve_inner(bin, targets).map(|(resolutions, _budget)| resolutions)
}

/// [`resolve_with`] that **also** returns the poll's folded-in graphql budget
/// reading (#1389, fix 8).
///
/// For the daemon poller to feed the shared
/// [`RateLimitCache`](crate::github_rate_limit::RateLimitCache). The budget is
/// `None` when there were no targets (no query ran) or the reply carried no
/// `rateLimit` block; the resolutions are exactly what [`resolve_with`] returns.
pub fn resolve_with_budget(
    bin: &Path,
    targets: &[PrTarget],
) -> Result<(HashMap<PrTarget, PrResolution>, Option<QueryRateLimit>)> {
    resolve_inner(bin, targets)
}

/// The shared body of [`resolve_with`] / [`resolve_with_budget`]: one `gh api
/// graphql` call, parsed into resolutions **and** the optional budget reading.
fn resolve_inner(
    bin: &Path,
    targets: &[PrTarget],
) -> Result<(HashMap<PrTarget, PrResolution>, Option<QueryRateLimit>)> {
    let Some((query, index)) = build_query(targets) else {
        return Ok((HashMap::new(), None));
    };
    let body = run_gh_graphql(bin, &query)?;
    // A GraphQL 200 can still carry errors; surface them rather than silently
    // reporting "no badges", which would look identical to "no PRs".
    if let Some(errors) = body.get("errors").and_then(Value::as_array) {
        if !errors.is_empty() {
            bail!("gh api graphql returned errors: {errors:?}");
        }
    }
    Ok((parse_response(&body, &index), parse_rate_limit(&body)))
}

// --- Merge-queue eligibility & enqueue (#1401) --------------------------------

/// What the merge-queue op needs to know about a branch's open PR.
///
/// Resolved **fresh** at enqueue time — never from the badge cache, which carries
/// neither the PR node `id` the mutation needs nor the current merge state.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MergeInfo {
    /// The PR's GraphQL global node id — the `enqueuePullRequest` input.
    pub pr_id: String,
    /// The PR number, for display.
    pub number: u64,
    /// The PR's web URL.
    pub url: String,
    /// Whether the PR is a draft (GitHub refuses to queue a draft).
    pub is_draft: bool,
    /// The remote PR head commit — compared to the local head to catch a stale UI.
    pub head_oid: String,
    /// GitHub's mergeability verdict, upper-cased (`CLEAN`, `BLOCKED`, `DIRTY`,
    /// `UNKNOWN`, …); `None` when the field was absent from the reply.
    pub merge_state: Option<String>,
    /// Whether the PR is already in the merge queue — an enqueue is then a no-op
    /// (idempotent success, not a failure).
    pub already_queued: bool,
    /// The rolled-up CI verdict on the PR head.
    pub checks: PrCheckState,
}

/// Builds the single aliased merge-eligibility query for every target, plus the
/// alias→target index to read the reply back. Same repo-grouping and aliasing as
/// [`build_query`], but with [`merge_branch_fragment`] and no `rateLimit` fold —
/// this is a rare, explicit, small-N call, not the hot-path poll.
fn build_merge_query(targets: &[PrTarget]) -> Option<(String, QueryIndex)> {
    if targets.is_empty() {
        return None;
    }
    let mut by_repo: BTreeMap<(&str, &str), Vec<&PrTarget>> = BTreeMap::new();
    for t in targets {
        by_repo
            .entry((t.owner.as_str(), t.name.as_str()))
            .or_default()
            .push(t);
    }
    let mut index = HashMap::new();
    let mut repos = Vec::new();
    for (ri, ((owner, name), branches)) in by_repo.iter().enumerate() {
        let mut frags = Vec::new();
        for (bi, target) in branches.iter().enumerate() {
            frags.push(merge_branch_fragment(&format!("b{bi}"), &target.branch));
            index.insert((ri, bi), (*target).clone());
        }
        let owner = Value::String((*owner).to_string());
        let name = Value::String((*name).to_string());
        repos.push(format!(
            "r{ri}: repository(owner:{owner}, name:{name}){{\n{}\n}}",
            frags.join("\n")
        ));
    }
    Some((format!("query{{\n{}\n}}", repos.join("\n")), index))
}

/// Reads one resolved merge `ref` node into a [`MergeInfo`]. `None` — meaning
/// *no readable open PR*, which the caller treats as "skip, no PR" — for a node
/// whose PR list is absent/empty or is missing the load-bearing `id`/`number`.
fn merge_info_from_ref(node: &Value) -> Option<MergeInfo> {
    let pr = node
        .get("associatedPullRequests")?
        .get("nodes")?
        .as_array()?
        .first()?;
    let contexts = node
        .get("target")
        .and_then(|t| t.get("statusCheckRollup"))
        .and_then(|r| r.get("contexts"))
        .and_then(|c| c.get("nodes"))
        .and_then(Value::as_array)
        .cloned()
        .unwrap_or_default();
    Some(MergeInfo {
        pr_id: pr.get("id").and_then(Value::as_str)?.to_string(),
        number: pr.get("number").and_then(Value::as_u64)?,
        url: pr
            .get("url")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string(),
        is_draft: pr.get("isDraft").and_then(Value::as_bool).unwrap_or(false),
        head_oid: pr
            .get("headRefOid")
            .and_then(Value::as_str)
            .unwrap_or_default()
            .to_string(),
        merge_state: pr
            .get("mergeStateStatus")
            .and_then(Value::as_str)
            .map(str::to_ascii_uppercase),
        already_queued: pr
            .get("mergeQueueEntry")
            .is_some_and(|entry| !entry.is_null()),
        checks: rollup_check_state(&contexts),
    })
}

/// Reads a merge-eligibility reply back into [`MergeInfo`]s, keyed by target. A
/// target whose part of the reply is missing, null, or PR-less is simply **absent**
/// — the caller reports that as a `no-pr` skip.
fn parse_merge_response(body: &Value, index: &QueryIndex) -> HashMap<PrTarget, MergeInfo> {
    let mut out = HashMap::new();
    let Some(data) = body.get("data") else {
        return out;
    };
    for ((ri, bi), target) in index {
        let Some(repo) = data.get(format!("r{ri}")).filter(|r| !r.is_null()) else {
            continue;
        };
        let Some(node) = repo.get(format!("b{bi}")).filter(|n| !n.is_null()) else {
            continue;
        };
        if let Some(info) = merge_info_from_ref(node) {
            out.insert(target.clone(), info);
        }
    }
    out
}

/// Resolves merge-queue eligibility facts for every target in **one** `gh api
/// graphql` call. **Blocking** — run on a blocking thread.
///
/// Only targets with a readable open PR appear in the map; an absent target means
/// no open PR (or an unreadable reply), which the merge-queue op treats as a
/// `no-pr` skip. A failed call (including a GraphQL 200 carrying `errors`) is `Err`,
/// so the whole batch reports the error rather than silently enqueuing nothing.
pub fn resolve_merge_targets(
    bin: &Path,
    targets: &[PrTarget],
) -> Result<HashMap<PrTarget, MergeInfo>> {
    let Some((query, index)) = build_merge_query(targets) else {
        return Ok(HashMap::new());
    };
    let body = run_gh_graphql(bin, &query)?;
    if let Some(errors) = body.get("errors").and_then(Value::as_array) {
        if !errors.is_empty() {
            bail!("gh api graphql returned errors: {errors:?}");
        }
    }
    Ok(parse_merge_response(&body, &index))
}

/// The outcome of a single `enqueuePullRequest` mutation.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EnqueueOutcome {
    /// The PR is now in the merge queue; the optional string is `mergeQueueEntry`'s
    /// reported `state`.
    Queued(Option<String>),
    /// GitHub rejected the enqueue — merge queue disabled on the repo, the PR not
    /// mergeable / conflicting, or insufficient permissions. The string is the
    /// human-readable reason, surfaced to the caller as a per-PR failure (never a
    /// panic, never a batch-sinking error).
    Rejected(String),
}

/// Joins one-or-more GraphQL `errors[].message` strings into a single reason.
fn enqueue_error_message(errors: &[Value]) -> String {
    let joined = errors
        .iter()
        .filter_map(|e| e.get("message").and_then(Value::as_str))
        .collect::<Vec<_>>()
        .join("; ");
    if joined.is_empty() {
        "enqueue rejected by GitHub".to_string()
    } else {
        joined
    }
}

/// Enqueues one PR into its repo's merge queue via the `enqueuePullRequest`
/// mutation. **Blocking** — run on a blocking thread.
///
/// Unlike [`run_gh_graphql`], a GraphQL error here is **not** a hard `Err`: `gh`
/// exits non-zero on a rejected mutation, and we map that (and a 200-with-`errors`)
/// to [`EnqueueOutcome::Rejected`] so one un-enqueuable PR lands in the batch's
/// `failed[]` list while the rest proceed. `Err` is reserved for "could not run
/// `gh` at all" (e.g. the binary is missing).
pub fn enqueue_pull_request(bin: &Path, pr_node_id: &str) -> Result<EnqueueOutcome> {
    // JSON string escaping is valid GraphQL string escaping (as in `branch_fragment`).
    let id_lit = Value::String(pr_node_id.to_string());
    let mutation =
        format!("mutation{{ enqueuePullRequest(input:{{pullRequestId:{id_lit}}}){{ mergeQueueEntry{{ state }} }} }}");
    let query_arg = format!("query={mutation}");
    let output = crate::github_metrics::run_gh(
        bin,
        ["api", "graphql", "-f", query_arg.as_str()],
        "api graphql",
        None,
    )
    .with_context(|| {
        format!(
            "failed to run {} (is the GitHub CLI installed?)",
            bin.display()
        )
    })?;
    if !output.status.success() {
        // A rejected mutation exits non-zero; the reason is in the JSON `errors`
        // body (preferred) or, failing that, stderr.
        let msg = serde_json::from_slice::<Value>(&output.stdout)
            .ok()
            .and_then(|body| {
                body.get("errors")
                    .and_then(Value::as_array)
                    .filter(|errs| !errs.is_empty())
                    .map(|errs| enqueue_error_message(errs))
            })
            .unwrap_or_else(|| String::from_utf8_lossy(&output.stderr).trim().to_string());
        return Ok(EnqueueOutcome::Rejected(msg));
    }
    let body: Value =
        serde_json::from_slice(&output.stdout).context("gh api graphql returned invalid JSON")?;
    if let Some(errors) = body.get("errors").and_then(Value::as_array) {
        if !errors.is_empty() {
            return Ok(EnqueueOutcome::Rejected(enqueue_error_message(errors)));
        }
    }
    let state = body
        .pointer("/data/enqueuePullRequest/mergeQueueEntry/state")
        .and_then(Value::as_str)
        .map(str::to_string);
    Ok(EnqueueOutcome::Queued(state))
}

/// The poller-written, snapshot-read resolution cache.
///
/// A plain `std::Mutex` map: writes come from the poll loop, reads from the tree
/// snapshot build. The lock is never held across an `.await` — every method takes
/// it, finishes, and drops it.
#[derive(Debug, Default)]
pub struct PrStatusCache {
    resolutions: Mutex<HashMap<PrTarget, PrResolution>>,
}

impl PrStatusCache {
    /// An empty cache. Until the first poll lands, every lookup misses and the
    /// tree simply renders no badge — and no negative either (#1370).
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// The resolution for one (repo, branch): a badge, an explicit no-PR, or
    /// `None` when never successfully checked.
    #[must_use]
    pub fn get(&self, owner: &str, name: &str, branch: &str) -> Option<PrResolution> {
        let key = PrTarget {
            owner: owner.to_string(),
            name: name.to_string(),
            branch: branch.to_string(),
        };
        self.lock().get(&key).cloned()
    }

    /// Replaces the cache wholesale, returning whether anything actually changed.
    ///
    /// The bool is load-bearing: the caller bumps the registry's change-notify only
    /// when it is `true`. Bumping unconditionally would defeat the server's
    /// diff-and-drop and re-push an identical snapshot to every window on every
    /// poll — the cost this whole design exists to avoid. A first round of
    /// negatives *is* a change — the one push that delivers them — after which
    /// identical polls stay silent.
    pub fn replace(&self, next: HashMap<PrTarget, PrResolution>) -> bool {
        let mut guard = self.lock();
        if *guard == next {
            return false;
        }
        *guard = next;
        true
    }

    /// Drops every cached resolution whose target is absent from `keep`, returning
    /// whether anything was removed.
    ///
    /// Lets the poller prune the verdicts of worktrees that closed (or repos whose
    /// lease lapsed) **without** spending a `gh` call to re-resolve the survivors
    /// (#1389, fix 1) — the wholesale [`replace`](Self::replace) only prunes as a
    /// side effect of a fetch, which a pure removal must never trigger. No caller
    /// bumps on the return today (a removed target's row is already gone from the
    /// tree, so nothing re-renders), but the bool is reported for symmetry with
    /// `replace` and to keep the prune observable in tests.
    pub fn retain_targets(&self, keep: &HashSet<PrTarget>) -> bool {
        let mut guard = self.lock();
        let before = guard.len();
        guard.retain(|target, _| keep.contains(target));
        guard.len() != before
    }

    /// Every cached (target, resolution) pair, cloned out for persistence (#1389,
    /// fix 4). Ordering is unspecified (a `HashMap`); the caller sorts if it needs
    /// a stable on-disk form.
    #[must_use]
    pub fn entries(&self) -> Vec<(PrTarget, PrResolution)> {
        self.lock()
            .iter()
            .map(|(t, r)| (t.clone(), r.clone()))
            .collect()
    }

    /// Seeds the cache from a persisted set, **without** bumping any change-notify.
    ///
    /// Called once at daemon startup (before any window subscribes) so restored
    /// badges render on the first tree snapshot rather than after the first poll
    /// (#1389, fix 4) — the [`crate::pr_status`] analogue of
    /// `WorktreesRegistry::seed_polling`. Existing entries with the same target are
    /// overwritten; the cache is empty at that point, so in practice this inserts.
    pub fn seed(&self, entries: impl IntoIterator<Item = (PrTarget, PrResolution)>) {
        let mut guard = self.lock();
        for (target, resolution) in entries {
            guard.insert(target, resolution);
        }
    }

    /// Whether any cached badge is still pending — the poller's cadence signal. A
    /// negative is terminal and never holds the fast cadence.
    #[must_use]
    pub fn any_pending(&self) -> bool {
        self.lock()
            .values()
            .any(|r| matches!(r, PrResolution::Pr(b) if b.checks == PrCheckState::Pending))
    }

    /// Poison-tolerant lock: a panicking holder must not wedge the badge cache,
    /// which is best-effort decoration.
    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<PrTarget, PrResolution>> {
        self.resolutions
            .lock()
            .unwrap_or_else(PoisonError::into_inner)
    }
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::test_support::shim::{retry_on_etxtbsy, shim_lock, write_exec_script};
    use serde_json::json;
    use std::sync::MutexGuard;

    fn target(branch: &str) -> PrTarget {
        PrTarget {
            owner: "rust-works".into(),
            name: "omni-dev".into(),
            branch: branch.into(),
        }
    }

    // --- Reducer: ported verbatim from the extension's github.test.ts so the
    //     daemon-side move is behaviour-preserving (#1337 PR 2). ---

    #[test]
    fn rollup_is_none_for_an_empty_rollup() {
        assert_eq!(rollup_check_state(&[]), PrCheckState::None);
    }

    #[test]
    fn rollup_reads_completed_check_run_conclusions() {
        for (conclusion, want) in [
            ("SUCCESS", PrCheckState::Success),
            ("NEUTRAL", PrCheckState::Success),
            ("SKIPPED", PrCheckState::Success),
            ("FAILURE", PrCheckState::Failure),
            ("CANCELLED", PrCheckState::Failure),
            ("TIMED_OUT", PrCheckState::Failure),
            ("ACTION_REQUIRED", PrCheckState::Failure),
            ("STARTUP_FAILURE", PrCheckState::Failure),
            ("STALE", PrCheckState::Failure),
        ] {
            let entry =
                json!({"__typename":"CheckRun","status":"COMPLETED","conclusion":conclusion});
            assert_eq!(
                rollup_check_state(&[entry]),
                want,
                "conclusion {conclusion} should be {want:?}"
            );
        }
    }

    #[test]
    fn rollup_treats_an_incomplete_check_run_as_pending() {
        // The conclusion is null while running; the status decides.
        for status in ["IN_PROGRESS", "QUEUED", "WAITING", "PENDING"] {
            let entry = json!({"__typename":"CheckRun","status":status,"conclusion":null});
            assert_eq!(rollup_check_state(&[entry]), PrCheckState::Pending);
        }
    }

    #[test]
    fn rollup_reads_status_context_states() {
        // A legacy StatusContext has no `status`, so `state` decides.
        for (state, want) in [
            ("SUCCESS", PrCheckState::Success),
            ("FAILURE", PrCheckState::Failure),
            ("ERROR", PrCheckState::Failure),
            ("PENDING", PrCheckState::Pending),
            ("EXPECTED", PrCheckState::Pending),
        ] {
            let entry = json!({"__typename":"StatusContext","state":state});
            assert_eq!(rollup_check_state(&[entry]), want, "state {state}");
        }
    }

    #[test]
    fn rollup_never_reads_an_unknown_value_as_a_pass() {
        // The load-bearing rule: anything unrecognised is pending, never success.
        let entry = json!({"__typename":"CheckRun","status":"COMPLETED","conclusion":"WAT"});
        assert_eq!(rollup_check_state(&[entry]), PrCheckState::Pending);
        // A completed-but-unset conclusion likewise.
        let entry = json!({"__typename":"CheckRun","status":"COMPLETED","conclusion":""});
        assert_eq!(rollup_check_state(&[entry]), PrCheckState::Pending);
    }

    #[test]
    fn rollup_precedence_is_failure_then_pending_then_success() {
        let ok = json!({"__typename":"CheckRun","status":"COMPLETED","conclusion":"SUCCESS"});
        let bad = json!({"__typename":"CheckRun","status":"COMPLETED","conclusion":"FAILURE"});
        let run = json!({"__typename":"CheckRun","status":"IN_PROGRESS","conclusion":null});
        // Failure dominates everything, in either order.
        assert_eq!(
            rollup_check_state(&[ok.clone(), run.clone(), bad.clone()]),
            PrCheckState::Failure
        );
        assert_eq!(
            rollup_check_state(&[bad, ok.clone()]),
            PrCheckState::Failure
        );
        // Pending beats success.
        assert_eq!(
            rollup_check_state(&[ok.clone(), run]),
            PrCheckState::Pending
        );
        assert_eq!(rollup_check_state(&[ok]), PrCheckState::Success);
    }

    // --- Suite awareness: the `needs:`-gate false green ---

    fn run(conclusion: &str, suite: Option<&str>) -> Value {
        let mut e = json!({
            "__typename": "CheckRun",
            "status": "COMPLETED",
            "conclusion": conclusion,
        });
        if let Some(s) = suite {
            e["checkSuite"] = json!({ "status": s });
        }
        e
    }

    #[test]
    fn rollup_is_pending_while_a_suite_is_still_creating_jobs() {
        // The exact shape observed on PRs #1294/#1329: every check run that exists
        // is green — GitHub's own rollup `state` reads SUCCESS — but the CI suite is
        // still spawning the `needs: gate` fan-out. Reporting success here is the
        // false ✓ this issue is about.
        let contexts = vec![
            run("SUCCESS", Some("IN_PROGRESS")),
            run("SUCCESS", Some("IN_PROGRESS")),
        ];
        assert_eq!(rollup_check_state(&contexts), PrCheckState::Pending);
        // QUEUED counts too — the suite exists but has not started its fan-out.
        assert_eq!(
            rollup_check_state(&[run("SUCCESS", Some("QUEUED"))]),
            PrCheckState::Pending
        );
    }

    #[test]
    fn rollup_is_success_once_every_backing_suite_is_terminal() {
        let contexts = vec![
            run("SUCCESS", Some("COMPLETED")),
            run("SKIPPED", Some("COMPLETED")),
        ];
        assert_eq!(rollup_check_state(&contexts), PrCheckState::Success);
    }

    #[test]
    fn rollup_ignores_a_zero_run_zombie_suite() {
        // codecov leaves a QUEUED suite with **zero** check runs on every PR — one
        // was still queued after 3.7 days. A rule keyed on "any non-terminal suite"
        // would pin such a PR yellow forever. Keying on suites reachable *through a
        // check run* excludes it structurally: with no runs, it never appears in the
        // rollup at all. So a rollup whose runs all carry terminal suites is green,
        // even though a zombie suite exists on the commit.
        let contexts = vec![run("SUCCESS", Some("COMPLETED"))];
        assert_eq!(rollup_check_state(&contexts), PrCheckState::Success);
    }

    #[test]
    fn rollup_tolerates_entries_without_suite_information() {
        // A legacy StatusContext has no `checkSuite`, and neither does a CheckRun if
        // the field is ever absent. Missing suite info must not imply "still
        // running", or every StatusContext-only repo pins yellow.
        assert_eq!(
            rollup_check_state(&[json!({"__typename":"StatusContext","state":"SUCCESS"})]),
            PrCheckState::Success
        );
        assert_eq!(
            rollup_check_state(&[run("SUCCESS", None)]),
            PrCheckState::Success
        );
        // An empty suite status is not a running suite either.
        assert_eq!(
            rollup_check_state(&[run("SUCCESS", Some(""))]),
            PrCheckState::Success
        );
    }

    #[test]
    fn rollup_failure_still_dominates_a_running_suite() {
        // A red check is red regardless of what else is still spawning.
        let contexts = vec![
            run("FAILURE", Some("IN_PROGRESS")),
            run("SUCCESS", Some("IN_PROGRESS")),
        ];
        assert_eq!(rollup_check_state(&contexts), PrCheckState::Failure);
    }

    #[test]
    fn build_query_asks_for_the_backing_suite_status() {
        let (query, _) = build_query(&[target("main")]).unwrap();
        assert!(query.contains("checkSuite{ status }"), "{query}");
    }

    #[test]
    fn build_query_folds_in_the_rate_limit_block() {
        // #1389, fix 8: every poll carries a free budget reading.
        let (query, _) = build_query(&[target("main")]).unwrap();
        assert!(
            query.contains("rateLimit{ limit cost remaining used resetAt }"),
            "{query}"
        );
    }

    #[test]
    fn parse_rate_limit_reads_the_folded_budget_block() {
        let body = json!({"data":{"rateLimit":
            {"limit":5000,"cost":1,"remaining":4970,"used":30,"resetAt":"2026-07-21T16:00:00Z"}}});
        let rl = parse_rate_limit(&body).expect("a complete block should parse");
        assert_eq!(rl.cost, 1);
        assert_eq!(rl.used, 30);
        assert_eq!(rl.limit, 5000);
        assert_eq!(rl.remaining, 4970);
        assert!(rl.reset > 0, "resetAt should parse to an epoch");
        // An older query shape (no block) reads as `None`, not a zeroed budget.
        assert!(parse_rate_limit(&json!({"data":{"r0":{}}})).is_none());
        // A partial block (missing `used`) is `None`, never half-populated.
        assert!(parse_rate_limit(
            &json!({"data":{"rateLimit":{"limit":5000,"cost":1,"remaining":4970}}})
        )
        .is_none());
    }

    // --- Query shape ---

    #[test]
    fn build_query_is_none_without_targets() {
        assert!(build_query(&[]).is_none());
    }

    #[test]
    fn build_query_groups_branches_under_one_repo_alias() {
        let (query, index) = build_query(&[target("main"), target("feature")]).unwrap();
        // One repo → one `repository(...)` block, two `ref(...)` aliases.
        assert_eq!(query.matches("repository(owner:").count(), 1);
        assert_eq!(query.matches(": ref(qualifiedName:").count(), 2);
        assert!(query.contains(r#""refs/heads/main""#), "{query}");
        assert!(query.contains(r#""refs/heads/feature""#), "{query}");
        assert_eq!(index.len(), 2);
    }

    #[test]
    fn build_query_reads_open_prs_off_the_ref_not_the_commit() {
        // Guards the semantic trap: `Commit.associatedPullRequests` returns the PR
        // that *introduced* the commit — on `main`, the last merged PR from an
        // unrelated branch — which would paint a false badge. It must be read off
        // the Ref, filtered to OPEN, which matches on head.
        let (query, _) = build_query(&[target("main")]).unwrap();
        assert!(
            query.contains("associatedPullRequests(first:1, states:OPEN)"),
            "{query}"
        );
        // The PR lookup must sit outside the `target{...on Commit{...}}` block.
        let commit_block = query.find("...on Commit").unwrap();
        let pr_lookup = query.find("associatedPullRequests").unwrap();
        assert!(
            pr_lookup > commit_block,
            "PR lookup must be on the Ref, after the Commit block"
        );
    }

    #[test]
    fn build_query_separates_distinct_repos() {
        let a = PrTarget {
            owner: "o1".into(),
            name: "r1".into(),
            branch: "main".into(),
        };
        let b = PrTarget {
            owner: "o2".into(),
            name: "r2".into(),
            branch: "main".into(),
        };
        let (query, index) = build_query(&[a, b]).unwrap();
        assert_eq!(query.matches("repository(owner:").count(), 2);
        assert_eq!(index.len(), 2);
    }

    #[test]
    fn build_query_escapes_branch_names() {
        // Defensive: JSON escaping keeps a quote in a ref name from breaking out of
        // the GraphQL string literal.
        let (query, _) = build_query(&[target(r#"we"ird"#)]).unwrap();
        assert!(query.contains(r#"refs/heads/we\"ird"#), "{query}");
    }

    // --- Reply parsing ---

    #[test]
    fn parse_response_reads_badges_and_resolves_absent_refs_as_negatives() {
        let targets = vec![target("feature"), target("unpushed"), target("no-pr")];
        let (_, index) = build_query(&targets).unwrap();
        // Aliases are assigned in BTreeMap order of (owner,name) then input order.
        let body = json!({"data":{"r0":{
            "b0": {
                "target": {"oid":"abc","statusCheckRollup":{"contexts":{"nodes":[
                    {"__typename":"CheckRun","status":"COMPLETED","conclusion":"SUCCESS"}
                ]}}},
                "associatedPullRequests":{"nodes":[{"number":65,"isDraft":true,"url":"u"}]}
            },
            // An unpushed branch resolves to a null ref — checked, and PR-less.
            "b1": null,
            // Pushed, but no open PR heads it.
            "b2": {
                "target": {"oid":"def","statusCheckRollup":null},
                "associatedPullRequests":{"nodes":[]}
            }
        }}});
        let out = parse_response(&body, &index);
        assert_eq!(out.len(), 3, "{out:?}");
        let Some(PrResolution::Pr(badge)) = out.get(&target("feature")) else {
            panic!("expected a badge for feature: {out:?}");
        };
        assert_eq!(badge.number, 65);
        assert!(badge.is_draft);
        assert_eq!(badge.checks, PrCheckState::Success);
        assert_eq!(badge.url, "u");
        assert_eq!(out.get(&target("unpushed")), Some(&PrResolution::NoPr));
        assert_eq!(out.get(&target("no-pr")), Some(&PrResolution::NoPr));
    }

    #[test]
    fn parse_response_reports_a_pushed_branch_with_no_pr_as_a_negative() {
        let (_, index) = build_query(&[target("quiet")]).unwrap();
        let body = json!({"data":{"r0":{"b0":{
            "target": {"oid":"abc","statusCheckRollup":null},
            "associatedPullRequests":{"nodes":[]}
        }}}});
        let out = parse_response(&body, &index);
        assert_eq!(out.get(&target("quiet")), Some(&PrResolution::NoPr));
    }

    #[test]
    fn parse_response_reports_an_unpushed_branch_as_a_negative() {
        let (_, index) = build_query(&[target("local-only")]).unwrap();
        let body = json!({"data":{"r0":{"b0":null}}});
        let out = parse_response(&body, &index);
        assert_eq!(out.get(&target("local-only")), Some(&PrResolution::NoPr));
    }

    #[test]
    fn parse_response_leaves_a_missing_alias_unresolved_rather_than_negative() {
        // Only an answer about the ref may mint a negative: a reply missing the
        // ref alias, or with a null repo alias (a repo-level failure), says
        // nothing about the branch — a false NoPr would silence the client
        // fallback for a branch that may have a PR.
        let (_, index) = build_query(&[target("x")]).unwrap();
        assert!(parse_response(&json!({"data":{"r0":{}}}), &index).is_empty());
        assert!(parse_response(&json!({"data":{"r0":null}}), &index).is_empty());
    }

    #[test]
    fn parse_response_leaves_a_malformed_pr_node_unresolved_rather_than_negative() {
        let (_, index) = build_query(&[target("x")]).unwrap();
        // The PR list is non-empty, so this is not "no PR" — but the node has no
        // readable number, so it is not a badge either. It must stay unresolved.
        let body = json!({"data":{"r0":{"b0":{
            "target": {"oid":"abc","statusCheckRollup":null},
            "associatedPullRequests":{"nodes":[{"isDraft":false,"url":"u"}]}
        }}}});
        assert!(parse_response(&body, &index).is_empty());
    }

    #[test]
    fn parse_response_reads_a_pr_with_no_checks_as_none() {
        let targets = vec![target("feature")];
        let (_, index) = build_query(&targets).unwrap();
        let body = json!({"data":{"r0":{"b0":{
            "target": {"oid":"abc","statusCheckRollup":null},
            "associatedPullRequests":{"nodes":[{"number":7,"isDraft":false,"url":"u"}]}
        }}}});
        let out = parse_response(&body, &index);
        // A PR with no checks is still a PR — PrCheckState::None, never NoPr.
        let Some(PrResolution::Pr(badge)) = out.get(&target("feature")) else {
            panic!("expected a badge: {out:?}");
        };
        assert_eq!(badge.checks, PrCheckState::None);
    }

    #[test]
    fn parse_response_tolerates_a_missing_data_block() {
        // A reply without `data` resolves nothing — and mints no negatives.
        let (_, index) = build_query(&[target("x")]).unwrap();
        assert!(parse_response(&json!({}), &index).is_empty());
    }

    // --- Wire shape ---

    #[test]
    fn badge_serializes_is_draft_as_camel_case() {
        // The extension's PrBadge inherited `isDraft` from gh's JSON. Serializing it
        // as `is_draft` would silently drop the draft marker on every row.
        let badge = PrBadge {
            number: 65,
            is_draft: true,
            checks: PrCheckState::Pending,
            url: "u".into(),
            head_oid: String::new(),
        };
        let v = serde_json::to_value(&badge).unwrap();
        assert_eq!(v["isDraft"], json!(true));
        assert_eq!(v["checks"], json!("pending"));
        assert!(v.get("is_draft").is_none(), "{v}");
    }

    #[test]
    fn check_state_serializes_lowercase() {
        for (state, want) in [
            (PrCheckState::Success, "success"),
            (PrCheckState::Failure, "failure"),
            (PrCheckState::Pending, "pending"),
            (PrCheckState::None, "none"),
        ] {
            assert_eq!(serde_json::to_value(state).unwrap(), json!(want));
        }
    }

    // --- Binary resolution ---

    #[test]
    fn resolve_gh_binary_from_prefers_env_then_candidate_then_fallback() {
        assert_eq!(
            resolve_gh_binary_from(Some("/custom/gh".into()), &["/usr/bin/gh"]),
            PathBuf::from("/custom/gh")
        );
        let existing = tempfile::NamedTempFile::new().unwrap();
        let existing_path = existing.path().to_str().unwrap();
        assert_eq!(
            resolve_gh_binary_from(None, &["/no/such/gh/xyzzy", existing_path]),
            PathBuf::from(existing_path)
        );
        assert_eq!(
            resolve_gh_binary_from(None, &["/no/such/gh/xyzzy"]),
            PathBuf::from("gh")
        );
        // An empty override falls through rather than resolving to "".
        assert_eq!(
            resolve_gh_binary_from(Some("".into()), &["/no/such/gh/xyzzy"]),
            PathBuf::from("gh")
        );
        // The real-env wrapper resolves without panicking.
        let _ = resolve_gh_binary();
    }

    // --- resolve_with: the degradation contract ---
    //
    // Badges are decoration: a missing, unauthenticated, or failing `gh` must
    // surface an error to the poller (which backs off and keeps the last good
    // badges) and never panic or hang. These cover the paths that decide that.

    /// Writes an executable stub standing in for `gh`, printing `stdout` and
    /// exiting `code`.
    ///
    /// Returns the shim serialisation lock alongside the path: the caller
    /// **must** hold the guard until it has finished exec'ing the stub, so
    /// concurrent shim subprocesses stay bounded. That lock does **not** close
    /// the `ETXTBSY` ("Text file busy") race — writing an executable and then
    /// `execve`ing it races every other thread that forks, which never takes
    /// this lock — so the caller also runs the exec through [`retry_on_etxtbsy`]
    /// (#642, #1344, #1348).
    fn fake_gh(dir: &Path, stdout: &str, code: i32) -> (PathBuf, MutexGuard<'static, ()>) {
        let guard = shim_lock();
        let path = dir.join("fake-gh");
        write_exec_script(
            &path,
            &format!("#!/bin/sh\ncat <<'JSON'\n{stdout}\nJSON\nexit {code}\n"),
        );
        (path, guard)
    }

    #[test]
    fn resolve_with_asks_nothing_for_no_targets() {
        // No branches to resolve → no subprocess at all. The binary is deliberately
        // bogus: if this spawned anything it would error instead of returning empty.
        let out = resolve_with(Path::new("/no/such/gh/xyzzy"), &[]).unwrap();
        assert!(out.is_empty());
    }

    #[test]
    fn resolve_with_errors_when_gh_is_missing() {
        // The common real case: `gh` not installed, or absent from launchd's
        // minimal PATH.
        let err = resolve_with(Path::new("/no/such/gh/xyzzy"), &[target("main")]).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("failed to run"), "{msg}");
        assert!(msg.contains("GitHub CLI"), "{msg}");
    }

    #[test]
    fn resolve_with_errors_on_a_nonzero_exit() {
        // e.g. `gh auth login` never run: gh exits non-zero and explains on stderr.
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(dir.path(), "", 1);
        let err = retry_on_etxtbsy(|| resolve_with(&bin, &[target("main")])).unwrap_err();
        assert!(
            format!("{err:#}").contains("gh api graphql failed"),
            "{err:#}"
        );
    }

    #[test]
    fn resolve_with_errors_on_unparseable_output() {
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(dir.path(), "not json at all", 0);
        let err = retry_on_etxtbsy(|| resolve_with(&bin, &[target("main")])).unwrap_err();
        assert!(format!("{err:#}").contains("invalid JSON"), "{err:#}");
    }

    #[test]
    fn resolve_with_surfaces_graphql_errors_rather_than_reporting_no_badges() {
        // A GraphQL 200 can still carry errors (a bad field, a rate limit). Reading
        // that as an empty result would be indistinguishable from "no open PRs" and
        // would silently blank every badge, so it must be an error. Doubly
        // load-bearing since #1370: the hard Err is what guarantees a failed poll
        // can never manufacture NoPr negatives.
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"data":null,"errors":[{"message":"API rate limit exceeded"}]}"#,
            0,
        );
        let err = retry_on_etxtbsy(|| resolve_with(&bin, &[target("main")])).unwrap_err();
        let msg = format!("{err:#}");
        assert!(msg.contains("returned errors"), "{msg}");
        assert!(msg.contains("rate limit"), "{msg}");
    }

    #[test]
    fn resolve_with_ignores_an_empty_errors_array() {
        // Some responses carry `errors: []`; that is a success, not a failure.
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"errors":[],"data":{"r0":{"b0":{
                "target":{"oid":"a","statusCheckRollup":null},
                "associatedPullRequests":{"nodes":[{"number":9,"isDraft":false,"url":"u"}]}}}}}"#,
            0,
        );
        let out = retry_on_etxtbsy(|| resolve_with(&bin, &[target("main")])).unwrap();
        let Some(PrResolution::Pr(badge)) = out.get(&target("main")) else {
            panic!("expected a badge: {out:?}");
        };
        assert_eq!(badge.number, 9);
    }

    #[test]
    fn resolve_with_reads_a_real_reply_end_to_end() {
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"a","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"COMPLETED","conclusion":"FAILURE"}
                ]}}},
                "associatedPullRequests":{"nodes":[{"number":42,"isDraft":true,"url":"u42"}]}}}}}"#,
            0,
        );
        let out = retry_on_etxtbsy(|| resolve_with(&bin, &[target("main")])).unwrap();
        let Some(PrResolution::Pr(badge)) = out.get(&target("main")) else {
            panic!("expected a badge: {out:?}");
        };
        assert_eq!(badge.number, 42);
        assert!(badge.is_draft);
        assert_eq!(badge.checks, PrCheckState::Failure);
    }

    #[test]
    fn resolve_with_reports_negatives_alongside_badges_end_to_end() {
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"data":{"r0":{
                "b0":{
                    "target":{"oid":"a","statusCheckRollup":null},
                    "associatedPullRequests":{"nodes":[{"number":7,"isDraft":false,"url":"u"}]}},
                "b1":null,
                "b2":{
                    "target":{"oid":"b","statusCheckRollup":null},
                    "associatedPullRequests":{"nodes":[]}}}}}"#,
            0,
        );
        let targets = vec![target("main"), target("unpushed"), target("quiet")];
        let out = retry_on_etxtbsy(|| resolve_with(&bin, &targets)).unwrap();
        assert_eq!(out.len(), 3, "{out:?}");
        assert!(
            matches!(out.get(&target("main")), Some(PrResolution::Pr(b)) if b.number == 7),
            "{out:?}"
        );
        assert_eq!(out.get(&target("unpushed")), Some(&PrResolution::NoPr));
        assert_eq!(out.get(&target("quiet")), Some(&PrResolution::NoPr));
    }

    // --- Cache ---

    /// A pending badge wrapped as a resolution, for cache fixtures.
    fn pending_pr(number: u64) -> PrResolution {
        PrResolution::Pr(PrBadge {
            number,
            is_draft: false,
            checks: PrCheckState::Pending,
            url: "u".into(),
            head_oid: String::new(),
        })
    }

    #[test]
    fn cache_replace_reports_whether_anything_changed() {
        let cache = PrStatusCache::new();
        let mut map = HashMap::new();
        map.insert(target("f"), pending_pr(1));

        // First write is a change.
        assert!(cache.replace(map.clone()));
        // An identical write is not — this is what keeps the poller from re-pushing
        // an unchanged snapshot to every window on every tick.
        assert!(!cache.replace(map.clone()));

        // A changed verdict is a change.
        let mut moved = map.clone();
        if let Some(PrResolution::Pr(badge)) = moved.get_mut(&target("f")) {
            badge.checks = PrCheckState::Success;
        }
        assert!(cache.replace(moved));
        // Emptying is a change.
        assert!(cache.replace(HashMap::new()));
        assert!(!cache.replace(HashMap::new()));
    }

    #[test]
    fn cache_replace_counts_a_new_negative_as_a_change() {
        let cache = PrStatusCache::new();
        let mut negatives = HashMap::new();
        negatives.insert(target("f"), PrResolution::NoPr);

        // The first round of negatives is a change — the one push that delivers
        // them to clients so their fallback goes quiet.
        assert!(cache.replace(negatives.clone()));
        // Re-polling the same answer is not.
        assert!(!cache.replace(negatives.clone()));

        // A PR opening (negative → badge) and closing (badge → negative) are both
        // real transitions.
        let mut opened = HashMap::new();
        opened.insert(target("f"), pending_pr(1));
        assert!(cache.replace(opened));
        assert!(cache.replace(negatives));
    }

    #[test]
    fn cache_any_pending_ignores_negative_resolutions() {
        // A negative is terminal: it must never hold the poller's fast cadence.
        let cache = PrStatusCache::new();
        let mut map = HashMap::new();
        map.insert(target("f"), PrResolution::NoPr);
        cache.replace(map);
        assert!(!cache.any_pending());
    }

    #[test]
    fn cache_get_and_any_pending() {
        let cache = PrStatusCache::new();
        assert!(cache.get("rust-works", "omni-dev", "f").is_none());
        assert!(!cache.any_pending());

        let mut map = HashMap::new();
        map.insert(target("f"), pending_pr(1));
        cache.replace(map.clone());
        assert!(
            matches!(
                cache.get("rust-works", "omni-dev", "f"),
                Some(PrResolution::Pr(b)) if b.number == 1
            ),
            "expected the cached badge back"
        );
        assert!(cache.any_pending());
        // A miss on a branch we never resolved.
        assert!(cache.get("rust-works", "omni-dev", "other").is_none());

        if let Some(PrResolution::Pr(badge)) = map.get_mut(&target("f")) {
            badge.checks = PrCheckState::Success;
        }
        cache.replace(map);
        assert!(!cache.any_pending());
    }

    #[test]
    fn cache_retain_targets_drops_only_the_vanished_entries() {
        // A pure removal (a worktree closed) must prune its verdict without a fetch
        // (#1389, fix 1), leaving the survivors untouched.
        let cache = PrStatusCache::new();
        let mut map = HashMap::new();
        map.insert(target("keep"), pending_pr(1));
        map.insert(target("drop"), pending_pr(2));
        cache.replace(map);

        let keep: HashSet<PrTarget> = std::iter::once(target("keep")).collect();
        assert!(cache.retain_targets(&keep), "a target was removed");
        assert!(cache.get("rust-works", "omni-dev", "keep").is_some());
        assert!(cache.get("rust-works", "omni-dev", "drop").is_none());
        // Idempotent: nothing left to remove reports no change.
        assert!(!cache.retain_targets(&keep));
    }

    #[test]
    fn cache_seed_then_entries_round_trips_without_a_bump() {
        // A warm start seeds restored verdicts so they render before the first poll
        // (#1389, fix 4); `entries` reads them back for the next persist.
        let cache = PrStatusCache::new();
        cache.seed([
            (target("f"), pending_pr(7)),
            (target("g"), PrResolution::NoPr),
        ]);
        assert!(matches!(
            cache.get("rust-works", "omni-dev", "f"),
            Some(PrResolution::Pr(b)) if b.number == 7
        ));
        assert!(matches!(
            cache.get("rust-works", "omni-dev", "g"),
            Some(PrResolution::NoPr)
        ));
        let mut entries = cache.entries();
        entries.sort_by(|a, b| a.0.cmp(&b.0));
        assert_eq!(entries.len(), 2);
        assert_eq!(entries[0].0, target("f"));
        assert_eq!(entries[1].0, target("g"));
    }

    // --- Merge-queue eligibility & enqueue (#1401) ---

    #[test]
    fn merge_query_asks_for_the_enqueue_fields() {
        let (query, index) = build_merge_query(&[target("main")]).unwrap();
        // The fields the badge poll never asks for but enqueue/eligibility need.
        for field in [
            "id",
            "headRefOid",
            "mergeStateStatus",
            "mergeQueueEntry{ state }",
        ] {
            assert!(query.contains(field), "missing {field}: {query}");
        }
        // Still reads the open PR off the Ref (not the Commit) and reuses the rollup.
        assert!(
            query.contains("associatedPullRequests(first:1, states:OPEN)"),
            "{query}"
        );
        assert!(query.contains("checkSuite{ status }"), "{query}");
        // No `rateLimit` fold — this is not the hot-path poll.
        assert!(!query.contains("rateLimit"), "{query}");
        assert_eq!(index.len(), 1);
    }

    #[test]
    fn merge_query_is_none_without_targets() {
        assert!(build_merge_query(&[]).is_none());
    }

    #[test]
    fn parse_merge_response_reads_pr_facts_and_already_queued() {
        let (_, index) = build_merge_query(&[target("ready"), target("queued")]).unwrap();
        // Aliases: BTreeMap by (owner,name) then input order → b0=ready, b1=queued.
        let body = json!({"data":{"r0":{
            "b0":{
                "target":{"oid":"sha-ready","statusCheckRollup":{"contexts":{"nodes":[
                    {"__typename":"CheckRun","status":"COMPLETED","conclusion":"SUCCESS"}
                ]}}},
                "associatedPullRequests":{"nodes":[{
                    "id":"PR_ready","number":10,"isDraft":false,
                    "url":"https://github.com/rust-works/omni-dev/pull/10",
                    "headRefOid":"sha-ready","mergeStateStatus":"CLEAN","mergeQueueEntry":null
                }]}
            },
            "b1":{
                "target":{"oid":"sha-q","statusCheckRollup":null},
                "associatedPullRequests":{"nodes":[{
                    "id":"PR_queued","number":11,"isDraft":true,
                    "url":"https://github.com/rust-works/omni-dev/pull/11",
                    "headRefOid":"sha-q","mergeStateStatus":"BLOCKED",
                    "mergeQueueEntry":{"state":"QUEUED"}
                }]}
            }
        }}});
        let out = parse_merge_response(&body, &index);

        let ready = out.get(&target("ready")).expect("ready resolved");
        assert_eq!(ready.pr_id, "PR_ready");
        assert_eq!(ready.number, 10);
        assert_eq!(ready.head_oid, "sha-ready");
        assert_eq!(ready.merge_state.as_deref(), Some("CLEAN"));
        assert!(!ready.is_draft);
        assert!(!ready.already_queued);
        assert_eq!(ready.checks, PrCheckState::Success);

        let queued = out.get(&target("queued")).expect("queued resolved");
        assert!(queued.is_draft);
        assert!(queued.already_queued);
        assert_eq!(queued.merge_state.as_deref(), Some("BLOCKED"));
        // No rollup nodes → no checks reported.
        assert_eq!(queued.checks, PrCheckState::None);
    }

    #[test]
    fn parse_merge_response_treats_absent_or_prless_refs_as_skips() {
        let (_, index) = build_merge_query(&[target("null-ref"), target("no-pr")]).unwrap();
        let body = json!({"data":{"r0":{
            // A never-pushed branch: the aliased ref is null.
            "b0": null,
            // Pushed, but no open PR heads it.
            "b1": {
                "target":{"oid":"x","statusCheckRollup":null},
                "associatedPullRequests":{"nodes":[]}
            }
        }}});
        let out = parse_merge_response(&body, &index);
        // Neither is enqueue-eligible, so neither appears — the caller maps the
        // absence to a `no-pr` skip.
        assert!(out.is_empty(), "{out:?}");
    }

    #[test]
    fn merge_info_requires_an_id_and_number() {
        // A PR node missing `id` (a malformed/partial reply) is unresolved, never a
        // half-built MergeInfo we might try to enqueue.
        let node = json!({
            "target":{"oid":"x","statusCheckRollup":null},
            "associatedPullRequests":{"nodes":[{"number":9,"url":"u"}]}
        });
        assert!(merge_info_from_ref(&node).is_none());
    }

    #[test]
    fn enqueue_error_message_joins_or_falls_back() {
        let errs = vec![
            json!({"message":"Merge queue is not enabled"}),
            json!({"message":"Pull request is not mergeable"}),
        ];
        assert_eq!(
            enqueue_error_message(&errs),
            "Merge queue is not enabled; Pull request is not mergeable"
        );
        // No readable messages → a generic-but-non-empty reason.
        assert_eq!(
            enqueue_error_message(&[json!({"code":"X"})]),
            "enqueue rejected by GitHub"
        );
    }

    #[test]
    fn parse_merge_response_tolerates_a_missing_data_block() {
        // A reply with no `data` (e.g. a top-level error already handled upstream)
        // yields no targets rather than panicking.
        let (_, index) = build_merge_query(&[target("main")]).unwrap();
        assert!(parse_merge_response(&json!({}), &index).is_empty());
    }

    #[test]
    fn resolve_merge_targets_asks_nothing_for_no_targets() {
        // No branches → no subprocess at all; the bogus binary would error if spawned.
        let out = resolve_merge_targets(Path::new("/no/such/gh/xyzzy"), &[]).unwrap();
        assert!(out.is_empty());
    }

    #[test]
    fn resolve_merge_targets_reads_a_reply_end_to_end() {
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"data":{"r0":{"b0":{
                "target":{"oid":"a","statusCheckRollup":{"contexts":{"nodes":[
                  {"__typename":"CheckRun","status":"COMPLETED","conclusion":"SUCCESS"}
                ]}}},
                "associatedPullRequests":{"nodes":[{
                  "id":"PR_1","number":42,"isDraft":false,"url":"u42",
                  "headRefOid":"a","mergeStateStatus":"CLEAN","mergeQueueEntry":null
                }]}}}}}"#,
            0,
        );
        let out = retry_on_etxtbsy(|| resolve_merge_targets(&bin, &[target("main")])).unwrap();
        let info = out.get(&target("main")).expect("resolved");
        assert_eq!(info.pr_id, "PR_1");
        assert_eq!(info.number, 42);
        assert_eq!(info.head_oid, "a");
        assert_eq!(info.merge_state.as_deref(), Some("CLEAN"));
        assert!(!info.already_queued);
        assert_eq!(info.checks, PrCheckState::Success);
    }

    #[test]
    fn resolve_merge_targets_errors_on_a_graphql_errors_body() {
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"errors":[{"message":"Something is wrong"}]}"#,
            0,
        );
        let err = retry_on_etxtbsy(|| resolve_merge_targets(&bin, &[target("main")])).unwrap_err();
        assert!(format!("{err:#}").contains("returned errors"), "{err:#}");
    }

    #[test]
    fn enqueue_pull_request_reports_queued_on_success() {
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"data":{"enqueuePullRequest":{"mergeQueueEntry":{"state":"QUEUED"}}}}"#,
            0,
        );
        let out = retry_on_etxtbsy(|| enqueue_pull_request(&bin, "PR_1")).unwrap();
        assert_eq!(out, EnqueueOutcome::Queued(Some("QUEUED".to_string())));
    }

    #[test]
    fn enqueue_pull_request_maps_a_nonzero_exit_to_rejected() {
        // `gh` exits non-zero on a rejected mutation; the reason is read from the
        // JSON `errors` body (preferred over stderr).
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"errors":[{"message":"Merge queue is not enabled on this repository"}]}"#,
            1,
        );
        let out = retry_on_etxtbsy(|| enqueue_pull_request(&bin, "PR_1")).unwrap();
        assert_eq!(
            out,
            EnqueueOutcome::Rejected("Merge queue is not enabled on this repository".to_string())
        );
    }

    #[test]
    fn enqueue_pull_request_maps_a_200_with_errors_to_rejected() {
        // A GraphQL 200 can still carry errors (a partial success); treat it as a
        // per-PR rejection, not a batch-sinking error.
        let dir = tempfile::tempdir().unwrap();
        let (bin, _shim) = fake_gh(
            dir.path(),
            r#"{"errors":[{"message":"Pull request is not mergeable"}]}"#,
            0,
        );
        let out = retry_on_etxtbsy(|| enqueue_pull_request(&bin, "PR_1")).unwrap();
        assert_eq!(
            out,
            EnqueueOutcome::Rejected("Pull request is not mergeable".to_string())
        );
    }
}