onetaskgraph-github-projects 0.2.5

A onetaskgraph source over GitHub Projects.
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
//! A stateless onetaskgraph source over one GitHub Projects v2 project.
//!
//! A project maps to the configured GitHub `ProjectV2`, not a repository: one Projects v2
//! board can contain work from several repositories and draft work from none. Project fields
//! read `ProjectV2.id`, `title`, `shortDescription`, `url`, `createdAt`, and `updatedAt`. Tasks
//! map from `ProjectV2Item.content` (`Issue`, `PullRequest`, or `DraftIssue`); labels read the
//! content's `labels` connection and `ProjectV2ItemFieldLabelValue`.
//!
//! Status reads the item value whose `ProjectV2ItemFieldSingleSelectValue.field.name` is
//! `Status`. Its option name is retained. The default maps Backlog, Todo/Open, In Progress/In
//! Review, Done/Closed/Merged, and Cancelled/Canceled; `status_mapping` overrides option names
//! case-insensitively, and all other user-defined names remain `Unknown`.
//!
//! `ProjectV2.items` pages but has no label, status, orphan, or content-search arguments.
//! Project listing alone is native; the plugin ignores every unsupported query predicate so the
//! engine can compensate from the wider result. Dependencies traverse underlying `Issue` nodes.
//! `Issue.blockedBy` supplies `DependsOn` edges and `Issue.blocking` supplies `DependedOnBy`
//! edges; pull requests and draft issues have neither field and therefore return an empty edge
//! page. Both dependency capabilities are `BothDirections`; project dependency reads aggregate
//! the configured project's issue edges. Projects v2 has no native project-to-project relationship,
//! so those aggregate edges use the related issues' `projectItems.project.id`.
//!
//! Writes update the configured board, create draft items (never another board), update existing
//! draft items, set the source-owned metadata field, and use GitHub's native issue dependency
//! mutation when both ends are issues. Required checks use only the local fixture server; the
//! ignored credentialed lane verifies the current schema, creates and reads back one uniquely
//! named draft, then deletes every matching project item and verifies that no residue remains.
#![deny(missing_docs)]

use std::collections::BTreeMap;

use chrono::{DateTime, Utc};
use onetaskgraph_plugin_api::{
    Capabilities, Cursor, DependencyEdge, DependencyEndpoint, DependencyKind, DependencySupport,
    Direction, Health, ItemKind, ItemWrite, Label, NativeId, Page, PageRequest, Project,
    ProjectQuery, Repository, SecretResolver, SourceError, SourceName, SourcePlugin, Status,
    StatusCategory, Support, Task, TaskQuery, TaskSource, WriteSupport,
};
use reqwest::{Client, StatusCode, Url};
use schemars::{Schema, schema_for};
use secrecy::{ExposeSecret, SecretString};
use serde::Deserialize;
use serde_json::{Value, json};

/// The registry name for this plugin.
pub const KIND: &str = "github-projects";
/// GitHub's maximum connection page size.
pub const MAX_PAGE_SIZE: u32 = 100;
/// Nested connection size which keeps GitHub's worst-case query below its node limit.
const NESTED_PAGE_SIZE: u32 = 50;

/// Exact GraphQL query documents issued by this plugin.
///
/// Keeping the production documents here lets the pinned-schema test validate the same bytes
/// that are sent to GitHub, rather than a test-only copy which could drift independently.
pub mod graphql {
    /// Reads the configured project and its task page.
    pub const PROJECT: &str = r#"query($owner:String!,$number:Int!,$first:Int!,$after:String,$nestedFirst:Int!){
      owner:repositoryOwner(login:$owner){
        ... on ProjectV2Owner{projectV2(number:$number){...Project}}
      }
    } fragment Project on ProjectV2 { id title shortDescription url createdAt updatedAt closed
      fields(first:$nestedFirst){nodes{
        ... on ProjectV2SingleSelectField{__typename id name options{id name}}
        ... on ProjectV2Field{__typename id name}
      }pageInfo{hasNextPage}}
      items(first:$first,after:$after){nodes{id fieldValues(first:$nestedFirst){nodes{
        ... on ProjectV2ItemFieldSingleSelectValue{name field{
          ... on ProjectV2SingleSelectField{id name options{id name}}
        }}
        ... on ProjectV2ItemFieldTextValue{text field{... on ProjectV2Field{id name}}}
        ... on ProjectV2ItemFieldLabelValue{labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}}
      }pageInfo{hasNextPage}} content{
        ... on Issue{__typename id title body url createdAt updatedAt state repository{nameWithOwner} labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}}
        ... on PullRequest{__typename id title body url createdAt updatedAt state repository{nameWithOwner} labels(first:$nestedFirst){nodes{id name color}pageInfo{hasNextPage}}}
        ... on DraftIssue{__typename id title body createdAt updatedAt}
      }} pageInfo{hasNextPage endCursor}}
    }"#;
    /// Reads both dependency directions for one issue.
    pub const TASK_DEPENDENCIES: &str = r#"query($id:ID!,$first:Int!,$after:String){node(id:$id){__typename ... on Issue{blockedBy(first:$first,after:$after){nodes{id}pageInfo{hasNextPage endCursor}}blocking(first:$first,after:$after){nodes{id}pageInfo{hasNextPage endCursor}}}}}"#;
    /// Continues the projects connection for an issue related to a dependency.
    pub const RELATED_PROJECTS: &str = r#"query($id:ID!,$first:Int!,$after:String!){node(id:$id){... on Issue{projectItems(first:$first,after:$after){nodes{project{id}}pageInfo{hasNextPage endCursor}}}}}"#;
    /// Reads issue dependencies and the projects containing each related issue.
    pub const PROJECT_DEPENDENCIES: &str = r#"query($id:ID!,$first:Int!,$after:String,$nestedFirst:Int!){node(id:$id){... on Issue{blockedBy(first:$first,after:$after){nodes{id projectItems(first:$nestedFirst){nodes{project{id}}pageInfo{hasNextPage endCursor}}}pageInfo{hasNextPage endCursor}}blocking(first:$first,after:$after){nodes{id projectItems(first:$nestedFirst){nodes{project{id}}pageInfo{hasNextPage endCursor}}}pageInfo{hasNextPage endCursor}}}}}"#;
    /// Creates a draft in the configured project.
    pub const CREATE_DRAFT: &str = r#"mutation($input:AddProjectV2DraftIssueInput!){addProjectV2DraftIssue(input:$input){projectItem{id content{... on DraftIssue{id}}}}}"#;
    /// Updates an existing draft's user-visible fields.
    pub const UPDATE_DRAFT: &str = r#"mutation($input:UpdateProjectV2DraftIssueInput!){updateProjectV2DraftIssue(input:$input){draftIssue{id}}}"#;
    /// Updates the visible fields of an issue-backed project item.
    pub const UPDATE_ISSUE: &str =
        r#"mutation($input:UpdateIssueInput!){updateIssue(input:$input){issue{id}}}"#;
    /// Updates a text or single-select value on one project item.
    pub const UPDATE_FIELD: &str = r#"mutation($input:UpdateProjectV2ItemFieldValueInput!){updateProjectV2ItemFieldValue(input:$input){projectV2Item{id}}}"#;
    /// Updates the one configured project; it never creates a board.
    pub const UPDATE_PROJECT: &str =
        r#"mutation($input:UpdateProjectV2Input!){updateProjectV2(input:$input){projectV2{id}}}"#;
    /// Adds GitHub's native issue blocked-by relationship.
    pub const ADD_BLOCKED_BY: &str = r#"mutation($input:AddBlockedByInput!){addBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
    /// Removes one native issue blocked-by relationship.
    pub const REMOVE_BLOCKED_BY: &str = r#"mutation($input:RemoveBlockedByInput!){removeBlockedBy(input:$input){issue{id} blockingIssue{id}}}"#;
}

fn default_token_env() -> String {
    "GH_PROJECTS_TOKEN".to_owned()
}
fn default_endpoint() -> String {
    "https://api.github.com/graphql".to_owned()
}

/// Configuration for one GitHub Projects v2 project.
#[derive(Debug, Clone, Default, Deserialize, schemars::JsonSchema)]
#[serde(default, deny_unknown_fields)]
pub struct GitHubProjectsConfig {
    /// Login of the user or organization which owns the project.
    pub owner: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates GitHub's owner grammar before private construction.
    /// The project number shown in its GitHub URL.
    pub project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` bounds this to a positive GraphQL Int.
    /// Environment variable containing a fine-grained token with Projects and Issues read/write
    /// plus Pull requests read-only access for every repository represented on the board.
    #[serde(default = "default_token_env")]
    pub token_env: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` validates the environment-variable grammar.
    /// GraphQL endpoint. GitHub Enterprise installations may override it.
    #[serde(default = "default_endpoint")]
    pub endpoint: String, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; `new` converts it to the private validated `Url`.
    /// Case-insensitive project status name to normalized category mapping.
    #[serde(default)]
    pub status_mapping: BTreeMap<String, StatusCategory>, // llmlint: ignore[invalid_states_unrepresentable] Schema DTO; normalization validates keys and converts them to `StatusName`.
}

/// Factory for [`GitHubProjectsSource`].
#[derive(Debug, Clone, Copy, Default)]
pub struct Plugin;

impl SourcePlugin for Plugin {
    fn kind(&self) -> &'static str {
        KIND
    }
    fn config_schema(&self) -> Schema {
        schema_for!(GitHubProjectsConfig)
    }
    fn build(
        &self,
        name: &SourceName,
        config: &Value,
        secrets: &dyn SecretResolver,
    ) -> Result<Box<dyn TaskSource>, SourceError> {
        let config: GitHubProjectsConfig =
            serde_json::from_value(config.clone()).map_err(|e| SourceError::Config {
                message: format!("source {name}: {e}"),
            })?;
        let source =
            GitHubProjectsSource::new(name, config, secrets).map_err(|error| match error {
                SourceError::Config { message } => SourceError::Config {
                    message: format!("source {name}: {message}"),
                },
                SourceError::Auth { message } => SourceError::Auth {
                    message: format!("source {name}: {message}"),
                },
                other => other,
            })?;
        Ok(Box::new(source))
    }
}

/// A source which reads GitHub afresh for every operation.
pub struct GitHubProjectsSource {
    /// This source's configured name, so a recorded far end naming it can be told from
    /// one naming a system this source knows nothing about.
    name: SourceName,
    owner: String, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after full GitHub-owner validation.
    project_number: u32, // llmlint: ignore[invalid_states_unrepresentable] Private, constructed only by `new` after GraphQL-Int validation.
    endpoint: Url,
    token: SecretString,
    credential_name: String, // llmlint: ignore[invalid_states_unrepresentable] Private diagnostic value constructed only after environment-name validation.
    statuses: BTreeMap<StatusName, StatusCategory>,
    client: Client,
}

impl GitHubProjectsSource {
    /// Validate configuration and capture the named credential without exposing it.
    ///
    /// `name` is this source's configured name, kept for one comparison: a far end
    /// recorded as `<name>:<native>` is an item of this same source, which its own
    /// relationship was supposed to hold.
    pub fn new(
        name: &SourceName,
        config: GitHubProjectsConfig,
        secrets: &dyn SecretResolver,
    ) -> Result<Self, SourceError> {
        if !valid_github_owner(&config.owner) {
            return Err(SourceError::Config {
                message: "owner must be 1-39 ASCII letters, digits, or single hyphens, and cannot start or end with a hyphen".into(),
            });
        }
        if config.project_number == 0 || config.project_number > i32::MAX as u32 {
            return Err(SourceError::Config {
                message: format!("project_number must be between 1 and {}", i32::MAX),
            });
        }
        if !valid_environment_name(&config.token_env) {
            return Err(SourceError::Config {
                message: "token_env must be a valid environment-variable name".into(),
            });
        }
        let endpoint = Url::parse(&config.endpoint).map_err(|e| SourceError::Config {
            message: format!("endpoint is not a valid URL: {e}"),
        })?;
        if endpoint.scheme() != "https"
            && !(endpoint.scheme() == "http"
                && endpoint
                    .host_str()
                    .is_some_and(|h| h == "127.0.0.1" || h == "localhost" || h == "::1"))
        {
            return Err(SourceError::Config {
                message:
                    "endpoint must use HTTPS (HTTP is accepted only for a loopback test server)"
                        .into(),
            });
        }
        let token = secrets.get(&config.token_env).filter(|token| !token.expose_secret().trim().is_empty()).ok_or_else(|| SourceError::Auth {
            message: format!("environment variable {} is missing or empty; set it to a fine-grained GitHub token granting Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board", config.token_env),
        })?;
        Ok(Self {
            name: name.clone(),
            owner: config.owner,
            project_number: config.project_number,
            endpoint,
            token,
            credential_name: config.token_env,
            statuses: normalize_status_mapping(config.status_mapping)?,
            client: Client::builder()
                .user_agent("onetaskgraph")
                .build()
                .map_err(|e| SourceError::Config {
                    message: format!("cannot build HTTP client: {e}"),
                })?,
        })
    }

    async fn graphql(&self, query: &str, variables: Value) -> Result<Value, SourceError> {
        let response = self
            .client
            .post(self.endpoint.clone())
            .bearer_auth(self.token.expose_secret())
            .json(&json!({"query": query, "variables": variables}))
            .send()
            .await
            .map_err(|e| SourceError::Unavailable {
                message: format!("GitHub GraphQL request failed: {e}"),
            })?;
        let status = response.status();
        let retry_after = response
            .headers()
            .get("retry-after")
            .and_then(|v| v.to_str().ok())
            .and_then(|v| v.parse().ok());
        let exhausted = response
            .headers()
            .get("x-ratelimit-remaining")
            .and_then(|v| v.to_str().ok())
            == Some("0");
        if status == StatusCode::TOO_MANY_REQUESTS || exhausted {
            return Err(SourceError::RateLimited {
                retry_after_seconds: retry_after,
            });
        }
        if status == StatusCode::UNAUTHORIZED || status == StatusCode::FORBIDDEN {
            return Err(SourceError::Auth {
                message: format!(
                    "GitHub rejected the configured credential with HTTP {status}; grant it Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board"
                ),
            });
        }
        if !status.is_success() {
            return Err(SourceError::Unavailable {
                message: format!("GitHub GraphQL returned HTTP {status}"),
            });
        }
        let body: Value = response.json().await.map_err(|e| SourceError::Malformed {
            message: format!("GitHub returned invalid JSON: {e}"),
        })?;
        let errors = body
            .get("errors")
            .map(|value| {
                value.as_array().ok_or_else(|| SourceError::Malformed {
                    message: "GitHub response errors is not an array".into(),
                })
            })
            .transpose()?;
        if let Some(errors) = errors.filter(|errors| !errors.is_empty()) {
            let messages = errors
                .iter()
                .filter_map(|e| e.get("message").and_then(Value::as_str))
                .collect::<Vec<_>>()
                .join("; ");
            let message = if messages.is_empty() {
                "GitHub returned GraphQL errors".into()
            } else {
                messages
            };
            let normalized = message.to_ascii_lowercase();
            if normalized.contains("resource not accessible") || normalized.contains("scope") {
                return Err(SourceError::Auth {
                    message: format!(
                        "{message}; grant {} Projects and Issues read/write plus Pull requests read-only access for every repository represented on the board",
                        self.credential_name
                    ),
                });
            }
            return Err(SourceError::Refused { message });
        }
        body.get("data")
            .filter(|data| data.is_object())
            .cloned()
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub response has no data object".into(),
            })
    }

    // llmlint: ignore[boundary_inputs_validated] GitHub caps nested connections at 100 and
    // GraphQL cannot independently page them inside the outer item page. This source page is
    // deliberately bounded at that published maximum; the live drift journey exercises it.
    async fn project_value(
        &self,
        items_after: Option<&str>,
        items_first: u32,
    ) -> Result<Value, SourceError> {
        let data = self.graphql(graphql::PROJECT, json!({"owner":self.owner,"number":self.project_number,"first":items_first.min(MAX_PAGE_SIZE),"after":items_after,"nestedFirst":NESTED_PAGE_SIZE})).await?;
        let project = data
            .pointer("/owner/projectV2")
            .filter(|v| !v.is_null())
            .cloned()
            .ok_or_else(|| SourceError::Refused {
                message: format!(
                    "GitHub project {}/{} was not found or is not visible to the token",
                    self.owner, self.project_number
                ),
            })?;
        Ok(project)
    }

    fn status(&self, item: &Value) -> Result<Status, SourceError> {
        let fields = item
            .pointer("/fieldValues/nodes")
            .and_then(Value::as_array)
            .expect("task validates fieldValues.nodes before mapping status");
        let name = fields
            .iter()
            .find(|v| v.pointer("/field/name").and_then(Value::as_str) == Some("Status"))
            .map(|value| required_str(value, "name"))
            .transpose()?
            .or(optional_str(
                item.get("content").unwrap_or(&Value::Null),
                "state",
            )?)
            .unwrap_or("Unknown")
            .to_owned();
        let category = self
            .statuses
            .get(&StatusName::new(&name))
            .copied()
            .unwrap_or_else(|| match name.to_ascii_lowercase().as_str() {
                "backlog" => StatusCategory::Backlog,
                "todo" | "open" => StatusCategory::Todo,
                "in progress" | "in review" => StatusCategory::InProgress,
                "done" | "closed" | "merged" => StatusCategory::Done,
                "cancelled" | "canceled" => StatusCategory::Cancelled,
                _ => StatusCategory::Unknown,
            });
        Ok(Status { category, name })
    }

    fn labels(item: &Value) -> Result<Vec<Label>, SourceError> {
        let direct = optional_nodes(item.pointer("/content/labels"), "content labels")?;
        let field_values = item
            .pointer("/fieldValues/nodes")
            .and_then(Value::as_array)
            .expect("task validates fieldValues.nodes before mapping labels");
        let field = field_values
            .iter()
            .find_map(|value| value.get("labels"))
            .map(|labels| optional_nodes(Some(labels), "field labels"))
            .transpose()?
            .flatten();
        let labels = direct
            .into_iter()
            .flatten()
            .chain(field.into_iter().flatten())
            .map(|v| {
                Ok(Label {
                    id: NativeId(required_str(v, "id")?.to_owned()),
                    name: required_str(v, "name")?.to_owned(),
                    color: optional_str(v, "color")?.map(str::to_owned),
                })
            })
            .collect::<Result<Vec<_>, SourceError>>()?
            .into_iter()
            .fold(Vec::new(), |mut labels, label| {
                if !labels.iter().any(|x: &Label| x.id == label.id) {
                    labels.push(label);
                }
                labels
            });
        Ok(labels)
    }

    fn task(&self, project_id: &str, item: &Value) -> Result<Option<Task>, SourceError> {
        let content = item.get("content").ok_or_else(|| SourceError::Malformed {
            message: "GitHub project item is missing content".into(),
        })?;
        if content.is_null() {
            return Ok(None);
        }
        let field_values = item
            .get("fieldValues")
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub project item is missing fieldValues".into(),
            })?;
        complete_connection(field_values, "project item field values")?;
        field_values
            .get("nodes")
            .and_then(Value::as_array)
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub project item fieldValues.nodes is not an array".into(),
            })?;
        if let Some(labels) = content.get("labels") {
            complete_connection(labels, "content labels")?;
        }
        for field_value in field_values["nodes"].as_array().expect("validated above") {
            if let Some(labels) = field_value.get("labels") {
                complete_connection(labels, "project item field labels")?;
            }
        }
        Ok(Some(Task {
            id: NativeId(required_str(content, "id")?.to_owned()),
            title: required_str(content, "title")?.to_owned(),
            content: optional_str(content, "body")?
                .filter(|s| !s.is_empty())
                .map(str::to_owned),
            status: self.status(item)?,
            labels: Self::labels(item)?,
            project: Some(NativeId(project_id.to_owned())),
            url: optional_str(content, "url")?.map(str::to_owned),
            created_at: optional_time(content, "createdAt")?,
            updated_at: optional_time(content, "updatedAt")?,
            metadata: metadata_field(field_values)?,
            repositories: repositories(content, field_values)?,
        }))
    }

    fn project(&self, value: &Value) -> Result<Project, SourceError> {
        let id = required_str(value, "id")?;
        let (content, metadata) =
            metadata_description(optional_str(value, "shortDescription")?.map(str::to_owned))?;
        let repositories = repositories_from_metadata(&metadata)?;
        Ok(Project {
            id: NativeId(id.into()),
            title: required_str(value, "title")?.into(),
            content,
            status: Status {
                category: if required_bool(value, "closed")? {
                    StatusCategory::Done
                } else {
                    StatusCategory::InProgress
                },
                name: if required_bool(value, "closed")? {
                    "Closed"
                } else {
                    "Open"
                }
                .into(),
            },
            labels: vec![],
            url: optional_str(value, "url")?.map(str::to_owned),
            created_at: optional_time(value, "createdAt")?,
            updated_at: optional_time(value, "updatedAt")?,
            metadata,
            repositories,
        })
    }

    async fn all_tasks(&self) -> Result<Vec<Task>, SourceError> {
        let mut after = None;
        let mut tasks = Vec::new();
        loop {
            let project = self.project_value(after.as_deref(), MAX_PAGE_SIZE).await?;
            let project_id = required_str(&project, "id")?;
            let items = project
                .pointer("/items/nodes")
                .and_then(Value::as_array)
                .ok_or_else(|| SourceError::Malformed {
                    message: "GitHub project items.nodes is not an array".into(),
                })?;
            for item in items {
                if let Some(task) = self.task(project_id, item)? {
                    tasks.push(task);
                }
            }
            let page =
                project
                    .pointer("/items/pageInfo")
                    .ok_or_else(|| SourceError::Malformed {
                        message: "GitHub project items have no pageInfo".into(),
                    })?;
            if !required_bool(page, "hasNextPage")? {
                break;
            }
            let next = required_str(page, "endCursor")?;
            validate_cursor_progress(after.as_deref(), next)?;
            after = Some(next.to_owned());
        }
        Ok(tasks)
    }

    async fn board_and_item(
        &self,
        content_id: Option<&NativeId>,
    ) -> Result<(Value, Option<Value>), SourceError> {
        let mut after = None;
        loop {
            let project = self.project_value(after.as_deref(), MAX_PAGE_SIZE).await?;
            let nodes = project
                .pointer("/items/nodes")
                .and_then(Value::as_array)
                .ok_or_else(|| SourceError::Malformed {
                    message: "GitHub project items.nodes is not an array".into(),
                })?;
            let found = content_id.and_then(|wanted| {
                nodes
                    .iter()
                    .find(|item| {
                        item.pointer("/content/id").and_then(Value::as_str)
                            == Some(wanted.0.as_str())
                    })
                    .cloned()
            });
            if found.is_some() || content_id.is_none() {
                return Ok((project, found));
            }
            let page =
                project
                    .pointer("/items/pageInfo")
                    .ok_or_else(|| SourceError::Malformed {
                        message: "GitHub project items have no pageInfo".into(),
                    })?;
            if !required_bool(page, "hasNextPage")? {
                return Ok((project, None));
            }
            let next = required_str(page, "endCursor")?;
            validate_cursor_progress(after.as_deref(), next)?;
            after = Some(next.to_owned());
        }
    }

    async fn set_item_field(
        &self,
        project_id: &str,
        item_id: &str,
        field_id: &str,
        value: Value,
    ) -> Result<(), SourceError> {
        let data = self
            .graphql(
                graphql::UPDATE_FIELD,
                json!({"input":{
                    "projectId":project_id,"itemId":item_id,"fieldId":field_id,"value":value
                }}),
            )
            .await?;
        let returned = data
            .pointer("/updateProjectV2ItemFieldValue/projectV2Item")
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub field update returned no project item".into(),
            })?;
        if required_str(returned, "id")? != item_id {
            return Err(SourceError::Malformed {
                message: "GitHub field update returned the wrong project item".into(),
            });
        }
        Ok(())
    }

    async fn native_dependency_ids(&self, id: &NativeId) -> Result<Vec<String>, SourceError> {
        let mut after = None;
        let mut ids = Vec::new();
        loop {
            let data = self
                .graphql(
                    graphql::TASK_DEPENDENCIES,
                    json!({"id":id.0,"first":MAX_PAGE_SIZE,"after":after}),
                )
                .await?;
            let connection =
                data.pointer("/node/blockedBy")
                    .ok_or_else(|| SourceError::Malformed {
                        message: "GitHub dependency response has no blockedBy connection".into(),
                    })?;
            ids.extend(
                connection
                    .get("nodes")
                    .and_then(Value::as_array)
                    .ok_or_else(|| SourceError::Malformed {
                        message: "GitHub dependency response nodes is not an array".into(),
                    })?
                    .iter()
                    .map(|value| required_str(value, "id").map(str::to_owned))
                    .collect::<Result<Vec<_>, _>>()?,
            );
            let next = next_cursor(connection)?;
            if let Some(next) = &next {
                validate_cursor_progress(after.as_deref(), &next.0)?;
            }
            after = next.map(|cursor| cursor.0);
            if after.is_none() {
                return Ok(ids);
            }
        }
    }

    fn field<'a>(project: &'a Value, name: &str) -> Result<Option<&'a Value>, SourceError> {
        complete_connection(
            project.get("fields").unwrap_or(&Value::Null),
            "project fields",
        )?;
        let fields = project
            .pointer("/fields/nodes")
            .and_then(Value::as_array)
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub project fields.nodes is not an array".into(),
            })?;
        Ok(fields
            .iter()
            .find(|field| field.get("name").and_then(Value::as_str) == Some(name)))
    }

    fn task_metadata(
        write: &ItemWrite<Task>,
        repositories: RepositoryStorage,
    ) -> Result<BTreeMap<String, Value>, SourceError> {
        let mut metadata = write.item.metadata.clone();
        if repositories == RepositoryStorage::Recorded && !write.item.repositories.is_empty() {
            metadata.insert(
                Repository::METADATA_KEY.into(),
                Value::Array(
                    write
                        .item
                        .repositories
                        .iter()
                        .map(|repository| Value::String(repository.as_str().to_owned()))
                        .collect(),
                ),
            );
        } else {
            metadata.remove(Repository::METADATA_KEY);
        }
        if !write.depends_on.is_empty() {
            metadata.insert(
                DependencyEdge::RECORDED_KEY.into(),
                Value::Array(
                    write
                        .depends_on
                        .iter()
                        .map(|edge| endpoint_value(&edge.to))
                        .collect(),
                ),
            );
        } else {
            metadata.remove(DependencyEdge::RECORDED_KEY);
        }
        Ok(metadata)
    }

    async fn dependencies(
        &self,
        id: &NativeId,
        direction: Direction,
        page: &PageRequest,
    ) -> Result<Page<DependencyEdge>, SourceError> {
        validate_page(page)?;
        let limit = page.limit.min(MAX_PAGE_SIZE) as usize;
        let cursor = page.cursor.as_ref().map(|c| c.0.as_str());
        let recorded = recorded_offset(cursor, direction)?;
        // Asked for even in the recorded phase, whose page reads nothing from the
        // connection: `__typename` is what says whether this item has a native
        // relationship at all, and that is what decides which far ends the reserved key is
        // allowed to hold.
        let data = self
            .graphql(
                graphql::TASK_DEPENDENCIES,
                json!({"id":id.0,"first":page.limit.min(MAX_PAGE_SIZE),
                       "after":if recorded.is_some() {None} else {cursor}}),
            )
            .await?;
        let node =
            data.get("node")
                .filter(|v| !v.is_null())
                .ok_or_else(|| SourceError::Refused {
                    message: format!(
                        "GitHub item {} was not found or does not support dependencies",
                        id.0
                    ),
                })?;
        let connection_name = match direction {
            Direction::DependsOn => "blockedBy",
            Direction::DependedOnBy => "blocking",
        };
        // A draft or a pull request has neither `blockedBy` nor `blocking`, so nothing it
        // depends on can be named natively and the reserved key may hold any far end. An
        // issue's connections hold issues, so the key may not hold one of those.
        let natively_names =
            (required_str(node, "__typename")? == "Issue").then_some(ItemKind::Task);
        if let Some(offset) = recorded {
            return Ok(recorded_page(
                self.recorded_task_edges(id, direction, natively_names)
                    .await?,
                offset,
                limit,
            ));
        }
        if natively_names.is_none() {
            return Ok(recorded_page(
                self.recorded_task_edges(id, direction, natively_names)
                    .await?,
                0,
                limit,
            ));
        }
        let connection = node
            .get(connection_name)
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub dependency response is missing its connection".into(),
            })?;
        let nodes = connection
            .get("nodes")
            .and_then(Value::as_array)
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub dependency response nodes is not an array".into(),
            })?;
        // `from` depends on `to`, always. GitHub spells the same relationship from either
        // end — `blockedBy` lists what this item waits on, `blocking` lists what waits on
        // it — so the near item is `from` in one direction and `to` in the other.
        let items = nodes
            .iter()
            .map(|value| {
                let related = NativeId(required_str(value, "id")?.into());
                let (from, to) = match direction {
                    Direction::DependsOn => (id.clone(), related),
                    Direction::DependedOnBy => (related, id.clone()),
                };
                Ok(DependencyEdge {
                    from: DependencyEndpoint::from_native(from, ItemKind::Task),
                    to: DependencyEndpoint::from_native(to, ItemKind::Task),
                    kind: DependencyKind::Blocks,
                })
            })
            .collect::<Result<Vec<_>, SourceError>>()?;
        let mut next = next_cursor(connection)?;
        if let Some(next) = &next {
            validate_cursor_progress(cursor, &next.0)?;
        }
        if next.is_none()
            && !self
                .recorded_task_edges(id, direction, natively_names)
                .await?
                .is_empty()
        {
            next = Some(Cursor(format!("{RECORDED_CURSOR}0")));
        }
        Ok(Page { items, next })
    }

    /// The edges this item records under [`DependencyEdge::RECORDED_KEY`], which is where
    /// a far end in another source has to live: no GitHub issue relationship can name one.
    ///
    /// Only forwards. The reverse of a recorded edge is derived from the far end, and this
    /// source never writes one down.
    ///
    /// The metadata lives on the *project item*, not on the issue this method is given, so
    /// reading it costs one board scan. That is why it happens once the native connection
    /// is spent rather than on every page.
    async fn recorded_task_edges(
        &self,
        id: &NativeId,
        direction: Direction,
        natively_names: Option<ItemKind>,
    ) -> Result<Vec<DependencyEdge>, SourceError> {
        if direction != Direction::DependsOn {
            return Ok(Vec::new());
        }
        let Some(task) = self
            .all_tasks()
            .await?
            .into_iter()
            .find(|task| task.id == *id)
        else {
            return Ok(Vec::new());
        };
        DependencyEdge::recorded(
            &task.metadata,
            id,
            ItemKind::Task,
            &self.name,
            natively_names,
        )
        .map_err(|message| SourceError::Malformed { message })
    }

    async fn related_issue_projects(&self, issue: &Value) -> Result<Vec<NativeId>, SourceError> {
        let issue_id = required_str(issue, "id")?;
        let mut connection =
            issue
                .get("projectItems")
                .cloned()
                .ok_or_else(|| SourceError::Malformed {
                    message: "GitHub related issue is missing projectItems".into(),
                })?;
        let mut projects = Vec::new();
        let mut previous = None;
        loop {
            let nodes = connection
                .get("nodes")
                .and_then(Value::as_array)
                .ok_or_else(|| SourceError::Malformed {
                    message: "GitHub related issue projectItems.nodes is not an array".into(),
                })?;
            for item in nodes {
                projects.push(NativeId(
                    required_str(
                        item.get("project").ok_or_else(|| SourceError::Malformed {
                            message: "GitHub dependency project item has no project".into(),
                        })?,
                        "id",
                    )?
                    .into(),
                ));
            }
            let Some(cursor) = next_cursor(&connection)? else {
                break;
            };
            validate_cursor_progress(previous.as_deref(), &cursor.0)?;
            previous = Some(cursor.0.clone());
            let data = self
                .graphql(
                    graphql::RELATED_PROJECTS,
                    json!({"id":issue_id,"first":MAX_PAGE_SIZE,"after":cursor.0}),
                )
                .await?;
            connection = data.pointer("/node/projectItems").cloned().ok_or_else(|| {
                SourceError::Malformed {
                    message: "GitHub related issue response is missing projectItems".into(),
                }
            })?;
        }
        Ok(projects)
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum ContentKind {
    DraftIssue,
    Issue,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum RepositoryStorage {
    Native,
    Recorded,
}
impl ContentKind {
    fn parse(content: &Value) -> Result<Self, SourceError> {
        match required_str(content, "__typename")? {
            "DraftIssue" => Ok(Self::DraftIssue),
            "Issue" => Ok(Self::Issue),
            other => Err(SourceError::Refused {
                message: format!("GitHub {other} items cannot be updated by this destination"),
            }),
        }
    }
}

#[async_trait::async_trait]
impl TaskSource for GitHubProjectsSource {
    fn kind(&self) -> &'static str {
        KIND
    }
    fn capabilities(&self) -> Capabilities {
        Capabilities {
            projects: Support::Native,
            orphan_tasks: Support::Unsupported,
            filter_by_label: Support::Unsupported,
            filter_by_status: Support::Unsupported,
            search_title: Support::Unsupported,
            search_content: Support::Unsupported,
            task_dependencies: DependencySupport::BothDirections,
            project_dependencies: DependencySupport::BothDirections,
            max_page_size: MAX_PAGE_SIZE,
        }
    }
    async fn health(&self) -> Result<Health, SourceError> {
        let project = self.project_value(None, 1).await?;
        Ok(Health {
            reachable: true,
            detail: Some(format!(
                "reading GitHub project {}/{} ({})",
                self.owner,
                self.project_number,
                required_str(&project, "title")?
            )),
        })
    }
    async fn get_task(&self, id: &NativeId) -> Result<Option<Task>, SourceError> {
        Ok(self
            .all_tasks()
            .await?
            .into_iter()
            .find(|task| task.id == *id))
    }
    async fn get_project(&self, id: &NativeId) -> Result<Option<Project>, SourceError> {
        let value = self.project_value(None, 1).await?;
        let project = self.project(&value)?;
        Ok((project.id == *id).then_some(project))
    }
    async fn query_tasks(
        &self,
        _query: &TaskQuery,
        page: &PageRequest,
    ) -> Result<Page<Task>, SourceError> {
        validate_page(page)?;
        let value = self
            .project_value(page.cursor.as_ref().map(|c| c.0.as_str()), page.limit)
            .await?;
        let id = required_str(&value, "id")?;
        let items_connection = value.get("items").ok_or_else(|| SourceError::Malformed {
            message: "GitHub project response is missing items".into(),
        })?;
        let nodes = items_connection
            .get("nodes")
            .and_then(Value::as_array)
            .ok_or_else(|| SourceError::Malformed {
                message: "GitHub project items.nodes is not an array".into(),
            })?;
        let items = nodes
            .iter()
            .map(|item| self.task(id, item))
            .collect::<Result<Vec<_>, SourceError>>()?
            .into_iter()
            .flatten()
            .collect();
        let next = next_cursor(items_connection)?;
        if let Some(next) = &next {
            validate_cursor_progress(
                page.cursor.as_ref().map(|cursor| cursor.0.as_str()),
                &next.0,
            )?;
        }
        Ok(Page { items, next })
    }
    async fn query_projects(
        &self,
        _query: &ProjectQuery,
        page: &PageRequest,
    ) -> Result<Page<Project>, SourceError> {
        validate_page(page)?;
        if page.cursor.is_some() {
            return Err(SourceError::Config {
                message: "GitHub project listing does not issue page cursors".into(),
            });
        }
        Ok(Page::last(vec![
            self.project(&self.project_value(None, 1).await?)?,
        ]))
    }
    async fn labels(&self, page: &PageRequest) -> Result<Page<Label>, SourceError> {
        validate_page(page)?;
        let offset = numeric_cursor(page.cursor.as_ref())?;
        let mut labels = self
            .all_tasks()
            .await?
            .into_iter()
            .flat_map(|t| t.labels)
            .fold(Vec::new(), |mut all, label| {
                if !all.iter().any(|x: &Label| x.id == label.id) {
                    all.push(label);
                }
                all
            });
        labels.sort_by(|a, b| a.name.cmp(&b.name).then(a.id.0.cmp(&b.id.0)));
        Ok(offset_page(
            labels,
            offset,
            page.limit.min(MAX_PAGE_SIZE) as usize,
        ))
    }
    async fn task_dependencies(
        &self,
        id: &NativeId,
        direction: Direction,
        page: &PageRequest,
    ) -> Result<Page<DependencyEdge>, SourceError> {
        self.dependencies(id, direction, page).await
    }
    async fn project_dependencies(
        &self,
        id: &NativeId,
        direction: Direction,
        page: &PageRequest,
    ) -> Result<Page<DependencyEdge>, SourceError> {
        validate_page(page)?;
        let project = self.project_value(None, 1).await?;
        if required_str(&project, "id")? != id.0 {
            return Err(SourceError::Refused {
                message: format!("GitHub project {} was not found", id.0),
            });
        }
        let mut edges = Vec::new();
        for task in self.all_tasks().await? {
            let mut cursor = None;
            loop {
                let data = self.graphql(graphql::PROJECT_DEPENDENCIES, json!({"id":task.id.0,"first":MAX_PAGE_SIZE,"after":cursor.as_ref().map(|cursor: &Cursor| cursor.0.as_str()),"nestedFirst":MAX_PAGE_SIZE})).await?;
                let connection_name = match direction {
                    Direction::DependsOn => "blockedBy",
                    Direction::DependedOnBy => "blocking",
                };
                let Some(connection) = data.pointer(&format!("/node/{connection_name}")) else {
                    // Pull requests and draft issues are valid project tasks, but the inline
                    // `... on Issue` selection intentionally yields no dependency connection.
                    break;
                };
                let related_issues = connection
                    .get("nodes")
                    .and_then(Value::as_array)
                    .ok_or_else(|| SourceError::Malformed {
                        message: "GitHub project dependency nodes is not an array".into(),
                    })?;
                for related_issue in related_issues {
                    for related in self.related_issue_projects(related_issue).await? {
                        if related != *id {
                            // Same orientation as the task level above, one level up.
                            let (from, to) = match direction {
                                Direction::DependsOn => (id.clone(), related),
                                Direction::DependedOnBy => (related, id.clone()),
                            };
                            edges.push(DependencyEdge {
                                from: DependencyEndpoint::from_native(from, ItemKind::Project),
                                to: DependencyEndpoint::from_native(to, ItemKind::Project),
                                kind: DependencyKind::Blocks,
                            });
                        }
                    }
                }
                let next = next_cursor(connection)?;
                if let Some(next) = &next {
                    validate_cursor_progress(
                        cursor.as_ref().map(|value: &Cursor| value.0.as_str()),
                        &next.0,
                    )?;
                }
                cursor = next;
                if cursor.is_none() {
                    break;
                }
            }
        }
        if direction == Direction::DependsOn {
            // A board's edges are aggregated from its issues, so another board is exactly
            // what this source can relate it to — and exactly what the reserved key must
            // not hold.
            edges.extend(
                DependencyEdge::recorded(
                    &self.project(&project)?.metadata,
                    id,
                    ItemKind::Project,
                    &self.name,
                    Some(ItemKind::Project),
                )
                .map_err(|message| SourceError::Malformed { message })?,
            );
        }
        let offset = numeric_cursor(page.cursor.as_ref())?;
        Ok(offset_page(edges, offset, page.limit as usize))
    }

    fn writes(&self) -> WriteSupport {
        WriteSupport::Supported
    }

    async fn write_task(&self, write: &ItemWrite<Task>) -> Result<NativeId, SourceError> {
        let (project, existing) = self.board_and_item(write.target.as_ref()).await?;
        let project_id = required_str(&project, "id")?;
        let metadata_field =
            Self::field(&project, METADATA_FIELD)?.ok_or_else(|| SourceError::Refused {
                message: format!("GitHub project has no source-owned {METADATA_FIELD} text field"),
            })?;
        if required_str(metadata_field, "__typename")? != "ProjectV2Field" {
            return Err(SourceError::Refused {
                message: format!(
                    "GitHub project source-owned {METADATA_FIELD} field is not a text field"
                ),
            });
        }
        let status_selection =
            Some(
                Self::field(&project, "Status")?.ok_or_else(|| SourceError::Refused {
                    message: "GitHub project has no Status field".into(),
                })?,
            )
            .map(|field| {
                if required_str(field, "__typename")? != "ProjectV2SingleSelectField" {
                    return Err(SourceError::Refused {
                        message: "GitHub project Status field is not a single-select field".into(),
                    });
                }
                let option = field
                    .get("options")
                    .and_then(Value::as_array)
                    .and_then(|options| {
                        options.iter().find(|option| {
                            option
                                .get("name")
                                .and_then(Value::as_str)
                                .is_some_and(|name| {
                                    name.eq_ignore_ascii_case(&write.item.status.name)
                                })
                        })
                    })
                    .ok_or_else(|| SourceError::Refused {
                        message: format!(
                            "GitHub Status field cannot represent status {}",
                            write.item.status.name
                        ),
                    })?;
                Ok::<_, SourceError>((
                    required_str(field, "id")?.to_owned(),
                    required_str(option, "id")?.to_owned(),
                ))
            })
            .transpose()?;
        let (content_id, item_id, content_kind) = if let Some(target) = &write.target {
            let item = existing.ok_or_else(|| SourceError::Refused {
                message: format!("GitHub destination item {} was not found", target.0),
            })?;
            let content_kind = ContentKind::parse(item.get("content").unwrap_or(&Value::Null))?;
            if content_kind == ContentKind::DraftIssue && !write.item.labels.is_empty() {
                return Err(SourceError::Refused {
                    message: "GitHub draft items cannot represent labels".into(),
                });
            }
            if content_kind == ContentKind::Issue {
                let held = Self::labels(&item)?;
                if held != write.item.labels {
                    return Err(SourceError::Refused {
                        message: "GitHub issue labels differ from the labels being written".into(),
                    });
                }
                let native = item
                    .pointer("/content/repository/nameWithOwner")
                    .and_then(Value::as_str)
                    .map(|value| format!("github.com/{value}"));
                if write
                    .item
                    .repositories
                    .iter()
                    .map(Repository::as_str)
                    .collect::<Vec<_>>()
                    != native.iter().map(String::as_str).collect::<Vec<_>>()
                {
                    return Err(SourceError::Refused {
                        message:
                            "GitHub issue repository differs from the repositories being written"
                                .into(),
                    });
                }
            }
            let operation = match content_kind {
                ContentKind::DraftIssue => graphql::UPDATE_DRAFT,
                ContentKind::Issue => graphql::UPDATE_ISSUE,
            };
            let input = if content_kind == ContentKind::DraftIssue {
                json!({"draftIssueId":target.0,"title":write.item.title,"body":write.item.content})
            } else {
                json!({"id":target.0,"title":write.item.title,"body":write.item.content})
            };
            let data = self.graphql(operation, json!({"input":input})).await?;
            let pointer = if content_kind == ContentKind::DraftIssue {
                "/updateProjectV2DraftIssue/draftIssue"
            } else {
                "/updateIssue/issue"
            };
            let returned = data
                .pointer(pointer)
                .ok_or_else(|| SourceError::Malformed {
                    message: "GitHub item update returned no item".into(),
                })?;
            if required_str(returned, "id")? != target.0 {
                return Err(SourceError::Malformed {
                    message: "GitHub item update returned the wrong item".into(),
                });
            }
            (
                target.clone(),
                NativeId(required_str(&item, "id")?.into()),
                content_kind,
            )
        } else {
            if !write.item.labels.is_empty() {
                return Err(SourceError::Refused {
                    message: "GitHub draft items cannot represent labels".into(),
                });
            }
            let data = self
                .graphql(
                    graphql::CREATE_DRAFT,
                    json!({"input":{
                        "projectId":project_id,"title":write.item.title,"body":write.item.content
                    }}),
                )
                .await?;
            let created = data
                .pointer("/addProjectV2DraftIssue/projectItem")
                .ok_or_else(|| SourceError::Malformed {
                    message: "GitHub draft creation returned no project item".into(),
                })?;
            (
                NativeId(
                    required_str(created.pointer("/content").unwrap_or(&Value::Null), "id")?.into(),
                ),
                NativeId(required_str(created, "id")?.into()),
                ContentKind::DraftIssue,
            )
        };

        let mut fallback = Vec::new();
        let mut native = Vec::new();
        for edge in &write.depends_on {
            let same_source = edge
                .to
                .source()
                .is_none_or(|source| source == self.name.as_str());
            let far_id = edge
                .to
                .id()
                .rsplit_once(':')
                .map_or(edge.to.id(), |(_, id)| id);
            let far_issue = if same_source {
                let far = self
                    .board_and_item(Some(&NativeId(far_id.into())))
                    .await?
                    .1
                    .ok_or_else(|| SourceError::Refused {
                        message: format!("GitHub dependency item {far_id} was not found"),
                    })?;
                match required_str(far.get("content").unwrap_or(&Value::Null), "__typename")? {
                    "Issue" => true,
                    "DraftIssue" | "PullRequest" => false,
                    other => {
                        return Err(SourceError::Malformed {
                            message: format!(
                                "GitHub dependency item has unknown content type {other}"
                            ),
                        });
                    }
                }
            } else {
                false
            };
            if content_kind == ContentKind::Issue && far_issue && edge.to.kind == ItemKind::Task {
                native.push(far_id.to_owned());
            } else {
                fallback.push(edge.clone());
            }
        }
        if content_kind == ContentKind::Issue {
            let current = self.native_dependency_ids(&content_id).await?;
            for (operation, far_id) in current
                .iter()
                .filter(|id| !native.contains(id))
                .map(|id| (graphql::REMOVE_BLOCKED_BY, id))
                .chain(
                    native
                        .iter()
                        .filter(|id| !current.contains(id))
                        .map(|id| (graphql::ADD_BLOCKED_BY, id)),
                )
            {
                let data = self
                    .graphql(
                        operation,
                        json!({"input":{"issueId":content_id.0,"blockingIssueId":far_id}}),
                    )
                    .await?;
                let root = if operation == graphql::ADD_BLOCKED_BY {
                    "addBlockedBy"
                } else {
                    "removeBlockedBy"
                };
                let issue = data.pointer(&format!("/{root}/issue")).ok_or_else(|| {
                    SourceError::Malformed {
                        message: "GitHub dependency update returned no issue".into(),
                    }
                })?;
                let blocker = data
                    .pointer(&format!("/{root}/blockingIssue"))
                    .ok_or_else(|| SourceError::Malformed {
                        message: "GitHub dependency update returned no blocking issue".into(),
                    })?;
                if required_str(issue, "id")? != content_id.0
                    || required_str(blocker, "id")? != far_id
                {
                    return Err(SourceError::Malformed {
                        message: "GitHub dependency update returned the wrong issues".into(),
                    });
                }
            }
        }
        let metadata_write = ItemWrite {
            target: write.target.clone(),
            item: write.item.clone(),
            depends_on: fallback,
        };
        let storage = if content_kind == ContentKind::Issue {
            RepositoryStorage::Native
        } else {
            RepositoryStorage::Recorded
        };
        let metadata = Self::task_metadata(&metadata_write, storage)?;
        self.set_item_field(
            project_id,
            &item_id.0,
            required_str(metadata_field, "id")?,
            json!({"text":Value::Object(metadata.clone().into_iter().collect()).to_string()}),
        )
        .await?;

        if let Some((field_id, option_id)) = status_selection {
            self.set_item_field(
                project_id,
                &item_id.0,
                &field_id,
                json!({"singleSelectOptionId":option_id}),
            )
            .await?;
        }
        Ok(content_id)
    }

    async fn write_project(&self, write: &ItemWrite<Project>) -> Result<NativeId, SourceError> {
        let project = self.project_value(None, 1).await?;
        let id = NativeId(required_str(&project, "id")?.into());
        if write.target.as_ref().is_some_and(|target| target != &id) {
            return Err(SourceError::Refused {
                message: format!(
                    "GitHub project {} was not found",
                    write.target.as_ref().unwrap().0
                ),
            });
        }
        if !write.item.labels.is_empty() {
            return Err(SourceError::Refused {
                message: "GitHub Projects v2 cannot represent project labels".into(),
            });
        }
        let mut metadata = write.item.metadata.clone();
        metadata.insert(
            Repository::METADATA_KEY.into(),
            Value::Array(
                write
                    .item
                    .repositories
                    .iter()
                    .map(|repository| Value::String(repository.as_str().to_owned()))
                    .collect(),
            ),
        );
        metadata.insert(
            DependencyEdge::RECORDED_KEY.into(),
            Value::Array(
                write
                    .depends_on
                    .iter()
                    .map(|edge| endpoint_value(&edge.to))
                    .collect(),
            ),
        );
        let description = project_metadata_description(write.item.content.as_deref(), &metadata)?;
        let data = self
            .graphql(
                graphql::UPDATE_PROJECT,
                json!({"input":{
                    "projectId":id.0,"title":write.item.title,"shortDescription":description,
                    "closed":write.item.status.category == StatusCategory::Done
                }}),
            )
            .await?;
        let returned =
            data.pointer("/updateProjectV2/projectV2")
                .ok_or_else(|| SourceError::Malformed {
                    message: "GitHub project update returned no project".into(),
                })?;
        if required_str(returned, "id")? != id.0 {
            return Err(SourceError::Malformed {
                message: "GitHub project update returned the wrong project".into(),
            });
        }
        Ok(id)
    }
}

/// Where the recorded tail of a task-dependency walk resumes; see
/// [`GitHubProjectsSource::recorded_task_edges`].
const RECORDED_CURSOR: &str = "onetaskgraph.depends_on:";

/// Where a recorded tail resumes, refusing a cursor no walk in `direction` reported.
///
/// The reserved key holds forward edges and nothing else — the reverse of a recorded edge
/// is derived from the far end, never written down on the near item — so only a forward
/// walk ever reports one of these cursors. A reverse read carrying one is resuming a walk
/// it did not come from, and it is told so rather than answered with an empty page that
/// reads as a walk which ended.
fn recorded_offset(
    cursor: Option<&str>,
    direction: Direction,
) -> Result<Option<usize>, SourceError> {
    cursor
        .and_then(|cursor| cursor.strip_prefix(RECORDED_CURSOR))
        .map(|offset| {
            if direction != Direction::DependsOn {
                return Err(SourceError::Config {
                    message: format!(
                        "{RECORDED_CURSOR}{offset} resumes recorded forward edges, which a \
                         reverse dependency read never issues; resume it in the direction \
                         that reported it"
                    ),
                });
            }
            offset.parse().map_err(|_| SourceError::Config {
                message: format!("{RECORDED_CURSOR}{offset} is not a recorded-edge cursor"),
            })
        })
        .transpose()
}

fn recorded_page(edges: Vec<DependencyEdge>, offset: usize, limit: usize) -> Page<DependencyEdge> {
    let mut page = offset_page(edges, offset, limit.max(1));
    page.next = page
        .next
        .map(|cursor| Cursor(format!("{RECORDED_CURSOR}{}", cursor.0)));
    page
}

fn normalize_status_mapping(
    mapping: BTreeMap<String, StatusCategory>,
) -> Result<BTreeMap<StatusName, StatusCategory>, SourceError> {
    let mut normalized = BTreeMap::new();
    for (name, category) in mapping {
        if name.trim().is_empty() {
            return Err(SourceError::Config {
                message: "status_mapping contains a blank status name".into(),
            });
        }
        let key = StatusName::new(&name);
        if normalized.insert(key, category).is_some() {
            return Err(SourceError::Config {
                message: format!("status_mapping contains case-insensitive duplicate {name}"),
            });
        }
    }
    Ok(normalized)
}

fn valid_github_owner(owner: &str) -> bool {
    !owner.is_empty()
        && owner.len() <= 39
        && !owner.starts_with('-')
        && !owner.ends_with('-')
        && !owner.contains("--")
        && owner
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'-')
}

fn valid_environment_name(name: &str) -> bool {
    let mut bytes = name.bytes();
    bytes
        .next()
        .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
        && bytes.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
}

#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
struct StatusName(String);

impl StatusName {
    fn new(name: &str) -> Self {
        Self(name.to_lowercase())
    }
}

fn required_str<'a>(value: &'a Value, field: &str) -> Result<&'a str, SourceError> {
    value
        .get(field)
        .and_then(Value::as_str)
        .ok_or_else(|| SourceError::Malformed {
            message: format!("GitHub response is missing string field {field}"),
        })
}

const METADATA_FIELD: &str = "onetaskgraph.metadata";

fn endpoint_value(endpoint: &DependencyEndpoint) -> Value {
    json!({"id":endpoint.id(), "kind":match endpoint.kind { ItemKind::Task => "task", ItemKind::Project => "project" }})
}

fn metadata_field(field_values: &Value) -> Result<BTreeMap<String, Value>, SourceError> {
    let nodes = field_values
        .get("nodes")
        .and_then(Value::as_array)
        .ok_or_else(|| SourceError::Malformed {
            message: "GitHub project item fieldValues.nodes is not an array".into(),
        })?;
    let Some(text) = nodes
        .iter()
        .find(|node| node.pointer("/field/name").and_then(Value::as_str) == Some(METADATA_FIELD))
        .and_then(|node| node.get("text"))
    else {
        return Ok(BTreeMap::new());
    };
    text.as_str()
        .ok_or_else(|| SourceError::Malformed {
            message: format!("GitHub {METADATA_FIELD} field text is not a string"),
        })
        .and_then(|text| {
            serde_json::from_str(text).map_err(|error| SourceError::Malformed {
                message: format!(
                    "GitHub {METADATA_FIELD} field is not canonical JSON metadata: {error}"
                ),
            })
        })
}

fn repositories(content: &Value, field_values: &Value) -> Result<Vec<Repository>, SourceError> {
    if let Some(origin) = content
        .pointer("/repository/nameWithOwner")
        .and_then(Value::as_str)
    {
        return Repository::try_from(format!("github.com/{origin}"))
            .map(|repository| vec![repository])
            .map_err(|message| SourceError::Malformed { message });
    }
    repositories_from_metadata(&metadata_field(field_values)?)
}

const PROJECT_METADATA_OPEN: &str = "<!-- onetaskgraph.metadata\n";
const PROJECT_METADATA_CLOSE: &str = "\n-->";

fn metadata_description(
    description: Option<String>,
) -> Result<(Option<String>, BTreeMap<String, Value>), SourceError> {
    let Some(description) = description else {
        return Ok((None, BTreeMap::new()));
    };
    let Some(start) = description.rfind(PROJECT_METADATA_OPEN) else {
        return Ok((Some(description), BTreeMap::new()));
    };
    let value_start = start + PROJECT_METADATA_OPEN.len();
    let Some(relative_end) = description[value_start..].find(PROJECT_METADATA_CLOSE) else {
        return Err(SourceError::Malformed {
            message: "unterminated onetaskgraph metadata slot in GitHub project description".into(),
        });
    };
    let value_end = value_start + relative_end;
    if !description[value_end + PROJECT_METADATA_CLOSE.len()..]
        .trim()
        .is_empty()
    {
        return Ok((Some(description), BTreeMap::new()));
    }
    let metadata = serde_json::from_str(&description[value_start..value_end]).map_err(|error| {
        SourceError::Malformed {
            message: format!("invalid canonical JSON in GitHub project metadata slot: {error}"),
        }
    })?;
    let visible = description[..start].trim_end();
    Ok(((!visible.is_empty()).then(|| visible.into()), metadata))
}

fn project_metadata_description(
    content: Option<&str>,
    metadata: &BTreeMap<String, Value>,
) -> Result<Option<String>, SourceError> {
    if metadata.is_empty() {
        return Ok(content.filter(|value| !value.is_empty()).map(str::to_owned));
    }
    let encoded = Value::Object(metadata.clone().into_iter().collect()).to_string();
    Ok(Some(format!(
        "{}{}{}\n{}",
        content.unwrap_or_default(),
        if content.is_some_and(|value| !value.is_empty()) {
            "\n\n"
        } else {
            ""
        },
        PROJECT_METADATA_OPEN,
        format_args!("{encoded}\n-->")
    )))
}

fn repositories_from_metadata(
    metadata: &BTreeMap<String, Value>,
) -> Result<Vec<Repository>, SourceError> {
    Repository::from_metadata(metadata).map_err(|message| SourceError::Malformed { message })
}
fn required_bool(value: &Value, field: &str) -> Result<bool, SourceError> {
    value
        .get(field)
        .and_then(Value::as_bool)
        .ok_or_else(|| SourceError::Malformed {
            message: format!("GitHub response is missing boolean field {field}"),
        })
}
fn optional_str<'a>(value: &'a Value, field: &str) -> Result<Option<&'a str>, SourceError> {
    match value.get(field) {
        None | Some(Value::Null) => Ok(None),
        Some(value) => value
            .as_str()
            .map(Some)
            .ok_or_else(|| SourceError::Malformed {
                message: format!("GitHub response field {field} is not a string or null"),
            }),
    }
}
fn optional_nodes<'a>(
    connection: Option<&'a Value>,
    name: &str,
) -> Result<Option<&'a Vec<Value>>, SourceError> {
    match connection {
        None | Some(Value::Null) => Ok(None),
        Some(value) => value
            .get("nodes")
            .and_then(Value::as_array)
            .map(Some)
            .ok_or_else(|| SourceError::Malformed {
                message: format!("GitHub {name}.nodes is not an array"),
            }),
    }
}
fn complete_connection(connection: &Value, name: &str) -> Result<(), SourceError> {
    let page_info = connection
        .get("pageInfo")
        .ok_or_else(|| SourceError::Malformed {
            message: format!("GitHub {name} has no pageInfo"),
        })?;
    if required_bool(page_info, "hasNextPage")? {
        return Err(SourceError::Malformed {
            message: format!(
                "GitHub {name} exceeds the supported nested connection size of {NESTED_PAGE_SIZE}"
            ),
        });
    }
    Ok(())
}
fn optional_time(value: &Value, field: &str) -> Result<Option<DateTime<Utc>>, SourceError> {
    optional_str(value, field)?
        .map(|timestamp| {
            timestamp.parse().map_err(|error| SourceError::Malformed {
                message: format!("GitHub response field {field} is not a timestamp: {error}"),
            })
        })
        .transpose()
}
fn validate_page(page: &PageRequest) -> Result<(), SourceError> {
    if page.limit == 0 {
        Err(SourceError::Config {
            message: "page limit must be at least 1".into(),
        })
    } else {
        Ok(())
    }
}
fn next_cursor(connection: &Value) -> Result<Option<Cursor>, SourceError> {
    let page = connection
        .get("pageInfo")
        .filter(|value| value.is_object())
        .ok_or_else(|| SourceError::Malformed {
            message: "GitHub connection is missing pageInfo".into(),
        })?;
    if required_bool(page, "hasNextPage")? {
        let cursor = required_str(page, "endCursor")?;
        validate_cursor_progress(None, cursor)?;
        Ok(Some(Cursor(cursor.into())))
    } else {
        Ok(None)
    }
}
fn validate_cursor_progress(previous: Option<&str>, next: &str) -> Result<(), SourceError> {
    if next.is_empty() || previous == Some(next) {
        Err(SourceError::Malformed {
            message: "GitHub pagination cursor is empty or did not advance".into(),
        })
    } else {
        Ok(())
    }
}
fn numeric_cursor(cursor: Option<&Cursor>) -> Result<usize, SourceError> {
    cursor.map_or(Ok(0), |c| {
        c.0.parse().map_err(|_| SourceError::Config {
            message: "label cursor is invalid".into(),
        })
    })
}
fn offset_page<T>(mut items: Vec<T>, offset: usize, limit: usize) -> Page<T> {
    if offset > items.len() {
        return Page::last(vec![]);
    }
    let tail = items.split_off(offset);
    let mut selected = tail;
    let next = (selected.len() > limit).then(|| Cursor((offset + limit).to_string()));
    selected.truncate(limit);
    Page {
        items: selected,
        next,
    }
}