devboy-linear 0.33.0

Linear provider for devboy-tools — GraphQL-backed IssueProvider/Provider skeleton with liveness support.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
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
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
//! Linear GraphQL client implementation.

use async_trait::async_trait;
use devboy_core::{
    Comment, CreateIssueInput, Error, Issue, IssueFilter, IssueProvider, IssueStatus,
    MergeRequestProvider, Pagination, PipelineProvider, Provider, ProviderResult, Result, SortInfo,
    SortOrder, UpdateIssueInput, User,
};
use secrecy::{ExposeSecret, SecretString};
use serde_json::{Map, Value, json};
use tracing::debug;

use crate::DEFAULT_LINEAR_URL;
use crate::types::{
    GraphQlResponse, LinearComment, LinearCommentCreateData, LinearIssue, LinearIssueCommentsData,
    LinearIssueCreateData, LinearIssueData, LinearIssueLabelsData, LinearIssueUpdateData,
    LinearIssuesData, LinearUser, LinearUsersData, LinearWorkflowState,
    LinearWorkflowStateConnection, LinearWorkflowStatesData, Viewer, ViewerData,
};

const VIEWER_QUERY: &str = r#"
query Viewer {
  viewer {
    id
    name
    displayName
    email
  }
}
"#;

const ISSUE_BY_ID_QUERY: &str = r#"
query IssueById($id: String!) {
  issue(id: $id) {
    id
    identifier
    title
    description
    priority
    url
    createdAt
    updatedAt
    state {
      name
      type
    }
    labels {
      nodes {
        name
      }
    }
    assignee {
      id
      name
      displayName
      email
      avatarUrl
    }
    parent {
      identifier
    }
    team {
      id
      key
    }
  }
}
"#;

const ISSUES_QUERY: &str = r#"
query Issues($first: Int!, $after: String, $filter: IssueFilter, $orderBy: PaginationOrderBy) {
  issues(first: $first, after: $after, filter: $filter, orderBy: $orderBy) {
    nodes {
      id
      identifier
      title
      description
      priority
      url
      createdAt
      updatedAt
      state {
        name
        type
      }
      labels {
        nodes {
          name
        }
      }
      assignee {
        id
        name
        displayName
        email
        avatarUrl
      }
      parent {
        identifier
      }
      team {
        id
        key
      }
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
"#;

const USERS_QUERY: &str = r#"
query Users($first: Int!, $filter: UserFilter) {
  users(first: $first, filter: $filter) {
    nodes {
      id
      name
      displayName
      email
      avatarUrl
    }
  }
}
"#;

const ISSUE_LABELS_QUERY: &str = r#"
query IssueLabels($first: Int!, $filter: IssueLabelFilter) {
  issueLabels(first: $first, filter: $filter) {
    nodes {
      id
      name
    }
  }
}
"#;

const ISSUE_CREATE_MUTATION: &str = r#"
mutation IssueCreate($input: IssueCreateInput!) {
  issueCreate(input: $input) {
    success
    issue {
      id
      identifier
      title
      description
      priority
      url
      createdAt
      updatedAt
      state {
        name
        type
      }
      labels {
        nodes {
          name
        }
      }
      assignee {
        id
        name
        displayName
        email
        avatarUrl
      }
      parent {
        identifier
      }
      team {
        id
        key
      }
    }
  }
}
"#;

const WORKFLOW_STATES_QUERY: &str = r#"
query WorkflowStates($first: Int!, $after: String, $filter: WorkflowStateFilter) {
  workflowStates(first: $first, after: $after, filter: $filter) {
    nodes {
      id
      name
      type
    }
    pageInfo {
      hasNextPage
      endCursor
    }
  }
}
"#;

const ISSUE_UPDATE_MUTATION: &str = r#"
mutation IssueUpdate($id: String!, $input: IssueUpdateInput!) {
  issueUpdate(id: $id, input: $input) {
    success
    issue {
      id
      identifier
      title
      description
      priority
      url
      createdAt
      updatedAt
      state {
        name
        type
      }
      labels {
        nodes {
          name
        }
      }
      assignee {
        id
        name
        displayName
        email
        avatarUrl
      }
      parent {
        identifier
      }
      team {
        id
        key
      }
    }
  }
}
"#;

const ISSUE_COMMENTS_QUERY: &str = r#"
query IssueComments($id: String!, $first: Int!, $after: String) {
  issue(id: $id) {
    comments(first: $first, after: $after) {
      nodes {
        id
        body
        createdAt
        updatedAt
        user {
          id
          name
          displayName
          email
          avatarUrl
        }
      }
      pageInfo {
        hasNextPage
        endCursor
      }
    }
  }
}
"#;

const COMMENT_CREATE_MUTATION: &str = r#"
mutation CommentCreate($input: CommentCreateInput!) {
  commentCreate(input: $input) {
    success
    comment {
      id
      body
      createdAt
      updatedAt
      user {
        id
        name
        displayName
        email
        avatarUrl
      }
    }
  }
}
"#;

pub struct LinearClient {
    base_url: String,
    team_id: String,
    team_key: Option<String>,
    token: SecretString,
    http: reqwest::Client,
}

impl LinearClient {
    pub fn new(team_id: impl Into<String>, token: SecretString) -> Self {
        Self::with_base_url(DEFAULT_LINEAR_URL, team_id, token)
    }

    pub fn with_base_url(
        base_url: impl Into<String>,
        team_id: impl Into<String>,
        token: SecretString,
    ) -> Self {
        Self {
            base_url: base_url.into().trim_end_matches('/').to_string(),
            team_id: team_id.into(),
            team_key: None,
            token,
            http: reqwest::Client::builder()
                .user_agent("devboy-tools")
                .build()
                .expect("Failed to create HTTP client"),
        }
    }

    pub fn with_team_key(mut self, team_key: impl Into<String>) -> Self {
        self.team_key = Some(team_key.into());
        self
    }

    pub fn team_id(&self) -> &str {
        &self.team_id
    }

    pub fn team_key(&self) -> Option<&str> {
        self.team_key.as_deref()
    }

    pub(crate) async fn viewer_with_token(&self, token: &SecretString) -> Result<Viewer> {
        let data: ViewerData = self.graphql(VIEWER_QUERY, json!({}), token).await?;
        Ok(data.viewer)
    }

    async fn graphql<T: serde::de::DeserializeOwned>(
        &self,
        query: &str,
        variables: Value,
        token: &SecretString,
    ) -> Result<T> {
        let body = json!({
            "query": query,
            "variables": variables,
        });

        debug!(url = %self.base_url, "linear graphql request");

        let response = self
            .http
            .post(&self.base_url)
            .header("Authorization", token.expose_secret())
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .json(&body)
            .send()
            .await
            .map_err(|e| Error::Network(e.to_string()))?;

        let status = response.status();
        if status == reqwest::StatusCode::UNAUTHORIZED {
            return Err(Error::Unauthorized("Invalid Linear API token".to_string()));
        }
        if status == reqwest::StatusCode::TOO_MANY_REQUESTS {
            return Err(Error::RateLimited {
                retry_after: parse_retry_after(response.headers()),
            });
        }
        if !status.is_success() {
            let text = response.text().await.unwrap_or_default();
            return Err(Error::Api {
                status: status.as_u16(),
                message: text,
            });
        }

        // Linear also signals throttling inside a 200 response via the
        // RATELIMITED error extension, so keep the headers around before the
        // body is consumed.
        let retry_after = parse_retry_after(response.headers());

        let gql_response: GraphQlResponse<T> = response
            .json()
            .await
            .map_err(|e| Error::InvalidData(e.to_string()))?;

        if !gql_response.errors.is_empty() {
            let rate_limited = gql_response.errors.iter().any(|e| {
                e.extensions.as_ref().and_then(|x| x.code.as_deref()) == Some("RATELIMITED")
            });
            let message = gql_response
                .errors
                .into_iter()
                .map(|e| e.message)
                .collect::<Vec<_>>()
                .join("; ");
            return if rate_limited {
                // `Error::RateLimited` carries no message, so keep Linear's
                // wording in the log instead of dropping it silently.
                debug!(%message, "linear graphql rate limited");
                Err(Error::RateLimited { retry_after })
            } else {
                Err(Error::Api {
                    status: 200,
                    message,
                })
            };
        }

        gql_response
            .data
            .ok_or_else(|| Error::InvalidData("Linear API returned no data".to_string()))
    }

    async fn list_issues_page(
        &self,
        first: u32,
        after: Option<&str>,
        filter: Value,
        order_by: &str,
    ) -> Result<LinearIssuesData> {
        let variables = json!({
            "first": first,
            "after": after,
            "filter": filter,
            "orderBy": order_by,
        });
        self.graphql(ISSUES_QUERY, variables, &self.token).await
    }

    async fn get_linear_issue_by_native_id(&self, id: &str) -> Result<Option<LinearIssue>> {
        let data: LinearIssueData = self
            .graphql(ISSUE_BY_ID_QUERY, json!({ "id": id }), &self.token)
            .await?;
        Ok(data.issue.filter(|issue| {
            issue
                .team
                .as_ref()
                .is_some_and(|team| team.id == self.team_id)
        }))
    }

    async fn get_linear_issue_by_identifier(
        &self,
        identifier: &str,
    ) -> Result<Option<LinearIssue>> {
        let (prefix, number) = parse_linear_identifier(identifier).ok_or_else(|| {
            Error::InvalidData(format!(
                "Linear issue key '{identifier}' must be a UUID or team-key identifier like ENG-123"
            ))
        })?;

        if let Some(team_key) = self.team_key()
            && !prefix.eq_ignore_ascii_case(team_key)
        {
            return Ok(None);
        }

        let filter = json!({
            "and": [
                {
                    "team": {
                        "id": {
                            "eq": self.team_id
                        }
                    }
                },
                {
                    "number": {
                        "eq": number
                    }
                }
            ]
        });

        // Single exact-identifier lookup — ordering is irrelevant here.
        let data = self.list_issues_page(1, None, filter, "updatedAt").await?;
        Ok(data.issues.nodes.into_iter().next())
    }

    async fn resolve_scoped_issue(&self, key: &str) -> Result<LinearIssue> {
        let issue = if looks_like_uuid(key) {
            self.get_linear_issue_by_native_id(key).await?
        } else {
            self.get_linear_issue_by_identifier(key).await?
        };

        issue.ok_or_else(|| Error::NotFound(format!("Linear issue not found: {key}")))
    }

    async fn resolve_assignee_id(&self, assignee: &str) -> Result<String> {
        if looks_like_uuid(assignee) {
            return Ok(assignee.to_string());
        }

        let filter = json!({
            "or": [
                {
                    "name": {
                        "eqIgnoreCase": assignee
                    }
                },
                {
                    "displayName": {
                        "eqIgnoreCase": assignee
                    }
                },
                {
                    "email": {
                        "eqIgnoreCase": assignee
                    }
                }
            ]
        });
        let variables = json!({
            "first": 10,
            "filter": filter,
        });
        let data: LinearUsersData = self.graphql(USERS_QUERY, variables, &self.token).await?;
        let user = data
            .users
            .nodes
            .into_iter()
            .find(|user| {
                user.name.eq_ignore_ascii_case(assignee)
                    || user
                        .display_name
                        .as_deref()
                        .is_some_and(|display| display.eq_ignore_ascii_case(assignee))
                    || user
                        .email
                        .as_deref()
                        .is_some_and(|email| email.eq_ignore_ascii_case(assignee))
            })
            .ok_or_else(|| Error::NotFound(format!("Linear user not found: {assignee}")))?;
        Ok(user.id)
    }

    async fn resolve_label_ids(&self, labels: &[String]) -> Result<Vec<String>> {
        if labels.is_empty() {
            return Ok(Vec::new());
        }

        let variables = json!({
            "first": 100,
            "filter": {
                "team": {
                    "id": {
                        "eq": self.team_id
                    }
                },
                "name": {
                    "in": labels
                }
            }
        });
        let data: LinearIssueLabelsData = self
            .graphql(ISSUE_LABELS_QUERY, variables, &self.token)
            .await?;

        let mut ids = Vec::with_capacity(labels.len());
        let mut missing = Vec::new();
        for wanted in labels {
            if let Some(label) = data
                .issue_labels
                .nodes
                .iter()
                .find(|label| label.name.eq_ignore_ascii_case(wanted))
            {
                ids.push(label.id.clone());
            } else {
                missing.push(wanted.clone());
            }
        }

        if !missing.is_empty() {
            return Err(Error::NotFound(format!(
                "Linear labels not found for team {}: {}",
                self.team_id,
                missing.join(", ")
            )));
        }

        Ok(ids)
    }

    async fn resolve_parent_id(&self, parent: &str) -> Result<String> {
        if looks_like_uuid(parent) {
            return Ok(parent.to_string());
        }

        let issue = self
            .get_linear_issue_by_identifier(parent)
            .await?
            .ok_or_else(|| Error::NotFound(format!("Linear parent issue not found: {parent}")))?;
        Ok(issue.id)
    }

    async fn resolve_workflow_state_id(&self, state: &str) -> Result<String> {
        let state = state.trim();
        if state.is_empty() {
            return Err(Error::InvalidData(
                "Linear state/status must not be empty".to_string(),
            ));
        }

        let data = self.list_workflow_states().await?;
        let nodes = data.workflow_states.nodes;

        // An exact state name always wins over the category aliases below.
        // Linear's own default states are literally called "Done", "Todo",
        // "Backlog" and "Canceled"; resolving those by category first would
        // shadow them and could land on a different state of the same type
        // (a team with both "Done" and "Released" is ordinary), silently
        // setting a status the caller never asked for.
        if let Some(node) = nodes
            .iter()
            .find(|node| node.name.eq_ignore_ascii_case(state))
        {
            return Ok(node.id.clone());
        }

        // Not a state name on this team — fall back to the shared category
        // vocabulary. Which state is chosen among several of the same type
        // follows the order Linear returns them in; callers who need a
        // specific one should name it exactly, which the branch above honours.
        let target_type = match state.to_ascii_lowercase().as_str() {
            "open" | "opened" => None,
            "closed" => Some("completed"),
            "cancelled" | "canceled" => Some("canceled"),
            "backlog" => Some("backlog"),
            "todo" => Some("unstarted"),
            "in_progress" | "in progress" | "started" => Some("started"),
            "done" | "completed" => Some("completed"),
            _ => {
                return Err(Error::NotFound(format!(
                    "Linear workflow state not found by name '{}' in team {}; \
                     available: {}",
                    state,
                    self.team_id,
                    nodes
                        .iter()
                        .map(|node| node.name.as_str())
                        .collect::<Vec<_>>()
                        .join(", ")
                )));
            }
        };

        let state_id = match target_type {
            Some(target_type) => nodes
                .into_iter()
                .find(|node| node.r#type.as_deref() == Some(target_type))
                .map(|node| node.id),
            // "open" means any non-terminal state.
            None => nodes
                .into_iter()
                .find(|node| {
                    !matches!(node.r#type.as_deref(), Some("completed") | Some("canceled"))
                })
                .map(|node| node.id),
        };

        state_id.ok_or_else(|| {
            Error::NotFound(format!(
                "Linear workflow state not found for '{}' in team {}",
                state, self.team_id
            ))
        })
    }

    /// Every workflow state on the team, following the connection cursor.
    ///
    /// A single `first: 100` page silently truncates larger teams, and a
    /// truncated list makes `resolve_workflow_state_id` miss an exact name and
    /// fall back to the category branch — landing on a different state of the
    /// same type. That is precisely the mis-set-status bug this resolver
    /// exists to avoid, so the list has to be complete.
    async fn list_workflow_states(&self) -> Result<LinearWorkflowStatesData> {
        // Bounded so a server that always reports another page cannot spin.
        const MAX_PAGES: usize = 50;

        let mut nodes = Vec::new();
        let mut after: Option<String> = None;

        for _ in 0..MAX_PAGES {
            let variables = json!({
                "first": 100,
                "after": after,
                "filter": { "team": { "id": { "eq": self.team_id } } }
            });
            let page: LinearWorkflowStatesData = self
                .graphql(WORKFLOW_STATES_QUERY, variables, &self.token)
                .await?;
            let connection = page.workflow_states;
            nodes.extend(connection.nodes);

            match connection.page_info {
                Some(info) if info.has_next_page => match info.end_cursor {
                    // A cursor-less "there is more" would restart from the
                    // beginning and loop; treat it as a protocol error.
                    Some(cursor) => after = Some(cursor),
                    None => {
                        return Err(Error::InvalidData(
                            "Linear reported more workflow states but returned no cursor"
                                .to_string(),
                        ));
                    }
                },
                _ => {
                    return Ok(LinearWorkflowStatesData {
                        workflow_states: LinearWorkflowStateConnection {
                            nodes,
                            page_info: None,
                        },
                    });
                }
            }
        }

        Err(Error::InvalidData(format!(
            "Linear still reported more workflow states after {MAX_PAGES} pages"
        )))
    }

    fn map_create_priority(priority: Option<&str>) -> Result<Option<i32>> {
        let Some(priority) = priority.map(str::trim).filter(|p| !p.is_empty()) else {
            return Ok(None);
        };

        match priority.to_ascii_lowercase().as_str() {
            "none" | "no priority" => Ok(Some(0)),
            "urgent" => Ok(Some(1)),
            "high" => Ok(Some(2)),
            "normal" | "medium" => Ok(Some(3)),
            "low" => Ok(Some(4)),
            other => match other.parse::<i32>() {
                Ok(value @ 0..=4) => Ok(Some(value)),
                _ => Err(Error::InvalidData(format!(
                    "Unsupported Linear priority '{priority}'. Expected urgent/high/normal/low or 0-4"
                ))),
            },
        }
    }
}

fn parse_linear_identifier(key: &str) -> Option<(&str, i64)> {
    let (prefix, number) = key.rsplit_once('-')?;
    let number = number.parse().ok()?;
    if prefix.is_empty() {
        return None;
    }
    Some((prefix, number))
}

fn looks_like_uuid(key: &str) -> bool {
    let mut hex_count = 0usize;
    let mut hyphen_count = 0usize;
    for ch in key.chars() {
        if ch == '-' {
            hyphen_count += 1;
        } else if ch.is_ascii_hexdigit() {
            hex_count += 1;
        } else {
            return false;
        }
    }
    hyphen_count == 4 && hex_count >= 32
}

fn map_user(user: Option<&LinearUser>) -> Option<User> {
    user.map(|u| User {
        id: u.id.clone(),
        username: u.display_name.clone().unwrap_or_else(|| u.name.clone()),
        name: Some(u.name.clone()),
        email: u.email.clone(),
        avatar_url: u.avatar_url.clone(),
    })
}

fn map_priority(priority: Option<i32>) -> Option<String> {
    priority.and_then(|p| match p {
        0 => None,
        1 => Some("urgent".to_string()),
        2 => Some("high".to_string()),
        3 => Some("normal".to_string()),
        4 => Some("low".to_string()),
        other => Some(other.to_string()),
    })
}

fn map_issue(issue: &LinearIssue) -> Issue {
    Issue {
        custom_fields: std::collections::HashMap::new(),
        key: if issue.identifier.is_empty() {
            format!("linear#{}", issue.id)
        } else {
            issue.identifier.clone()
        },
        title: issue.title.clone(),
        description: issue.description.clone(),
        // `state` stays binary open/closed like every other provider, so
        // cross-provider filters keep working. The rich workflow state name
        // goes to `status` and its unified bucket to `status_category`.
        state: map_state(issue.state.as_ref()),
        status: issue
            .state
            .as_ref()
            .map(|state| state.name.clone())
            .filter(|name| !name.is_empty()),
        status_category: issue
            .state
            .as_ref()
            .and_then(|state| state.r#type.as_deref())
            .and_then(map_status_category)
            .map(str::to_string),
        source: "linear".to_string(),
        priority: map_priority(issue.priority),
        labels: issue
            .labels
            .nodes
            .iter()
            .map(|label| label.name.clone())
            .collect(),
        author: None,
        assignees: map_user(issue.assignee.as_ref()).into_iter().collect(),
        url: issue.url.clone(),
        created_at: issue.created_at.clone(),
        updated_at: issue.updated_at.clone(),
        attachments_count: None,
        parent: issue
            .parent
            .as_ref()
            .map(|parent| parent.identifier.clone()),
        subtasks: Vec::new(),
    }
}

fn map_comment(comment: &LinearComment) -> Comment {
    Comment {
        id: comment.id.clone(),
        body: comment.body.clone().unwrap_or_default(),
        author: map_user(comment.user.as_ref()),
        created_at: comment.created_at.clone(),
        updated_at: comment.updated_at.clone(),
        position: None,
    }
}

/// Default sort field, matching the `get_issues` tool contract
/// ("default: updated_at"). Linear's own default is `createdAt`, so it is
/// always sent explicitly rather than relying on the server default.
const DEFAULT_SORT_BY: &str = "updated_at";

/// Maps the cross-provider `sort_by` value onto Linear's
/// `PaginationOrderBy` enum, which only accepts these two fields.
fn map_order_by(sort_by: Option<&str>) -> Result<&'static str> {
    match sort_by.map(str::trim).unwrap_or(DEFAULT_SORT_BY) {
        "created_at" => Ok("createdAt"),
        "updated_at" => Ok("updatedAt"),
        other => Err(Error::InvalidData(format!(
            "unsupported sort_by '{other}' for Linear; expected one of: created_at, updated_at"
        ))),
    }
}

/// Linear paginates in descending order and exposes no ascending variant on
/// `PaginationOrderBy`, so `desc` is accepted and `asc` is refused with a
/// message naming the argument.
///
/// Deliberately **not** `ProviderUnsupported`: that variant means "this
/// provider cannot handle this tool at all" and the MCP layer swallows it to
/// try the next provider, which would surface the misleading
/// "No provider supports 'get_issues'".
fn validate_sort_order(sort_order: Option<&str>) -> Result<()> {
    match sort_order.map(str::trim) {
        None | Some("") | Some("desc") => Ok(()),
        Some(other) => Err(Error::InvalidData(format!(
            "unsupported sort_order '{other}' for Linear; only 'desc' is available \
             because Linear's pagination has no ascending order"
        ))),
    }
}

/// Unified status categories this provider accepts as a filter and emits as
/// [`Issue::status_category`]. Single source of truth — the schema enricher
/// advertises exactly these values.
pub(crate) const STATE_CATEGORIES: &[&str] =
    &["backlog", "todo", "in_progress", "done", "cancelled"];

/// Seconds to wait before retrying, from a throttled Linear response.
///
/// Prefers the standard `Retry-After` (delta-seconds form); falls back to
/// Linear's `X-RateLimit-Requests-Reset`, which is an epoch timestamp in
/// **milliseconds** and therefore has to be converted to a delta.
fn parse_retry_after(headers: &reqwest::header::HeaderMap) -> Option<u64> {
    if let Some(seconds) = headers
        .get(reqwest::header::RETRY_AFTER)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.trim().parse::<u64>().ok())
    {
        return Some(seconds);
    }

    let reset_ms = headers
        .get("x-ratelimit-requests-reset")
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.trim().parse::<u64>().ok())?;

    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .ok()?
        .as_millis() as u64;

    // Already elapsed (or clock skew) — retry immediately rather than
    // reporting a bogus wait.
    Some(reset_ms.saturating_sub(now_ms).div_ceil(1000))
}

/// Binary open/closed state, matching the cross-provider `Issue::state`
/// contract. Linear's `completed`/`canceled` workflow types are terminal;
/// everything else (including an unknown/missing type) is still open.
fn map_state(state: Option<&LinearWorkflowState>) -> String {
    match state.and_then(|s| s.r#type.as_deref()) {
        Some("completed") | Some("canceled") => "closed".to_string(),
        _ => "open".to_string(),
    }
}

/// Linear workflow state type → unified `Issue::status_category`
/// (`backlog` / `todo` / `in_progress` / `done` / `cancelled`).
///
/// Inverse of [`map_state_category`]. `triage` is Linear's pre-backlog
/// inbox — not yet actionable, so it buckets with `backlog`.
fn map_status_category(state_type: &str) -> Option<&'static str> {
    match state_type {
        "triage" | "backlog" => Some("backlog"),
        "unstarted" => Some("todo"),
        "started" => Some("in_progress"),
        "completed" => Some("done"),
        "canceled" => Some("cancelled"),
        _ => None,
    }
}

/// Unified status category → Linear workflow state type, used to translate
/// caller-supplied filters into Linear's `state.type` predicate.
fn map_state_category(category: &str) -> Option<&'static str> {
    match category {
        "backlog" => Some("backlog"),
        "todo" => Some("unstarted"),
        "in_progress" => Some("started"),
        "done" => Some("completed"),
        "cancelled" => Some("canceled"),
        _ => None,
    }
}

fn build_issue_filter(team_id: &str, filter: &IssueFilter) -> Result<Value> {
    if filter.native_query.is_some() {
        return Err(Error::ProviderUnsupported {
            provider: "linear".to_string(),
            operation: "get_issues(native_query)".to_string(),
        });
    }

    let mut clauses = vec![json!({
        "team": {
            "id": {
                "eq": team_id
            }
        }
    })];

    if let Some(state) = filter
        .state
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        match state.to_ascii_lowercase().as_str() {
            "open" | "opened" => clauses.push(json!({
                "state": {
                    "type": {
                        "nin": ["completed", "canceled"]
                    }
                }
            })),
            "closed" => clauses.push(json!({
                "state": {
                    "type": {
                        "in": ["completed", "canceled"]
                    }
                }
            })),
            "all" => {}
            _ => clauses.push(json!({
                "state": {
                    "name": {
                        "eqIgnoreCase": state
                    }
                }
            })),
        }
    }

    if let Some(requested) = filter
        .state_category
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        // Reject instead of ignoring: silently dropping the clause would
        // widen the query to every issue in the team, and the caller would
        // read that as a genuine result set.
        let category = map_state_category(requested).ok_or_else(|| {
            Error::InvalidData(format!(
                "unknown state category '{requested}' for Linear; expected one of: {}",
                STATE_CATEGORIES.join(", ")
            ))
        })?;
        clauses.push(json!({
            "state": {
                "type": {
                    "eq": category
                }
            }
        }));
    }

    if let Some(search) = filter
        .search
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        clauses.push(json!({
            "or": [
                {
                    "title": {
                        "containsIgnoreCase": search
                    }
                },
                {
                    "description": {
                        "containsIgnoreCase": search
                    }
                }
            ]
        }));
    }

    if let Some(labels) = filter.labels.as_ref().filter(|labels| !labels.is_empty()) {
        if matches!(filter.labels_operator.as_deref(), Some("and")) {
            clauses.push(json!({
                "and": labels.iter().map(|label| json!({
                    "labels": {
                        "name": {
                            "eq": label
                        }
                    }
                })).collect::<Vec<_>>()
            }));
        } else {
            clauses.push(json!({
                "labels": {
                    "name": {
                        "in": labels
                    }
                }
            }));
        }
    }

    if let Some(assignee) = filter
        .assignee
        .as_deref()
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        clauses.push(json!({
            "or": [
                {
                    "assignee": {
                        "name": {
                            "eqIgnoreCase": assignee
                        }
                    }
                },
                {
                    "assignee": {
                        "displayName": {
                            "eqIgnoreCase": assignee
                        }
                    }
                },
                {
                    "assignee": {
                        "email": {
                            "eqIgnoreCase": assignee
                        }
                    }
                }
            ]
        }));
    }

    if clauses.len() == 1 {
        return Ok(clauses.remove(0));
    }

    let mut root = Map::new();
    root.insert("and".to_string(), Value::Array(clauses));
    Ok(Value::Object(root))
}

#[async_trait]
impl IssueProvider for LinearClient {
    async fn get_issues(&self, filter: IssueFilter) -> Result<ProviderResult<Issue>> {
        let offset = filter.offset.unwrap_or(0);
        let limit = filter.limit.unwrap_or(50).max(1);
        let total_needed = offset.saturating_add(limit);
        validate_sort_order(filter.sort_order.as_deref())?;
        let order_by = map_order_by(filter.sort_by.as_deref())?;
        let gql_filter = build_issue_filter(&self.team_id, &filter)?;

        let mut after: Option<String> = None;
        let mut fetched = 0u32;
        let mut issues = Vec::new();
        let mut has_more = false;
        let mut next_cursor = None;

        while fetched < total_needed {
            let remaining = total_needed.saturating_sub(fetched).max(1);
            let page_size = remaining.min(100);
            let data = self
                .list_issues_page(page_size, after.as_deref(), gql_filter.clone(), order_by)
                .await?;

            let page_info = data.issues.page_info;
            let page_nodes = data.issues.nodes;
            if page_nodes.is_empty() {
                has_more = false;
                next_cursor = None;
                break;
            }

            for issue in page_nodes {
                if fetched >= offset && issues.len() < limit as usize {
                    issues.push(map_issue(&issue));
                }
                fetched = fetched.saturating_add(1);
                if fetched >= total_needed {
                    break;
                }
            }

            has_more = page_info.has_next_page;
            next_cursor = page_info.end_cursor.clone();
            if !has_more {
                break;
            }
            after = page_info.end_cursor;
        }

        Ok(ProviderResult {
            items: issues,
            pagination: Some(Pagination {
                offset,
                limit,
                total: None,
                has_more,
                next_cursor,
            }),
            sort_info: Some(SortInfo {
                sort_by: Some(
                    filter
                        .sort_by
                        .as_deref()
                        .unwrap_or(DEFAULT_SORT_BY)
                        .to_string(),
                ),
                sort_order: SortOrder::Desc,
                available_sorts: vec!["created_at".to_string(), "updated_at".to_string()],
            }),
        })
    }

    async fn get_issue(&self, key: &str) -> Result<Issue> {
        Ok(map_issue(&self.resolve_scoped_issue(key).await?))
    }

    async fn create_issue(&self, input: CreateIssueInput) -> Result<Issue> {
        let assignee_id = match input.assignees.first() {
            Some(assignee) => Some(self.resolve_assignee_id(assignee).await?),
            None => None,
        };
        let label_ids = self.resolve_label_ids(&input.labels).await?;
        let parent_id = match input.parent.as_deref() {
            Some(parent) => Some(self.resolve_parent_id(parent).await?),
            None => None,
        };
        let priority = Self::map_create_priority(input.priority.as_deref())?;

        let mut payload = Map::new();
        payload.insert("teamId".to_string(), Value::String(self.team_id.clone()));
        payload.insert("title".to_string(), Value::String(input.title));

        if let Some(description) = input.description {
            payload.insert("description".to_string(), Value::String(description));
        }
        if let Some(priority) = priority {
            payload.insert("priority".to_string(), Value::Number(priority.into()));
        }
        if let Some(assignee_id) = assignee_id {
            payload.insert("assigneeId".to_string(), Value::String(assignee_id));
        }
        if let Some(parent_id) = parent_id {
            payload.insert("parentId".to_string(), Value::String(parent_id));
        }
        if let Some(project_id) = input.project_id {
            payload.insert("projectId".to_string(), Value::String(project_id));
        }
        if !label_ids.is_empty() {
            payload.insert(
                "labelIds".to_string(),
                Value::Array(label_ids.into_iter().map(Value::String).collect()),
            );
        }

        let data: LinearIssueCreateData = self
            .graphql(
                ISSUE_CREATE_MUTATION,
                json!({
                    "input": Value::Object(payload),
                }),
                &self.token,
            )
            .await?;
        if !data.issue_create.success {
            return Err(Error::Api {
                status: 200,
                message: "Linear issueCreate returned success=false".to_string(),
            });
        }

        let issue = data.issue_create.issue.ok_or_else(|| {
            Error::InvalidData("Linear issueCreate returned no issue payload".to_string())
        })?;
        Ok(map_issue(&issue))
    }

    async fn update_issue(&self, key: &str, input: UpdateIssueInput) -> Result<Issue> {
        let issue_id = self.resolve_scoped_issue(key).await?.id;

        let assignee_id = match input.assignees.as_ref() {
            Some(assignees) if assignees.is_empty() => Some(Value::Null),
            Some(assignees) => Some(Value::String(
                self.resolve_assignee_id(&assignees[0]).await?,
            )),
            None => None,
        };
        let label_ids = match input.labels.as_ref() {
            Some(labels) => Some(
                self.resolve_label_ids(labels)
                    .await?
                    .into_iter()
                    .map(Value::String)
                    .collect::<Vec<_>>(),
            ),
            None => None,
        };
        let parent_id = match input.parent_id.as_deref() {
            Some("none") | Some("") => Some(Value::Null),
            Some(parent) => Some(Value::String(self.resolve_parent_id(parent).await?)),
            None => None,
        };
        let priority = Self::map_create_priority(input.priority.as_deref())?;
        let state_id = match input.status.as_deref().or(input.state.as_deref()) {
            Some(state) => Some(self.resolve_workflow_state_id(state).await?),
            None => None,
        };

        let mut payload = Map::new();
        if let Some(title) = input.title {
            payload.insert("title".to_string(), Value::String(title));
        }
        if let Some(description) = input.description {
            payload.insert("description".to_string(), Value::String(description));
        }
        if let Some(priority) = priority {
            payload.insert("priority".to_string(), Value::Number(priority.into()));
        }
        if let Some(assignee_id) = assignee_id {
            payload.insert("assigneeId".to_string(), assignee_id);
        }
        if let Some(parent_id) = parent_id {
            payload.insert("parentId".to_string(), parent_id);
        }
        if let Some(label_ids) = label_ids {
            payload.insert("labelIds".to_string(), Value::Array(label_ids));
        }
        if let Some(state_id) = state_id {
            payload.insert("stateId".to_string(), Value::String(state_id));
        }

        if payload.is_empty() {
            return self.get_issue(key).await;
        }

        let data: LinearIssueUpdateData = self
            .graphql(
                ISSUE_UPDATE_MUTATION,
                json!({
                    "id": issue_id,
                    "input": Value::Object(payload),
                }),
                &self.token,
            )
            .await?;
        if !data.issue_update.success {
            return Err(Error::Api {
                status: 200,
                message: "Linear issueUpdate returned success=false".to_string(),
            });
        }

        let issue = data.issue_update.issue.ok_or_else(|| {
            Error::InvalidData("Linear issueUpdate returned no issue payload".to_string())
        })?;
        Ok(map_issue(&issue))
    }

    async fn get_comments(&self, issue_key: &str) -> Result<ProviderResult<Comment>> {
        let issue_id = self.resolve_scoped_issue(issue_key).await?.id;

        let mut after: Option<String> = None;
        let mut comments = Vec::new();

        loop {
            let data: LinearIssueCommentsData = self
                .graphql(
                    ISSUE_COMMENTS_QUERY,
                    json!({
                        "id": issue_id,
                        "first": 100,
                        "after": after,
                    }),
                    &self.token,
                )
                .await?;
            let issue = data.issue.ok_or_else(|| {
                Error::NotFound(format!(
                    "Linear issue not found when fetching comments: {issue_key}"
                ))
            })?;

            let page_info = issue.comments.page_info;
            comments.extend(issue.comments.nodes.iter().map(map_comment));

            if !page_info.has_next_page {
                break;
            }
            after = page_info.end_cursor;
            if after.is_none() {
                break;
            }
        }

        Ok(comments.into())
    }

    async fn add_comment(&self, issue_key: &str, body: &str) -> Result<Comment> {
        let issue_id = self.resolve_scoped_issue(issue_key).await?.id;

        let data: LinearCommentCreateData = self
            .graphql(
                COMMENT_CREATE_MUTATION,
                json!({
                    "input": {
                        "issueId": issue_id,
                        "body": body,
                    }
                }),
                &self.token,
            )
            .await?;
        if !data.comment_create.success {
            return Err(Error::Api {
                status: 200,
                message: "Linear commentCreate returned success=false".to_string(),
            });
        }

        let comment = data.comment_create.comment.ok_or_else(|| {
            Error::InvalidData("Linear commentCreate returned no comment payload".to_string())
        })?;
        Ok(map_comment(&comment))
    }

    async fn get_statuses(&self) -> Result<ProviderResult<IssueStatus>> {
        let data = self.list_workflow_states().await?;
        let statuses = data
            .workflow_states
            .nodes
            .into_iter()
            .enumerate()
            .map(|(idx, state)| IssueStatus {
                id: state.id,
                name: state.name,
                category: match state.r#type.as_deref() {
                    Some("backlog") => "backlog".to_string(),
                    Some("unstarted") => "todo".to_string(),
                    Some("started") => "in_progress".to_string(),
                    Some("completed") => "done".to_string(),
                    Some("canceled") => "cancelled".to_string(),
                    Some(other) => other.to_string(),
                    None => "custom".to_string(),
                },
                color: None,
                order: Some(idx as u32),
            })
            .collect::<Vec<_>>();
        Ok(statuses.into())
    }

    fn provider_name(&self) -> &'static str {
        "linear"
    }
}

#[async_trait]
impl MergeRequestProvider for LinearClient {
    fn provider_name(&self) -> &'static str {
        "linear"
    }
}

#[async_trait]
impl PipelineProvider for LinearClient {
    fn provider_name(&self) -> &'static str {
        "linear"
    }
}

#[async_trait]
impl Provider for LinearClient {
    async fn get_current_user(&self) -> Result<User> {
        let viewer = self.viewer_with_token(&self.token).await?;
        Ok(User {
            id: viewer.id,
            username: viewer
                .display_name
                .clone()
                .unwrap_or_else(|| viewer.name.clone()),
            name: Some(viewer.name),
            email: viewer.email,
            avatar_url: None,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use httpmock::Method::POST;
    use httpmock::MockServer;
    use serde_json::json;

    fn workflow_state(name: &str, r#type: Option<&str>) -> LinearWorkflowState {
        LinearWorkflowState {
            name: name.to_string(),
            r#type: r#type.map(str::to_string),
        }
    }

    fn headers_from(pairs: &[(&str, &str)]) -> reqwest::header::HeaderMap {
        let mut headers = reqwest::header::HeaderMap::new();
        for (name, value) in pairs {
            headers.insert(
                reqwest::header::HeaderName::from_bytes(name.as_bytes()).unwrap(),
                reqwest::header::HeaderValue::from_str(value).unwrap(),
            );
        }
        headers
    }

    #[test]
    fn parse_retry_after_prefers_standard_header() {
        let headers = headers_from(&[
            ("retry-after", "42"),
            ("x-ratelimit-requests-reset", "99999999999999"),
        ]);
        assert_eq!(parse_retry_after(&headers), Some(42));
    }

    #[test]
    fn parse_retry_after_converts_linear_reset_epoch_millis_to_delta() {
        let now_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_millis() as u64;
        let headers =
            headers_from(&[("x-ratelimit-requests-reset", &(now_ms + 30_000).to_string())]);
        // Allow a second of slack for the clock ticking between the two reads.
        let seconds = parse_retry_after(&headers).expect("delta from reset header");
        assert!((29..=31).contains(&seconds), "unexpected delta: {seconds}");
    }

    #[test]
    fn parse_retry_after_handles_missing_and_elapsed_values() {
        assert_eq!(parse_retry_after(&headers_from(&[])), None);
        assert_eq!(
            parse_retry_after(&headers_from(&[("retry-after", "not-a-number")])),
            None
        );
        // A reset already in the past must not underflow into a huge wait.
        assert_eq!(
            parse_retry_after(&headers_from(&[("x-ratelimit-requests-reset", "1")])),
            Some(0)
        );
    }

    #[test]
    fn map_state_is_binary_and_only_terminal_types_close() {
        for open_type in ["triage", "backlog", "unstarted", "started"] {
            let state = workflow_state("Whatever", Some(open_type));
            assert_eq!(map_state(Some(&state)), "open", "type={open_type}");
        }
        for closed_type in ["completed", "canceled"] {
            let state = workflow_state("Whatever", Some(closed_type));
            assert_eq!(map_state(Some(&state)), "closed", "type={closed_type}");
        }
        // Missing state, or a type Linear may add later, stays open rather
        // than silently disappearing from `state:open` queries.
        assert_eq!(map_state(None), "open");
        assert_eq!(map_state(Some(&workflow_state("New", None))), "open");
        assert_eq!(
            map_state(Some(&workflow_state("New", Some("something_new")))),
            "open"
        );
    }

    #[test]
    fn build_issue_filter_rejects_unknown_state_category() {
        let filter = IssueFilter {
            state_category: Some("in-progress".to_string()),
            ..Default::default()
        };
        let err = build_issue_filter("team-1", &filter).unwrap_err();
        match err {
            Error::InvalidData(message) => {
                assert!(message.contains("in-progress"), "message: {message}");
                assert!(message.contains("in_progress"), "message: {message}");
            }
            other => panic!("expected InvalidData, got {other:?}"),
        }
    }

    #[test]
    fn build_issue_filter_accepts_every_advertised_state_category() {
        for category in STATE_CATEGORIES {
            let filter = IssueFilter {
                state_category: Some((*category).to_string()),
                ..Default::default()
            };
            build_issue_filter("team-1", &filter)
                .unwrap_or_else(|e| panic!("category {category} rejected: {e:?}"));
        }
    }

    #[test]
    fn map_status_category_covers_every_linear_state_type() {
        assert_eq!(map_status_category("triage"), Some("backlog"));
        assert_eq!(map_status_category("backlog"), Some("backlog"));
        assert_eq!(map_status_category("unstarted"), Some("todo"));
        assert_eq!(map_status_category("started"), Some("in_progress"));
        assert_eq!(map_status_category("completed"), Some("done"));
        assert_eq!(map_status_category("canceled"), Some("cancelled"));
        assert_eq!(map_status_category("something_new"), None);
    }

    #[test]
    fn map_status_category_round_trips_through_map_state_category() {
        // Every unified category the filter layer accepts must map back to
        // itself, so `status_category` values are valid filter inputs.
        for category in ["backlog", "todo", "in_progress", "done", "cancelled"] {
            let linear_type = map_state_category(category)
                .unwrap_or_else(|| panic!("no linear type for {category}"));
            assert_eq!(map_status_category(linear_type), Some(category));
        }
    }

    fn linear_issue(identifier: &str, title: &str, state: &str) -> Value {
        json!({
            "id": format!("id-{identifier}"),
            "identifier": identifier,
            "title": title,
            "description": format!("Description for {identifier}"),
            "priority": 2,
            "url": format!("https://linear.app/acme/issue/{identifier}/{}", title.replace(' ', "-").to_lowercase()),
            "createdAt": "2026-05-01T10:00:00.000Z",
            "updatedAt": "2026-05-02T10:00:00.000Z",
            "state": {
                "name": state,
                "type": "started"
            },
            "labels": {
                "nodes": [
                    { "name": "bug" }
                ]
            },
            "assignee": {
                "id": "u1",
                "name": "Alice Doe",
                "displayName": "alice",
                "email": "alice@example.com",
                "avatarUrl": "https://example.com/alice.png"
            },
            "parent": {
                "identifier": "ENG-1"
            },
            "team": {
                "id": "team-1",
                "key": "ENG"
            }
        })
    }

    fn linear_comment(id: &str, body: &str) -> Value {
        json!({
            "id": id,
            "body": body,
            "createdAt": "2026-05-04T10:00:00.000Z",
            "updatedAt": "2026-05-05T10:00:00.000Z",
            "user": {
                "id": "u1",
                "name": "Alice Doe",
                "displayName": "alice",
                "email": "alice@example.com",
                "avatarUrl": "https://example.com/alice.png"
            }
        })
    }

    #[tokio::test]
    async fn get_current_user_reads_viewer() {
        let server = MockServer::start();
        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Viewer");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "viewer": {
                            "id": "u1",
                            "name": "Alice",
                            "displayName": "alice",
                            "email": "alice@example.com"
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let user = client.get_current_user().await.unwrap();
        assert_eq!(user.id, "u1");
        assert_eq!(user.username, "alice");
        assert_eq!(user.name.as_deref(), Some("Alice"));
        assert_eq!(user.email.as_deref(), Some("alice@example.com"));
        mock.assert();
    }

    #[tokio::test]
    async fn get_issue_by_identifier_uses_team_scoped_issue_filter() {
        let server = MockServer::start();
        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""first":1"#)
                .body_includes(r#""team":{"id":{"eq":"team-1"}}"#)
                .body_includes(r#""number":{"eq":42}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-42", "Fix login", "In Progress")
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": null
                            }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let issue = client.get_issue("ENG-42").await.unwrap();
        assert_eq!(issue.key, "ENG-42");
        assert_eq!(issue.title, "Fix login");
        assert_eq!(issue.state, "open");
        assert_eq!(issue.status.as_deref(), Some("In Progress"));
        assert_eq!(issue.status_category.as_deref(), Some("in_progress"));
        assert_eq!(issue.priority.as_deref(), Some("high"));
        assert_eq!(issue.labels, vec!["bug".to_string()]);
        assert_eq!(issue.parent.as_deref(), Some("ENG-1"));
        assert_eq!(issue.assignees.len(), 1);
        assert_eq!(issue.assignees[0].username, "alice");

        mock.assert();
    }

    #[tokio::test]
    async fn get_issue_by_identifier_rejects_mismatched_team_prefix() {
        let server = MockServer::start();
        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        )
        .with_team_key("ENG");

        let result = client.get_issue("OPS-42").await;
        assert!(matches!(result, Err(Error::NotFound(msg)) if msg.contains("OPS-42")));
    }

    #[tokio::test]
    async fn get_issue_by_native_id_uses_issue_query() {
        let server = MockServer::start();
        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query IssueById")
                .body_includes(r#""id":"3d1b0f7a-8f3a-4b2a-9c1a-2b6a0c4b9a11""#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issue": linear_issue("ENG-7", "Fetch by uuid", "Backlog")
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let uuid = "3d1b0f7a-8f3a-4b2a-9c1a-2b6a0c4b9a11";
        let issue = client.get_issue(uuid).await.unwrap();
        assert_eq!(issue.key, "ENG-7");

        mock.assert();
    }

    #[tokio::test]
    async fn get_issue_by_native_id_rejects_issue_from_other_team() {
        let server = MockServer::start();
        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query IssueById")
                .body_includes(r#""id":"3d1b0f7a-8f3a-4b2a-9c1a-2b6a0c4b9a11""#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issue": {
                            "id": "3d1b0f7a-8f3a-4b2a-9c1a-2b6a0c4b9a11",
                            "identifier": "OPS-7",
                            "title": "Foreign team issue",
                            "description": "Should not resolve",
                            "priority": 2,
                            "url": "https://linear.app/acme/issue/OPS-7/foreign-team-issue",
                            "createdAt": "2026-05-01T10:00:00.000Z",
                            "updatedAt": "2026-05-02T10:00:00.000Z",
                            "state": {
                                "name": "Backlog",
                                "type": "backlog"
                            },
                            "labels": { "nodes": [] },
                            "assignee": null,
                            "parent": null,
                            "team": {
                                "id": "team-2",
                                "key": "OPS"
                            }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let uuid = "3d1b0f7a-8f3a-4b2a-9c1a-2b6a0c4b9a11";
        let result = client.get_issue(uuid).await;
        assert!(matches!(result, Err(Error::NotFound(msg)) if msg.contains(uuid)));

        mock.assert();
    }

    #[tokio::test]
    async fn get_issues_applies_filters_and_reports_pagination() {
        let server = MockServer::start();
        let page_1 = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""first":3"#)
                .body_includes(r#""state":{"type":{"nin":["completed","canceled"]}}"#)
                .body_includes(r#""title":{"containsIgnoreCase":"login"}"#)
                .body_includes(r#""labels":{"name":{"eq":"bug"}}"#)
                .body_includes(r#""displayName":{"eqIgnoreCase":"alice"}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-1", "One", "Backlog"),
                                linear_issue("ENG-2", "Two", "In Progress"),
                                linear_issue("ENG-3", "Three", "In Progress")
                            ],
                            "pageInfo": {
                                "hasNextPage": true,
                                "endCursor": "cursor-1"
                            }
                        }
                    }
                }));
        });
        let page_2 = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes(r#""after":"cursor-1""#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-4", "Four", "Done")
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": "cursor-2"
                            }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let result = client
            .get_issues(IssueFilter {
                state: Some("open".to_string()),
                search: Some("login".to_string()),
                labels: Some(vec!["bug".to_string(), "api".to_string()]),
                labels_operator: Some("and".to_string()),
                assignee: Some("alice".to_string()),
                limit: Some(2),
                offset: Some(1),
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(result.items.len(), 2);
        assert_eq!(result.items[0].key, "ENG-2");
        assert_eq!(result.items[1].key, "ENG-3");

        let pagination = result.pagination.unwrap();
        assert_eq!(pagination.offset, 1);
        assert_eq!(pagination.limit, 2);
        assert!(pagination.has_more);
        assert_eq!(pagination.next_cursor.as_deref(), Some("cursor-1"));

        page_1.assert();
        assert_eq!(page_2.calls(), 0);
    }

    #[test]
    fn map_order_by_covers_the_advertised_sort_fields() {
        assert_eq!(map_order_by(Some("created_at")).unwrap(), "createdAt");
        assert_eq!(map_order_by(Some("updated_at")).unwrap(), "updatedAt");
        // Unset falls back to the documented tool default, sent explicitly
        // because Linear's own server-side default is createdAt.
        assert_eq!(map_order_by(None).unwrap(), "updatedAt");

        let err = map_order_by(Some("priority")).unwrap_err();
        assert!(
            matches!(&err, Error::InvalidData(m) if m.contains("priority") && m.contains("updated_at")),
            "unexpected error: {err:?}"
        );
    }

    #[test]
    fn validate_sort_order_accepts_desc_and_names_the_argument_on_asc() {
        validate_sort_order(None).unwrap();
        validate_sort_order(Some("desc")).unwrap();

        let err = validate_sort_order(Some("asc")).unwrap_err();
        match &err {
            // Must be InvalidData, not ProviderUnsupported: the MCP layer
            // swallows ProviderUnsupported and reports the misleading
            // "No provider supports 'get_issues'" instead.
            Error::InvalidData(message) => {
                assert!(message.contains("sort_order"), "message: {message}");
                assert!(message.contains("asc"), "message: {message}");
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn resolve_workflow_state_prefers_an_exact_name_over_the_category_alias() {
        // The team has two `completed` states and the literal name "Done" is
        // one of them. Resolving "Done" by category could land on "Released";
        // the exact name must win.
        let server = MockServer::start();
        let states = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query WorkflowStates");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": { "workflowStates": { "nodes": [
                        { "id": "st-released", "name": "Released", "type": "completed" },
                        { "id": "st-done", "name": "Done", "type": "completed" }
                    ] } }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        assert_eq!(
            client.resolve_workflow_state_id("Done").await.unwrap(),
            "st-done"
        );
        // A pure category still resolves by type, first state of that type.
        assert_eq!(
            client.resolve_workflow_state_id("closed").await.unwrap(),
            "st-released"
        );
        // An unknown name fails loudly and lists what is available.
        let err = client
            .resolve_workflow_state_id("Shipped")
            .await
            .unwrap_err();
        assert!(
            matches!(&err, Error::NotFound(m) if m.contains("Shipped") && m.contains("Released")),
            "unexpected error: {err:?}"
        );
        states.assert_calls(3);
    }

    #[tokio::test]
    async fn get_issues_sends_order_by_and_reports_sort_info() {
        let server = MockServer::start();
        let page = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""orderBy":"createdAt""#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [linear_issue("ENG-1", "One", "In Progress")],
                            "pageInfo": { "hasNextPage": false, "endCursor": null }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let result = client
            .get_issues(IssueFilter {
                sort_by: Some("created_at".to_string()),
                sort_order: Some("desc".to_string()),
                ..Default::default()
            })
            .await
            .unwrap();

        let sort = result.sort_info.expect("sort_info reported");
        assert_eq!(sort.sort_by.as_deref(), Some("created_at"));
        assert_eq!(sort.sort_order, SortOrder::Desc);
        assert_eq!(sort.available_sorts, vec!["created_at", "updated_at"]);
        page.assert();
    }

    #[tokio::test]
    async fn create_issue_resolves_inputs_and_returns_created_issue() {
        let server = MockServer::start();
        let users = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Users")
                .body_includes(r#""displayName":{"eqIgnoreCase":"alice"}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "users": {
                            "nodes": [
                                {
                                    "id": "user-1",
                                    "name": "Alice Doe",
                                    "displayName": "alice",
                                    "email": "alice@example.com",
                                    "avatarUrl": "https://example.com/alice.png"
                                }
                            ]
                        }
                    }
                }));
        });
        let labels = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query IssueLabels")
                .body_includes(r#""team":{"id":{"eq":"team-1"}}"#)
                .body_includes(r#""name":{"in":["bug","backend"]}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issueLabels": {
                            "nodes": [
                                { "id": "label-1", "name": "bug" },
                                { "id": "label-2", "name": "backend" }
                            ]
                        }
                    }
                }));
        });
        let parent = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""number":{"eq":1}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-1", "Parent issue", "Backlog")
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": null
                            }
                        }
                    }
                }));
        });
        let create = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("mutation IssueCreate")
                .body_includes(r#""teamId":"team-1""#)
                .body_includes(r#""title":"Create login flow""#)
                .body_includes(r#""description":"Ship the first pass""#)
                .body_includes(r#""priority":1"#)
                .body_includes(r#""assigneeId":"user-1""#)
                .body_includes(r#""parentId":"id-ENG-1""#)
                .body_includes(r#""projectId":"project-1""#)
                .body_includes(r#""labelIds":["label-1","label-2"]"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issueCreate": {
                            "success": true,
                            "issue": linear_issue("ENG-99", "Create login flow", "Backlog")
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let issue = client
            .create_issue(CreateIssueInput {
                title: "Create login flow".to_string(),
                description: Some("Ship the first pass".to_string()),
                labels: vec!["bug".to_string(), "backend".to_string()],
                assignees: vec!["alice".to_string()],
                priority: Some("urgent".to_string()),
                parent: Some("ENG-1".to_string()),
                project_id: Some("project-1".to_string()),
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(issue.key, "ENG-99");
        assert_eq!(issue.title, "Create login flow");
        assert_eq!(issue.priority.as_deref(), Some("high"));
        assert_eq!(issue.parent.as_deref(), Some("ENG-1"));
        assert_eq!(issue.assignees.len(), 1);
        assert_eq!(issue.assignees[0].username, "alice");
        assert_eq!(issue.labels, vec!["bug".to_string()]);

        users.assert();
        labels.assert();
        parent.assert();
        create.assert();
    }

    #[tokio::test]
    async fn update_issue_resolves_status_and_clears_optional_fields() {
        let server = MockServer::start();
        let issue_lookup = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""number":{"eq":42}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-42", "Original issue", "Backlog")
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": null
                            }
                        }
                    }
                }));
        });
        let workflow_states = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                // States are now fetched unfiltered and matched by exact name
                // locally, so an exact name is never shadowed by a category alias.
                .body_includes("query WorkflowStates");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "workflowStates": {
                            "nodes": [
                                {
                                    "id": "workflow-2",
                                    "name": "In Review",
                                    "type": "started"
                                }
                            ]
                        }
                    }
                }));
        });
        let update = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("mutation IssueUpdate")
                .body_includes(r#""id":"id-ENG-42""#)
                .body_includes(r#""title":"Updated issue title""#)
                .body_includes(r#""description":"Updated description""#)
                .body_includes(r#""priority":4"#)
                .body_includes(r#""assigneeId":null"#)
                .body_includes(r#""parentId":null"#)
                .body_includes(r#""labelIds":[]"#)
                .body_includes(r#""stateId":"workflow-2""#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issueUpdate": {
                            "success": true,
                            "issue": {
                                "id": "id-ENG-42",
                                "identifier": "ENG-42",
                                "title": "Updated issue title",
                                "description": "Updated description",
                                "priority": 4,
                                "url": "https://linear.app/acme/issue/ENG-42/updated-issue-title",
                                "createdAt": "2026-05-01T10:00:00.000Z",
                                "updatedAt": "2026-05-03T10:00:00.000Z",
                                "state": {
                                    "name": "In Review",
                                    "type": "started"
                                },
                                "labels": {
                                    "nodes": []
                                },
                                "assignee": null,
                                "parent": null
                            }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let issue = client
            .update_issue(
                "ENG-42",
                UpdateIssueInput {
                    title: Some("Updated issue title".to_string()),
                    description: Some("Updated description".to_string()),
                    state: Some("closed".to_string()),
                    status: Some("In Review".to_string()),
                    labels: Some(vec![]),
                    assignees: Some(vec![]),
                    priority: Some("low".to_string()),
                    parent_id: Some("none".to_string()),
                    ..Default::default()
                },
            )
            .await
            .unwrap();

        assert_eq!(issue.key, "ENG-42");
        assert_eq!(issue.title, "Updated issue title");
        assert_eq!(issue.description.as_deref(), Some("Updated description"));
        assert_eq!(issue.state, "open");
        assert_eq!(issue.status.as_deref(), Some("In Review"));
        assert_eq!(issue.status_category.as_deref(), Some("in_progress"));
        assert_eq!(issue.priority.as_deref(), Some("low"));
        assert!(issue.labels.is_empty());
        assert!(issue.assignees.is_empty());
        assert_eq!(issue.parent, None);

        issue_lookup.assert();
        workflow_states.assert();
        update.assert();
    }

    #[tokio::test]
    async fn get_comments_paginates_and_maps_authors() {
        let server = MockServer::start();
        let issue_lookup = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""number":{"eq":42}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-42", "Issue for comments", "Backlog")
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": null
                            }
                        }
                    }
                }));
        });
        let comments_page_1 = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query IssueComments")
                .body_includes(r#""id":"id-ENG-42""#)
                .body_includes(r#""first":100"#)
                .body_includes(r#""after":null"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issue": {
                            "comments": {
                                "nodes": [
                                    linear_comment("comment-1", "First comment")
                                ],
                                "pageInfo": {
                                    "hasNextPage": true,
                                    "endCursor": "cursor-1"
                                }
                            }
                        }
                    }
                }));
        });
        let comments_page_2 = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes(r#""after":"cursor-1""#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issue": {
                            "comments": {
                                "nodes": [
                                    linear_comment("comment-2", "Second comment")
                                ],
                                "pageInfo": {
                                    "hasNextPage": false,
                                    "endCursor": "cursor-2"
                                }
                            }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let comments = client.get_comments("ENG-42").await.unwrap();
        assert_eq!(comments.items.len(), 2);
        assert_eq!(comments.items[0].id, "comment-1");
        assert_eq!(comments.items[0].body, "First comment");
        assert_eq!(
            comments.items[0]
                .author
                .as_ref()
                .map(|u| u.username.as_str()),
            Some("alice")
        );
        assert_eq!(comments.items[1].id, "comment-2");

        issue_lookup.assert();
        comments_page_1.assert();
        comments_page_2.assert();
    }

    #[tokio::test]
    async fn add_comment_resolves_issue_and_returns_comment() {
        let server = MockServer::start();
        let issue_lookup = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""number":{"eq":42}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-42", "Issue for add comment", "Backlog")
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": null
                            }
                        }
                    }
                }));
        });
        let create = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("mutation CommentCreate")
                .body_includes(r#""issueId":"id-ENG-42""#)
                .body_includes(r#""body":"Need a follow-up here.""#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "commentCreate": {
                            "success": true,
                            "comment": linear_comment("comment-3", "Need a follow-up here.")
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let comment =
            devboy_core::IssueProvider::add_comment(&client, "ENG-42", "Need a follow-up here.")
                .await
                .unwrap();
        assert_eq!(comment.id, "comment-3");
        assert_eq!(comment.body, "Need a follow-up here.");
        assert_eq!(
            comment.author.as_ref().map(|u| u.username.as_str()),
            Some("alice")
        );

        issue_lookup.assert();
        create.assert();
    }

    #[tokio::test]
    async fn get_statuses_returns_team_workflow_states() {
        let server = MockServer::start();
        let states = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query WorkflowStates")
                .body_includes(r#""team":{"id":{"eq":"team-1"}}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "workflowStates": {
                            "nodes": [
                                { "id": "s1", "name": "Backlog", "type": "backlog" },
                                { "id": "s2", "name": "In Review", "type": "started" },
                                { "id": "s3", "name": "Done", "type": "completed" }
                            ]
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let statuses = client.get_statuses().await.unwrap();
        assert_eq!(statuses.items.len(), 3);
        assert_eq!(statuses.items[0].name, "Backlog");
        assert_eq!(statuses.items[0].category, "backlog");
        assert_eq!(statuses.items[1].category, "in_progress");
        assert_eq!(statuses.items[2].category, "done");

        states.assert();
    }

    #[tokio::test]
    async fn get_issues_rejects_native_query_and_supports_closed_state_category() {
        let client = LinearClient::with_base_url(
            "https://api.linear.app/graphql",
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let unsupported = client
            .get_issues(IssueFilter {
                native_query: Some("project = ENG".to_string()),
                ..Default::default()
            })
            .await;
        assert!(matches!(
            unsupported,
            Err(Error::ProviderUnsupported { provider, operation })
                if provider == "linear" && operation == "get_issues(native_query)"
        ));

        let server = MockServer::start();
        let mock = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes(r#""state":{"type":{"in":["completed","canceled"]}}"#)
                .body_includes(r#""state":{"type":{"eq":"completed"}}"#)
                .body_includes(r#""labels":{"name":{"in":["ops","api"]}}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": null
                            }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let result = client
            .get_issues(IssueFilter {
                state: Some("closed".to_string()),
                state_category: Some("done".to_string()),
                labels: Some(vec!["ops".to_string(), "api".to_string()]),
                labels_operator: Some("or".to_string()),
                limit: Some(5),
                ..Default::default()
            })
            .await
            .unwrap();

        assert!(result.items.is_empty());
        assert!(!result.pagination.unwrap().has_more);
        mock.assert();
    }

    #[tokio::test]
    async fn get_current_user_surfaces_graphql_transport_errors() {
        let unauthorized = MockServer::start();
        let unauthorized_mock = unauthorized.mock(|when, then| {
            when.method(POST).path("/graphql");
            then.status(401).header("content-type", "application/json");
        });
        let unauthorized_client = LinearClient::with_base_url(
            format!("{}/graphql", unauthorized.base_url()),
            "team-1",
            SecretString::from("lin_api_bad".to_owned()),
        );
        let unauthorized_err = unauthorized_client.get_current_user().await.unwrap_err();
        assert!(matches!(unauthorized_err, Error::Unauthorized(_)));
        unauthorized_mock.assert();

        let throttled = MockServer::start();
        let throttled_mock = throttled.mock(|when, then| {
            when.method(POST).path("/graphql");
            then.status(429).header("content-type", "application/json");
        });
        let throttled_client = LinearClient::with_base_url(
            format!("{}/graphql", throttled.base_url()),
            "team-1",
            SecretString::from("lin_api_throttled".to_owned()),
        );
        let throttled_err = throttled_client.get_current_user().await.unwrap_err();
        assert!(matches!(
            throttled_err,
            Error::RateLimited { retry_after: None }
        ));
        throttled_mock.assert();

        let gql_error = MockServer::start();
        let gql_error_mock = gql_error.mock(|when, then| {
            when.method(POST).path("/graphql");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "errors": [
                        {
                            "message": "viewer is unavailable"
                        }
                    ]
                }));
        });
        let gql_error_client = LinearClient::with_base_url(
            format!("{}/graphql", gql_error.base_url()),
            "team-1",
            SecretString::from("lin_api_gql_error".to_owned()),
        );
        let gql_error_result = gql_error_client.get_current_user().await.unwrap_err();
        assert!(matches!(
            gql_error_result,
            Error::Api { status: 200, message } if message.contains("viewer is unavailable")
        ));
        gql_error_mock.assert();
    }

    #[tokio::test]
    async fn get_current_user_maps_graphql_rate_limit_and_missing_data() {
        let rate_limited = MockServer::start();
        let rate_limited_mock = rate_limited.mock(|when, then| {
            when.method(POST).path("/graphql");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "errors": [
                        {
                            "message": "Too many requests",
                            "extensions": {
                                "code": "RATELIMITED"
                            }
                        }
                    ]
                }));
        });
        let rate_limited_client = LinearClient::with_base_url(
            format!("{}/graphql", rate_limited.base_url()),
            "team-1",
            SecretString::from("lin_api_rate_limited".to_owned()),
        );
        let rate_limited_err = rate_limited_client.get_current_user().await.unwrap_err();
        assert!(matches!(
            rate_limited_err,
            Error::RateLimited { retry_after: None }
        ));
        rate_limited_mock.assert();

        let missing_data = MockServer::start();
        let missing_data_mock = missing_data.mock(|when, then| {
            when.method(POST).path("/graphql");
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": null
                }));
        });
        let missing_data_client = LinearClient::with_base_url(
            format!("{}/graphql", missing_data.base_url()),
            "team-1",
            SecretString::from("lin_api_missing_data".to_owned()),
        );
        let missing_data_err = missing_data_client.get_current_user().await.unwrap_err();
        assert!(matches!(
            missing_data_err,
            Error::InvalidData(message) if message.contains("no data")
        ));
        missing_data_mock.assert();
    }

    #[tokio::test]
    async fn create_and_update_issue_cover_validation_and_noop_paths() {
        let client = LinearClient::with_base_url(
            "https://api.linear.app/graphql",
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );

        let invalid_priority = client
            .create_issue(CreateIssueInput {
                title: "Broken".to_string(),
                priority: Some("critical".to_string()),
                ..Default::default()
            })
            .await;
        assert!(matches!(
            invalid_priority,
            Err(Error::InvalidData(message)) if message.contains("Unsupported Linear priority")
        ));

        let invalid_identifier = client
            .update_issue("ENG", UpdateIssueInput::default())
            .await;
        assert!(matches!(
            invalid_identifier,
            Err(Error::InvalidData(message)) if message.contains("must be a UUID or team-key identifier")
        ));

        let server = MockServer::start();
        let issue_lookup = server.mock(|when, then| {
            when.method(POST)
                .path("/graphql")
                .body_includes("query Issues")
                .body_includes(r#""number":{"eq":77}"#);
            then.status(200)
                .header("content-type", "application/json")
                .json_body(json!({
                    "data": {
                        "issues": {
                            "nodes": [
                                linear_issue("ENG-77", "No-op issue", "Backlog")
                            ],
                            "pageInfo": {
                                "hasNextPage": false,
                                "endCursor": null
                            }
                        }
                    }
                }));
        });

        let client = LinearClient::with_base_url(
            format!("{}/graphql", server.base_url()),
            "team-1",
            SecretString::from("lin_api_test".to_owned()),
        );
        let issue = client
            .update_issue("ENG-77", UpdateIssueInput::default())
            .await
            .unwrap();
        assert_eq!(issue.key, "ENG-77");
        assert_eq!(issue_lookup.calls(), 2);
    }
}