thirdshift 0.13.1

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! Asking GitHub, through `gh`, about issues, pull requests and the signed-in
//! user.

use std::fmt;
use std::process::{Command, Output};
use std::time::Duration;

use anyhow::{Context, Result, bail};
use chrono::{DateTime, Utc};
use serde_json::Value;

use crate::issue::{IssueUrl, Repo};
use crate::labels::{Label, Labels};
use crate::process::{self, Control, Interruption};

mod check_read;
pub(crate) use check_read::is_transient as check_read_is_transient;

mod advisories;
mod session_issue;
mod trust;
pub use advisories::{
    DraftAdvisory, FindingDraft, FindingProvenance, Package, RecordedFinding, SecurityRecord,
    SecurityRecords,
};

#[cfg(test)]
mod execution_tests;

/// A failed gh command keeps its diagnostic locally; notifications use only
/// its fixed operational category.
#[derive(Debug)]
enum CommandFailure {
    Rejected { command: String, stderr: String },
    InvalidJson { command: String },
    InvalidResponse(String),
    Execution,
}

impl CommandFailure {
    fn rejected(command: String, output: &Output) -> Self {
        Self::Rejected {
            command,
            stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
        }
    }
}

impl fmt::Display for CommandFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Rejected { command, stderr } => write!(f, "{command} failed: {stderr}"),
            Self::InvalidJson { command } => write!(f, "{command} returned invalid JSON"),
            Self::InvalidResponse(message) => f.write_str(message),
            Self::Execution => f.write_str("could not run gh"),
        }
    }
}

impl std::error::Error for CommandFailure {}

/// A fixed cause for failed GitHub queries, never their original diagnostics.
/// Only explicit quota messages establish exhaustion; a bare 403 does not.
pub(crate) fn operational_cause(error: &anyhow::Error) -> Option<&'static str> {
    let stderr = match error.downcast_ref::<CommandFailure>() {
        Some(CommandFailure::Rejected { stderr, .. }) => stderr,
        Some(_) => return Some("GitHub dependency failure"),
        None => &error.downcast_ref::<check_read::ReadFailure>()?.stderr,
    };
    let stderr = stderr.to_ascii_lowercase();
    Some(
        if stderr.contains("api rate limit exceeded")
            || stderr.contains("api rate limit already exceeded")
            || stderr.contains("secondary rate limit")
        {
            "GitHub rate-limit exhaustion"
        } else {
            "GitHub dependency failure"
        },
    )
}

/// GitHub CLI operations bound to an immutable interruption policy.
/// Ordinary views stop for Command interruption; completion views finish
/// independently without changing the recorded request or other views.
pub struct GitHub {
    interruption: Interruption,
}

impl GitHub {
    pub fn new() -> Self {
        Self {
            interruption: Interruption::Ordinary,
        }
    }

    pub fn completion(&self) -> Self {
        Self {
            interruption: Interruption::Completion,
        }
    }

    /// The `fields` of `issue`, as JSON.
    fn issue_view(&self, issue: &IssueUrl, fields: &str) -> Result<Value> {
        self.gh_json(&[
            "issue",
            "view",
            &issue.number.to_string(),
            "--repo",
            &issue.repo_slug(),
            "--json",
            fields,
        ])
    }

    /// Whether `issue` is open.
    pub fn issue_is_open(&self, issue: &IssueUrl) -> Result<bool> {
        state_is_open(&self.issue_view(issue, "state")?)
    }

    /// The title of `issue`.
    pub fn issue_title(&self, issue: &IssueUrl) -> Result<String> {
        let json = self.issue_view(issue, "title")?;
        Ok(json["title"]
            .as_str()
            .context(CommandFailure::InvalidResponse(
                "gh output has no title".into(),
            ))?
            .to_string())
    }

    /// `issue`'s title, state, labels and when it was created.
    pub fn issue(&self, issue: &IssueUrl) -> Result<Issue> {
        let json = self.issue_view(issue, "title,state,labels,createdAt")?;
        let created = json["createdAt"]
            .as_str()
            .context(CommandFailure::InvalidResponse(
                "gh output has no createdAt".into(),
            ))?;
        Ok(Issue {
            title: json["title"].as_str().map(String::from),
            is_open: state_is_open(&json)?,
            labels: labels_of(&json)?,
            created: DateTime::parse_from_rfc3339(created)
                .with_context(|| {
                    CommandFailure::InvalidResponse(format!(
                        "gh output has an unreadable createdAt {created}"
                    ))
                })?
                .to_utc(),
        })
    }

    /// The labels of `issue`.
    pub fn issue_labels(&self, issue: &IssueUrl) -> Result<Labels> {
        labels_of(&self.issue_view(issue, "labels")?)
    }

    /// Set `issue`'s labels to exactly `labels`, in one request, so a swap of
    /// one label for another can't stop halfway. Through the REST API: `gh issue
    /// edit` fails on the GitHub Projects (classic) sunset in older `gh`.
    pub fn set_labels(&self, issue: &IssueUrl, labels: &Labels) -> Result<()> {
        let path = labels_path(issue);
        let fields: Vec<String> = labels
            .names()
            .map(|label| format!("labels[]={label}"))
            .collect();
        let mut args = vec!["api", "--method", "PUT", &path, "--silent"];
        for field in &fields {
            args.extend(["-f", field]);
        }
        self.gh(&args)
    }

    /// Take `label` off `issue`, in one request that keeps its other labels.
    /// Through the REST API, as [`GitHub::set_labels`] is. GitHub refuses it if the issue
    /// does not have the label.
    pub fn remove_label(&self, issue: &IssueUrl, label: &str) -> Result<()> {
        self.gh(&[
            "api",
            "--method",
            "DELETE",
            &label_path(issue, label),
            "--silent",
        ])
    }

    /// The sub-issues of `issue`, its Tickets if it has any, in one query.
    pub fn tickets(&self, issue: &IssueUrl) -> Result<Vec<Ticket>> {
        let json = self.issue_query(issue, TICKETS_QUERY, None)?;
        nodes(
            &json["data"]["repository"]["issue"]["subIssues"],
            "subIssues",
        )?
        .iter()
        .map(|node| {
            let mut blockers = Vec::new();
            let mut open_blockers = Vec::new();
            for blocker in nodes(&node["blockedBy"], "blockedBy")? {
                blockers.push(node_issue(blocker)?);
                if node_is_open(blocker)? {
                    open_blockers.push(node_issue(blocker)?);
                }
            }
            Ok(Ticket {
                issue: node_issue(node)?,
                is_open: node_is_open(node)?,
                labels: named(nodes(&node["labels"], "labels")?),
                has_sub_issues: sub_issue_count(node)? > 0,
                blockers,
                open_blockers,
            })
        })
        .collect()
    }

    /// The answer to `query`, a GraphQL query about `issue` that takes its
    /// `$owner`, `$repo` and `$number`, and an optional label-history cursor.
    fn issue_query(&self, issue: &IssueUrl, query: &str, after: Option<&str>) -> Result<Value> {
        let query = format!("query={query}");
        let owner = format!("owner={}", issue.owner);
        let repo = format!("repo={}", issue.repo);
        let number = format!("number={}", issue.number);
        let mut args = vec![
            "api", "graphql", "-f", &query, "-f", &owner, "-f", &repo, "-F", &number,
        ];
        let cursor;
        if let Some(after) = after {
            cursor = format!("after={after}");
            args.extend(["-f", &cursor]);
        }
        self.gh_json(&args)
    }

    /// Every node of `issue`'s `connection`, the `what` that `query` reads
    /// page by page through its `$after` cursor, with the last page's answer.
    fn paged_nodes(
        &self,
        issue: &IssueUrl,
        query: &str,
        connection: &str,
        what: &str,
    ) -> Result<(Value, Vec<Value>)> {
        let mut after = None;
        let mut all = Vec::new();
        loop {
            let json = self.issue_query(issue, query, after.as_deref())?;
            let page = &json["data"]["repository"]["issue"][connection];
            all.extend(nodes(page, connection)?.iter().cloned());
            let info = &page["pageInfo"];
            if !info["hasNextPage"].as_bool().with_context(|| {
                CommandFailure::InvalidResponse(format!("{what} has no hasNextPage"))
            })? {
                return Ok((json, all));
            }
            let next = info["endCursor"].as_str().with_context(|| {
                CommandFailure::InvalidResponse(format!("{what} has no endCursor"))
            })?;
            if Some(next) == after.as_deref() {
                bail!(CommandFailure::InvalidResponse(format!(
                    "{what} cursor did not advance"
                )));
            }
            after = Some(next.to_string());
        }
    }

    /// Close `issue` with `comment`.
    pub fn close_issue(&self, issue: &IssueUrl, comment: &str) -> Result<()> {
        self.gh(&[
            "issue",
            "close",
            &issue.number.to_string(),
            "--repo",
            &issue.repo_slug(),
            "--comment",
            comment,
        ])
    }

    /// The numeric database id of `issue`, for API calls that take one
    /// instead of the issue number (sub-issues, dependencies).
    fn issue_db_id(&self, issue: &IssueUrl) -> Result<u64> {
        let json = self.gh_json(&[
            "api",
            &format!("repos/{}/issues/{}", issue.repo_slug(), issue.number),
            "--jq",
            ".id",
        ])?;
        json.as_u64().context(CommandFailure::InvalidResponse(
            "gh api did not return the issue's database id".into(),
        ))
    }

    /// Link `child` as a native sub-issue of `parent`.
    pub fn add_sub_issue(&self, parent: &IssueUrl, child: &IssueUrl) -> Result<()> {
        let child_id = self.issue_db_id(child)?;
        self.post_by_id(
            parent,
            &format!("issues/{}/sub_issues", parent.number),
            "sub_issue_id",
            child_id,
        )
    }

    /// Add a native "blocked by" edge: `ticket` is blocked by `blocker`.
    pub fn add_blocked_by(&self, ticket: &IssueUrl, blocker: &IssueUrl) -> Result<()> {
        let blocker_id = self.issue_db_id(blocker)?;
        self.post_by_id(
            ticket,
            &format!("issues/{}/dependencies/blocked_by", ticket.number),
            "issue_id",
            blocker_id,
        )
    }

    /// `POST` one database-id field to the `endpoint` below
    /// `repos/<owner>/<repo>`: the shared shape behind issue links that take
    /// an id instead of an issue number.
    fn post_by_id(&self, issue: &IssueUrl, endpoint: &str, field: &str, id: u64) -> Result<()> {
        self.gh(&[
            "api",
            "--method",
            "POST",
            &format!("repos/{}/{}", issue.repo_slug(), endpoint),
            "-F",
            &format!("{field}={id}"),
        ])
    }

    /// Every open issue labelled `label` in the repository `repo`, an
    /// `owner/repo`, newest first. They come from GitHub's issue list, not its
    /// search, whose index can be a while behind an issue just opened.
    pub fn open_issues_labelled(&self, repo: &str, label: Label) -> Result<Vec<ListedIssue>> {
        self.issues_labelled(repo, label, "open")
    }

    /// Every closed issue labelled `label` in the repository `repo`, an
    /// `owner/repo`, newest first.
    pub fn closed_issues_labelled(&self, repo: &str, label: Label) -> Result<Vec<ListedIssue>> {
        self.issues_labelled(repo, label, "closed")
    }

    /// Every issue labelled `label` in the repository `repo` whose state is
    /// `state`, `open` or `closed`, newest first.
    fn issues_labelled(&self, repo: &str, label: Label, state: &str) -> Result<Vec<ListedIssue>> {
        let json = self.gh_json(&[
            "issue",
            "list",
            "--state",
            state,
            "--repo",
            repo,
            "--label",
            label.name(),
            "--json",
            "url,title,labels",
            "--limit",
            "1000",
        ])?;
        json.as_array()
            .context(CommandFailure::InvalidResponse(
                "gh issue list did not return a list".into(),
            ))?
            .iter()
            .map(|listed| {
                let field = |name: &str| {
                    listed[name].as_str().with_context(|| {
                        CommandFailure::InvalidResponse(format!(
                            "gh issue list output has no {name}"
                        ))
                    })
                };
                Ok(ListedIssue {
                    issue: IssueUrl::parse(field("url")?).context(
                        CommandFailure::InvalidResponse(
                            "gh issue list output has an invalid issue URL".into(),
                        ),
                    )?,
                    title: field("title")?.to_string(),
                    labels: labels_of(listed)?,
                })
            })
            .collect()
    }

    /// Every issue in the repository `repo`, an `owner/repo`, created at or
    /// after `since`, open or closed. The security-fix publishing session
    /// must not create public issues outside the staged path, so anything
    /// dating from its own window is a side-effect leak. Compared at whole
    /// seconds, as the `created` check on a fix Ticket is.
    pub fn issues_created_since(&self, repo: &str, since: DateTime<Utc>) -> Result<Vec<IssueUrl>> {
        let mut found = Vec::new();
        for state in ["open", "closed"] {
            let json = self.gh_json(&[
                "issue",
                "list",
                "--state",
                state,
                "--repo",
                repo,
                "--json",
                "url,createdAt",
                "--limit",
                "1000",
            ])?;
            for listed in json.as_array().context(CommandFailure::InvalidResponse(
                "gh issue list did not return a list".into(),
            ))? {
                let url = listed["url"]
                    .as_str()
                    .context(CommandFailure::InvalidResponse(
                        "gh issue list output has no url".into(),
                    ))?;
                let at = listed["createdAt"]
                    .as_str()
                    .context(CommandFailure::InvalidResponse(
                        "gh issue list output has no createdAt".into(),
                    ))?;
                let at = DateTime::parse_from_rfc3339(at)
                    .with_context(|| {
                        CommandFailure::InvalidResponse(format!(
                            "gh issue list output has an unreadable createdAt {at}"
                        ))
                    })?
                    .to_utc();
                if at.timestamp() >= since.timestamp() {
                    found.push(
                        IssueUrl::parse(url).context(CommandFailure::InvalidResponse(
                            "gh issue list output has an invalid issue URL".into(),
                        ))?,
                    );
                }
            }
        }
        Ok(found)
    }

    /// `issue` as a Pickup run that lists issues by `label` reads it, in one
    /// query per page of label history, oldest first. Every page is read so
    /// missing older Claims cannot be mistaken for never-Claimed work.
    pub fn candidate(&self, issue: &IssueUrl, label: Label) -> Result<Candidate> {
        let (json, label_events) =
            self.paged_nodes(issue, CANDIDATE_QUERY, "labelled", "label history")?;
        let issue = &json["data"]["repository"]["issue"];
        let parent = issue["parent"]["url"]
            .as_str()
            .map(IssueUrl::parse)
            .transpose()
            .context(CommandFailure::InvalidResponse(
                "gh api graphql output has an invalid parent issue URL".into(),
            ))?;
        let mut open_blockers = Vec::new();
        for blocker in nodes(&issue["blockedBy"], "blockedBy")? {
            if node_is_open(blocker)? {
                open_blockers.push(node_number(blocker)?);
            }
        }
        let at = |event: &Value| -> Result<DateTime<Utc>> {
            let at = event["createdAt"]
                .as_str()
                .context(CommandFailure::InvalidResponse(
                    "gh api graphql output has an event with no createdAt".into(),
                ))?;
            Ok(DateTime::parse_from_rfc3339(at)
                .with_context(|| {
                    CommandFailure::InvalidResponse(format!(
                        "gh api graphql output has an unreadable createdAt {at}"
                    ))
                })?
                .to_utc())
        };
        let mut shaped = Vec::new();
        let mut history = ClaimHistory::NeverClaimed;
        let mut claim_generation = 0;
        for event in &label_events {
            let applied = match event["__typename"].as_str() {
                Some("LabeledEvent") => true,
                Some("UnlabeledEvent") => false,
                other => bail!(CommandFailure::InvalidResponse(format!(
                    "gh api graphql output has an unknown label event {other:?}"
                ))),
            };
            let name = event["label"]["name"].as_str();
            if applied && name.is_some_and(|name| crate::claim::IN_PROGRESS.is_named(name)) {
                claim_generation += 1;
            }
            history = history.after(name, applied, label);
            if applied && name.is_some_and(|name| label.is_named(name)) {
                shaped.push(Shaped {
                    by: Shaping::Labelled,
                    at: at(event)?,
                });
            }
        }
        for event in nodes(&issue["linked"], "linked")? {
            let by = match event["__typename"].as_str() {
                Some("SubIssueAddedEvent" | "SubIssueRemovedEvent") => Shaping::SubIssues,
                Some("BlockedByAddedEvent" | "BlockedByRemovedEvent") => Shaping::Blockers,
                other => bail!(CommandFailure::InvalidResponse(format!(
                    "gh api graphql output has an unknown event {other:?}"
                ))),
            };
            shaped.push(Shaped { by, at: at(event)? });
        }
        Ok(Candidate {
            parent,
            sub_issue_is_open: nodes(&issue["subIssues"], "subIssues")?
                .iter()
                .map(node_is_open)
                .collect::<Result<_>>()?,
            open_blockers,
            last_shaped: shaped.into_iter().max_by_key(|shaped| shaped.at),
            handed_back: matches!(history, ClaimHistory::HandedBack),
            claim_generation,
            claimed: matches!(history, ClaimHistory::Claimed),
        })
    }

    /// Add each of `labels` to the repository `repo`, an `owner/repo`, with its
    /// description, unless the repository has it already.
    pub fn ensure_labels(&self, repo: &str, labels: &[Label]) -> Result<()> {
        let known = self.gh_json(&[
            "label", "list", "--repo", repo, "--json", "name", "--limit", "1000",
        ])?;
        let known = named(known.as_array().context(CommandFailure::InvalidResponse(
            "gh label list did not return a list".into(),
        ))?);
        for label in labels {
            if !known.has(*label) {
                self.gh(&[
                    "label",
                    "create",
                    label.name(),
                    "--repo",
                    repo,
                    "--description",
                    label.description(),
                ])?;
            }
        }
        Ok(())
    }

    /// Open an issue titled `title`, with `body` and `labels`, in the repository
    /// of `issue`, and return it. See [`GitHub::create_issue_in`].
    pub fn create_issue(
        &self,
        issue: &IssueUrl,
        title: &str,
        body: &str,
        labels: &[Label],
    ) -> Result<IssueUrl> {
        self.create_issue_in(&issue.repo(), title, body, labels)
    }

    /// Open an issue titled `title`, with `body` and `labels`, in `repo`,
    /// and return it. Each label is first added to the repository,
    /// with its description, if the repository lacks it: `gh` refuses a label it
    /// doesn't know.
    pub fn create_issue_in(
        &self,
        repo: &Repo,
        title: &str,
        body: &str,
        labels: &[Label],
    ) -> Result<IssueUrl> {
        let repo = repo.slug();
        self.ensure_labels(&repo, labels)?;
        let names: Vec<&str> = labels.iter().map(|label| label.name()).collect();
        let url = self.gh_stdout(&[
            "issue",
            "create",
            "--repo",
            &repo,
            "--title",
            title,
            "--body",
            body,
            "--label",
            &names.join(","),
        ])?;
        IssueUrl::parse(&url).context(CommandFailure::InvalidResponse(
            "gh issue create did not print the issue's URL".into(),
        ))
    }

    /// The public email of the signed-in user's GitHub profile, or `None` if it
    /// is private. Private addresses need the `user` scope, which a default
    /// `gh auth login` token lacks, so thirdshift never asks for them.
    pub fn profile_email(&self) -> Result<Option<String>> {
        let json = self.gh_json(&["api", "user"])?;
        Ok(json["email"].as_str().map(str::to_string))
    }

    /// The `fields` of the pull request `pr`, its head branch or its number, as
    /// JSON.
    fn pr_view(&self, issue: &IssueUrl, pr: &str, fields: &str) -> Result<Value> {
        self.gh_json(&[
            "pr",
            "view",
            pr,
            "--repo",
            &issue.repo_slug(),
            "--json",
            fields,
        ])
    }

    /// A PR JSON read where GitHub's missing-PR diagnostic means absence.
    /// Active cancellation and all other transport failures still propagate.
    fn optional_pr_view(
        &self,
        issue: &IssueUrl,
        selector: &str,
        fields: &str,
    ) -> Result<Option<Value>> {
        match self.pr_view(issue, selector, fields) {
            Ok(json) => Ok(Some(json)),
            Err(error) if format!("{error:#}").contains("no pull requests found") => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// A coherent pull request observation, selected by head branch for initial
    /// discovery and by number after capture. Policy belongs to the pull
    /// request owner.
    pub fn pr_snapshot(&self, issue: &IssueUrl, selector: &str) -> Result<Option<PrSnapshot>> {
        let Some(json) = self.optional_pr_view(issue, selector, SNAPSHOT_FIELDS)? else {
            return Ok(None);
        };
        let mergeable = match json["mergeable"].as_str() {
            Some("MERGEABLE") => Mergeable::Yes,
            Some("CONFLICTING") => Mergeable::No,
            Some("UNKNOWN") => Mergeable::Unknown,
            other => bail!(CommandFailure::InvalidResponse(format!(
                "gh output has an unknown mergeable state {other:?}"
            ))),
        };
        Ok(Some(PrSnapshot {
            pr: PullRequest::from_json(&json)?,
            mergeable,
            head_commit: json["headRefOid"]
                .as_str()
                .context(CommandFailure::InvalidResponse(
                    "gh output has no headRefOid".into(),
                ))?
                .to_string(),
            from_fork: json["isCrossRepository"].as_bool().context(
                CommandFailure::InvalidResponse("gh output has no isCrossRepository".into()),
            )?,
        }))
    }

    /// Every pull request in this repository, in any state, whose head branch
    /// starts with `prefix`. PRs from forks are left out: their heads are not
    /// this repository's branches.
    pub fn pull_requests_with_head_prefix(
        &self,
        issue: &IssueUrl,
        prefix: &str,
    ) -> Result<Vec<PullRequest>> {
        let json = self.gh_json(&[
            "pr",
            "list",
            "--repo",
            &issue.repo_slug(),
            "--state",
            "all",
            "--search",
            &format!("head:{prefix}"),
            "--limit",
            "1000",
            "--json",
            &format!("{PR_FIELDS},isCrossRepository"),
        ])?;
        json.as_array()
            .context(CommandFailure::InvalidResponse(
                "gh pr list did not return a list".into(),
            ))?
            .iter()
            .filter(|pr| pr["isCrossRepository"] != Value::Bool(true))
            .map(PullRequest::from_json)
            .collect()
    }

    /// Open a draft pull request from `head` into `base`, and return its URL.
    pub fn create_draft_pr(
        &self,
        issue: &IssueUrl,
        head: &str,
        base: &str,
        title: &str,
        body: &str,
    ) -> Result<String> {
        self.gh_stdout(&[
            "pr",
            "create",
            "--repo",
            &issue.repo_slug(),
            "--head",
            head,
            "--base",
            base,
            "--title",
            title,
            "--body",
            body,
            "--draft",
        ])
    }

    /// The body of pull request `number`.
    pub fn pr_body(&self, issue: &IssueUrl, number: u64) -> Result<String> {
        let json = self.pr_view(issue, &number.to_string(), "body")?;
        Ok(json["body"]
            .as_str()
            .context(CommandFailure::InvalidResponse(
                "gh output has no body".into(),
            ))?
            .to_string())
    }

    /// Set the body of pull request `number` to `body`, through the REST API:
    /// `gh pr edit` fails on the GitHub Projects (classic) sunset in older `gh`.
    pub fn set_pr_body(&self, issue: &IssueUrl, number: u64, body: &str) -> Result<()> {
        self.gh(&[
            "api",
            "--method",
            "PATCH",
            &format!("repos/{}/pulls/{number}", issue.repo_slug()),
            "-f",
            &format!("body={body}"),
            "--silent",
        ])
    }

    /// Mark the selected pull request ready for review.
    pub fn mark_ready(&self, issue: &IssueUrl, selector: &str) -> Result<()> {
        self.gh(&["pr", "ready", selector, "--repo", &issue.repo_slug()])
    }

    /// Convert the selected pull request back to a draft. Spec PR creation
    /// also uses this before Delivery has captured its identity.
    pub fn convert_to_draft(&self, issue: &IssueUrl, selector: &str) -> Result<()> {
        self.gh(&[
            "pr",
            "ready",
            selector,
            "--undo",
            "--repo",
            &issue.repo_slug(),
        ])
    }

    /// Whether a structured review decision blocks this numbered PR's merge.
    /// Failed or unrecognized reads are unknown and leave the merge to GitHub.
    pub fn review_blocks_merge(&self, issue: &IssueUrl, number: u64) -> bool {
        self.pr_view(issue, &number.to_string(), "reviewDecision")
            .ok()
            .is_some_and(|json| {
                matches!(
                    json["reviewDecision"].as_str(),
                    Some("REVIEW_REQUIRED" | "CHANGES_REQUESTED")
                )
            })
    }

    /// One guarded merge request, with a merge commit and without auto-merge
    /// or local branch deletion (ADR 0004). Delivery owns reconciliation.
    pub fn merge(&self, issue: &IssueUrl, number: u64, head: &str) -> Result<()> {
        self.gh(&[
            "pr",
            "merge",
            &number.to_string(),
            "--repo",
            &issue.repo_slug(),
            "--merge",
            "--match-head-commit",
            head,
        ])
    }

    /// Every check run and commit status on commit `sha`, each with its
    /// conclusion as GitHub named it. Of the check runs sharing a name, as
    /// the attempts of a re-run job do, only the latest is here.
    pub fn checks_on(&self, issue: &IssueUrl, sha: &str) -> Result<Vec<Check>> {
        let commit = format!("repos/{}/commits/{sha}", issue.repo_slug());
        // CI retries the complete observation, not its individual requests.
        let runs =
            self.gh_api_items_once(&format!("{commit}/check-runs?per_page=100"), "check_runs")?;
        let statuses =
            self.gh_api_items_once(&format!("{commit}/status?per_page=100"), "statuses")?;
        let url = |value: &Value| {
            value
                .as_str()
                .filter(|url| !url.is_empty())
                .map(String::from)
        };

        let mut checks = Vec::new();
        for run in &runs {
            let conclusion = match run["status"].as_str() {
                Some("completed") => Conclusion::of_check_run(run["conclusion"].as_str()),
                _ => Conclusion::Unfinished,
            };
            checks.push(Check {
                name: run["name"]
                    .as_str()
                    .context(CommandFailure::InvalidResponse(
                        "a check run has no name".into(),
                    ))?
                    .to_string(),
                conclusion,
                job: ActionsJob::of(run["id"].as_u64(), run["details_url"].as_str()),
                url: url(&run["details_url"]).or_else(|| url(&run["html_url"])),
            });
        }
        for status in &statuses {
            let conclusion = Conclusion::of_commit_status(status["state"].as_str());
            checks.push(Check {
                name: status["context"]
                    .as_str()
                    .context(CommandFailure::InvalidResponse(
                        "a commit status has no context".into(),
                    ))?
                    .to_string(),
                conclusion,
                url: url(&status["target_url"]),
                job: None,
            });
        }
        Ok(checks)
    }

    /// The GitHub Actions job whose check run is `check_run`, as the jobs
    /// API reports it: its conclusion and each of its steps'.
    pub fn job_run(&self, issue: &IssueUrl, check_run: u64) -> Result<JobRun> {
        let path = format!("repos/{}/actions/jobs/{check_run}", issue.repo_slug());
        let job = self.gh_json(&["api", &path])?;
        let conclusion = |value: &Value| match value["status"].as_str() {
            Some("completed") => Conclusion::of_check_run(value["conclusion"].as_str()),
            _ => Conclusion::Unfinished,
        };
        let steps = job["steps"]
            .as_array()
            .map(Vec::as_slice)
            .unwrap_or_default();
        Ok(JobRun {
            conclusion: conclusion(&job),
            steps: steps.iter().map(conclusion).collect(),
        })
    }

    /// Ask GitHub to re-run the failed jobs of the GitHub Actions workflow run
    /// `workflow_run`, as a new attempt of it.
    pub fn rerun_failed_jobs(&self, issue: &IssueUrl, workflow_run: u64) -> Result<()> {
        self.gh(&[
            "run",
            "rerun",
            &workflow_run.to_string(),
            "--failed",
            "--repo",
            &issue.repo_slug(),
        ])
    }

    /// Run `gh <args>`, failing with its stderr if it exits non-zero.
    fn gh(&self, args: &[&str]) -> Result<()> {
        self.gh_stdout(args).map(drop)
    }

    /// Run `gh <args>` and return its trimmed stdout, failing with its stderr if
    /// it exits non-zero.
    fn gh_stdout(&self, args: &[&str]) -> Result<String> {
        let output = self.output(args)?;
        if !output.status.success() {
            bail!(CommandFailure::rejected(
                format!("gh {}", args.join(" ")),
                &output
            ));
        }
        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
    }

    /// Every item of the `field` list of the GitHub API's `path`, across all its
    /// pages.
    fn gh_api_items(&self, path: &str, field: &str) -> Result<Vec<Value>> {
        self.retry_read(&format!("gh api {path}"), || {
            self.gh_api_items_once(path, field)
        })
    }

    fn gh_api_items_once(&self, path: &str, field: &str) -> Result<Vec<Value>> {
        let output = self.output(&["api", "--paginate", "--jq", &format!(".{field}[]"), path])?;
        if !output.status.success() {
            bail!(check_read::ReadFailure {
                command: format!("gh api {path}"),
                stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
                private_status: None,
            });
        }
        serde_json::Deserializer::from_slice(&output.stdout)
            .into_iter()
            .collect::<Result<_, _>>()
            .with_context(|| CommandFailure::InvalidJson {
                command: format!("gh api {path}"),
            })
    }

    /// Read-only JSON commands get three attempts, separated by one then two
    /// seconds, for transient failures only. Mutations use `gh_stdout` or
    /// `output_with_input` instead.
    fn gh_json(&self, args: &[&str]) -> Result<Value> {
        let command = format!("gh {}", args[..2].join(" "));
        self.retry_read(&command, || self.gh_json_once(args, &command))
    }

    fn retry_read<T>(&self, command: &str, mut read: impl FnMut() -> Result<T>) -> Result<T> {
        for attempt in 1..=3 {
            let error = match read() {
                Ok(value) => return Ok(value),
                Err(error) => error,
            };
            if attempt == 3 || !check_read::is_transient(&error) {
                return Err(error);
            }
            crate::progress::step(format!(
                "{command} failed (attempt {attempt}/3): {error:#}; retrying in {attempt}s"
            ));
            self.interruption.pause(Duration::from_secs(attempt))?;
        }
        unreachable!("the third attempt returns success or the last cause")
    }

    fn gh_json_once(&self, args: &[&str], command: &str) -> Result<Value> {
        let output = self.output(args)?;
        if !output.status.success() {
            bail!(check_read::ReadFailure {
                command: command.to_string(),
                stderr: String::from_utf8_lossy(&output.stderr).trim().to_string(),
                private_status: None,
            });
        }
        serde_json::from_slice(&output.stdout).with_context(|| CommandFailure::InvalidJson {
            command: command.to_string(),
        })
    }
    fn output(&self, args: &[&str]) -> Result<Output> {
        self.output_with_input(args, None)
    }

    fn output_with_input(&self, args: &[&str], input: Option<&[u8]>) -> Result<Output> {
        process::output(
            Command::new("gh").args(args),
            input,
            Control {
                name: "gh",
                interruption: self.interruption,
                stop: &|child| process::stop(child, &[libc::SIGTERM]),
            },
        )
        .map_err(|error| {
            self.interruption
                .check()
                .err()
                .unwrap_or_else(|| error.context(CommandFailure::Execution))
        })
    }
}

/// Whether the issue `json` describes, with its `state`, is open.
fn state_is_open(json: &Value) -> Result<bool> {
    Ok(json["state"]
        .as_str()
        .context(CommandFailure::InvalidResponse(
            "gh output has no state".into(),
        ))?
        == "OPEN")
}

/// An issue as an Architect run reads the issue its Architecture review
/// ended on, and as a Claim reads its issue after a Self-merge.
#[derive(Clone)]
pub struct Issue {
    pub title: Option<String>,
    pub is_open: bool,
    pub labels: Labels,
    pub created: DateTime<Utc>,
}

/// The labels of the issue `json` describes, with its `labels`.
fn labels_of(json: &Value) -> Result<Labels> {
    Ok(named(json["labels"].as_array().context(
        CommandFailure::InvalidResponse("gh output has no labels".into()),
    )?))
}

/// The labels `labels` describe, each with its `name`.
fn named(labels: &[Value]) -> Labels {
    labels
        .iter()
        .filter_map(|label| label["name"].as_str())
        .collect()
}

/// The REST API's path for the labels of `issue`.
fn labels_path(issue: &IssueUrl) -> String {
    format!("repos/{}/issues/{}/labels", issue.repo_slug(), issue.number)
}

/// The REST API's path for `label` on `issue`.
fn label_path(issue: &IssueUrl, label: &str) -> String {
    format!("{}/{label}", labels_path(issue))
}

/// The command that does what [`GitHub::remove_label`] does, to run by hand.
pub fn remove_label_command(issue: &IssueUrl, label: Label) -> String {
    format!("gh api --method DELETE {}", label_path(issue, label.name()))
}

/// The command that adds `label` to `issue`, keeping its other labels, to
/// run by hand: unlike [`GitHub::set_labels`], it needs none of the others named.
pub fn add_label_command(issue: &IssueUrl, label: Label) -> String {
    format!(
        "gh api --method POST {} -f 'labels[]={label}'",
        labels_path(issue)
    )
}

/// A Spec's sub-issue, as a Spec run reads it.
#[derive(Clone)]
pub struct Ticket {
    pub issue: IssueUrl,
    pub is_open: bool,
    pub labels: Labels,
    /// It has sub-issues of its own.
    pub has_sub_issues: bool,
    /// The issues it is blocked by, in the Spec or not.
    pub blockers: Vec<IssueUrl>,
    /// Those blockers that are open.
    pub open_blockers: Vec<IssueUrl>,
}

/// Every sub-issue of `issue`, open or closed, with its labels, whether it
/// has sub-issues of its own and the issues it is blocked by: its GitHub
/// "blocked by" links, never the text of its body.
const TICKETS_QUERY: &str = "\
query($owner: String!, $repo: String!, $number: Int!) {
  repository(owner: $owner, name: $repo) {
    issue(number: $number) {
      subIssues(first: 100) {
        nodes {
          url
          state
          labels(first: 100) { nodes { name } }
          subIssues { totalCount }
          blockedBy(first: 100) { nodes { url state } }
        }
      }
    }
  }
}";

/// The `nodes` of `connection`, the `what` of a GraphQL answer.
fn nodes<'a>(connection: &'a Value, what: &str) -> Result<&'a Vec<Value>> {
    connection["nodes"].as_array().with_context(|| {
        CommandFailure::InvalidResponse(format!("gh api graphql output has no {what}"))
    })
}

/// Whether the issue a GraphQL answer's `node` describes is open.
fn node_is_open(node: &Value) -> Result<bool> {
    Ok(node["state"]
        .as_str()
        .context(CommandFailure::InvalidResponse(
            "gh api graphql output has an issue with no state".into(),
        ))?
        == "OPEN")
}

/// The full Issue URL GitHub returned for a Ticket or blocker.
fn node_issue(node: &Value) -> Result<IssueUrl> {
    IssueUrl::parse(
        node["url"]
            .as_str()
            .context(CommandFailure::InvalidResponse(
                "gh api graphql output has an issue with no URL".into(),
            ))?,
    )
    .context(CommandFailure::InvalidResponse(
        "gh api graphql output has an invalid issue URL".into(),
    ))
}

/// The number of the issue a GraphQL answer's `node` describes.
fn node_number(node: &Value) -> Result<u64> {
    node["number"]
        .as_u64()
        .context(CommandFailure::InvalidResponse(
            "gh api graphql output has an issue with no number".into(),
        ))
}

/// How many sub-issues the issue a GraphQL answer's `node` describes has.
fn sub_issue_count(node: &Value) -> Result<u64> {
    node["subIssues"]["totalCount"]
        .as_u64()
        .context(CommandFailure::InvalidResponse(
            "gh api graphql output has an issue with no subIssues count".into(),
        ))
}

/// An issue as a listing of its repository's issues gives it.
#[derive(Debug, Clone)]
pub struct ListedIssue {
    pub issue: IssueUrl,
    pub title: String,
    pub labels: Labels,
}

/// An open issue labelled for a Pickup run to take, as the Pickup run reads
/// what its listing doesn't give.
pub struct Candidate {
    /// The issue it is a sub-issue of, if it is one.
    pub parent: Option<IssueUrl>,
    /// For each of its sub-issues, whether that one is open.
    pub sub_issue_is_open: Vec<bool>,
    /// The numbers of the open issues it is blocked by.
    pub open_blockers: Vec<u64>,
    /// The latest of the changes that shape it, if its timeline has one.
    pub last_shaped: Option<Shaped>,
    /// Complete label history records the last Claim ending, followed by a
    /// ready-label application, with neither withdrawn or superseded.
    pub handed_back: bool,
    /// Number of Claim applications in complete timeline order. Detects a
    /// Claim made since selection, even if it ended in the same second.
    pub claim_generation: usize,
    /// A Claim is active at the history sample, even if a prior issue listing
    /// still showed only `ready-for-agent`.
    pub claimed: bool,
}

impl Candidate {
    /// It has sub-issues of its own.
    pub fn has_sub_issues(&self) -> bool {
        !self.sub_issue_is_open.is_empty()
    }
}

/// The last Claim and whether the Day shift subsequently handed it back.
/// Timeline order, rather than timestamp comparisons, also distinguishes
/// consecutive GitHub label operations made within the same second.
enum ClaimHistory {
    NeverClaimed,
    Claimed,
    Released,
    HandedBack,
}

impl ClaimHistory {
    fn after(self, name: Option<&str>, applied: bool, ready: Label) -> Self {
        if name.is_some_and(|name| crate::claim::IN_PROGRESS.is_named(name)) {
            return match (self, applied) {
                (_, true) => Self::Claimed,
                (Self::Claimed, false) => Self::Released,
                (state, false) => state,
            };
        }
        if name.is_some_and(|name| ready.is_named(name)) {
            return match (self, applied) {
                (Self::Released | Self::HandedBack, true) => Self::HandedBack,
                (Self::HandedBack, false) => Self::Released,
                (state, _) => state,
            };
        }
        self
    }
}

/// A change that shapes an issue, and when it was made.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Shaped {
    pub by: Shaping,
    pub at: DateTime<Utc>,
}

/// What shapes an issue for a Pickup run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Shaping {
    /// The label a Pickup run lists issues by was applied.
    Labelled,
    /// A sub-issue was added or removed.
    SubIssues,
    /// A "blocked by" link was added or removed.
    Blockers,
}

/// An issue's parent, the state of each of its sub-issues, the issues it is
/// blocked by, and the events of its timeline that shape it: each time a
/// label was applied or removed (paginated to completion), and the last
/// sub-issue or "blocked by" link added or removed. They are read from the
/// timeline because adding a sub-issue does not change the issue's update
/// time. The sub-issues read are the first hundred, the ones
/// [`TICKETS_QUERY`] reads, so a Pickup run and a Spec run see the same
/// Tickets.
const CANDIDATE_QUERY: &str = "\
query($owner: String!, $repo: String!, $number: Int!, $after: String) {
  repository(owner: $owner, name: $repo) {
    issue(number: $number) {
      parent { url }
      subIssues(first: 100) { nodes { state } }
      blockedBy(first: 100) { nodes { number state } }
      labelled: timelineItems(first: 100, after: $after, itemTypes: [LABELED_EVENT, UNLABELED_EVENT]) {
        pageInfo { hasNextPage endCursor }
        nodes {
          __typename
          ... on LabeledEvent { createdAt label { name } }
          ... on UnlabeledEvent { createdAt label { name } }
        }
      }
      linked: timelineItems(
        last: 1
        itemTypes: [
          SUB_ISSUE_ADDED_EVENT
          SUB_ISSUE_REMOVED_EVENT
          BLOCKED_BY_ADDED_EVENT
          BLOCKED_BY_REMOVED_EVENT
        ]
      ) {
        nodes {
          __typename
          ... on SubIssueAddedEvent { createdAt }
          ... on SubIssueRemovedEvent { createdAt }
          ... on BlockedByAddedEvent { createdAt }
          ... on BlockedByRemovedEvent { createdAt }
        }
      }
    }
  }
}";

const PR_FIELDS: &str = "number,url,state,headRefName,baseRefName,isDraft";

const SNAPSHOT_FIELDS: &str =
    "number,url,state,headRefName,baseRefName,isDraft,mergeable,headRefOid,isCrossRepository";

/// The fields needed for one pull request observation, read together.
#[derive(Debug, Clone)]
pub struct PrSnapshot {
    pub pr: PullRequest,
    pub mergeable: Mergeable,
    pub head_commit: String,
    pub from_fork: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PrState {
    Open,
    Closed,
    Merged,
}

impl fmt::Display for PrState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(match self {
            PrState::Open => "open",
            PrState::Closed => "closed",
            PrState::Merged => "merged",
        })
    }
}

#[derive(Debug, Clone)]
pub struct PullRequest {
    pub number: u64,
    pub url: String,
    pub state: PrState,
    pub head: String,
    pub base: String,
    pub is_draft: bool,
}

impl PullRequest {
    pub fn is_open(&self) -> bool {
        self.state == PrState::Open
    }

    fn from_json(json: &Value) -> Result<Self> {
        let field = |name: &str| -> Result<String> {
            json[name].as_str().map(String::from).with_context(|| {
                CommandFailure::InvalidResponse(format!("gh output has no {name}"))
            })
        };
        let state = match field("state")?.as_str() {
            "OPEN" => PrState::Open,
            "CLOSED" => PrState::Closed,
            "MERGED" => PrState::Merged,
            other => bail!(CommandFailure::InvalidResponse(format!(
                "gh output has an unknown PR state {other}"
            ))),
        };
        Ok(PullRequest {
            number: json["number"]
                .as_u64()
                .context(CommandFailure::InvalidResponse(
                    "gh output has no number".into(),
                ))?,
            url: field("url")?,
            state,
            head: field("headRefName")?,
            base: field("baseRefName")?,
            is_draft: json["isDraft"]
                .as_bool()
                .context(CommandFailure::InvalidResponse(
                    "gh output has no isDraft".into(),
                ))?,
        })
    }
}

/// Whether a pull request can be merged into its base.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mergeable {
    Yes,
    /// It conflicts with its base.
    No,
    /// GitHub is still working it out.
    Unknown,
}

/// What GitHub said of a check run or commit status: a check run's
/// conclusion, or that it has not completed, or a commit status's state,
/// each named as GitHub names it. What each means for CI is CI watch's to
/// read.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Conclusion {
    /// A check run that has not completed.
    Unfinished,
    Success,
    Failure,
    Neutral,
    Skipped,
    Cancelled,
    TimedOut,
    ActionRequired,
    Stale,
    StartupFailure,
    /// A commit status still pending.
    Pending,
    /// A commit status in error.
    Error,
    /// A conclusion or state GitHub does not document, as GitHub wrote it:
    /// empty when a completed check run has none.
    Unrecognised(String),
}

impl Conclusion {
    /// The conclusion `conclusion` of a completed check run.
    fn of_check_run(conclusion: Option<&str>) -> Self {
        match conclusion {
            Some("success") => Self::Success,
            Some("failure") => Self::Failure,
            Some("neutral") => Self::Neutral,
            Some("skipped") => Self::Skipped,
            Some("cancelled") => Self::Cancelled,
            Some("timed_out") => Self::TimedOut,
            Some("action_required") => Self::ActionRequired,
            Some("stale") => Self::Stale,
            Some("startup_failure") => Self::StartupFailure,
            other => Self::Unrecognised(other.unwrap_or_default().to_string()),
        }
    }

    /// The state `state` of a commit status.
    fn of_commit_status(state: Option<&str>) -> Self {
        match state {
            Some("success") => Self::Success,
            Some("failure") => Self::Failure,
            Some("pending") => Self::Pending,
            Some("error") => Self::Error,
            other => Self::Unrecognised(other.unwrap_or_default().to_string()),
        }
    }
}

/// A check run or a commit status.
#[derive(Clone)]
pub struct Check {
    pub name: String,
    pub conclusion: Conclusion,
    pub url: Option<String>,
    /// The GitHub Actions job it is, if it is one. No other check can be
    /// re-run: not a commit status, nor a check run of another app.
    pub job: Option<ActionsJob>,
}

/// A job of a GitHub Actions workflow run, as one of its attempts ran it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ActionsJob {
    /// Its check run's id, which a new attempt of the job does not keep.
    pub check_run: u64,
    /// The workflow run it belongs to.
    pub workflow_run: u64,
    /// Whether it is an Abandoned job, which only the CI watch tells, and
    /// only of a job that failed: false until then.
    pub abandoned: bool,
}

/// A GitHub Actions job as the jobs API reports it, with no annotation or
/// log text: its conclusion and each of its steps', in order, a step not
/// completed being [`Conclusion::Unfinished`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct JobRun {
    pub conclusion: Conclusion,
    pub steps: Vec<Conclusion>,
}

impl ActionsJob {
    /// The job whose check run is `check_run`, if `details_url`, the check
    /// run's, is a job's page: `…/actions/runs/<workflow run>/job/<job>`.
    fn of(check_run: Option<u64>, details_url: Option<&str>) -> Option<Self> {
        let (_, after) = details_url?.split_once("/actions/runs/")?;
        let (workflow_run, _) = after.split_once("/job/")?;
        Some(ActionsJob {
            check_run: check_run?,
            workflow_run: workflow_run.parse().ok()?,
            abandoned: false,
        })
    }
}

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

    #[test]
    fn only_a_check_run_whose_details_are_a_jobs_page_is_an_actions_job() {
        let job = "https://github.com/acme/widgets/actions/runs/900/job/41";
        assert_eq!(
            ActionsJob::of(Some(41), Some(job)),
            Some(ActionsJob {
                check_run: 41,
                workflow_run: 900,
                abandoned: false,
            })
        );
        for not_a_job in [
            "https://ci.example/test",
            "https://github.com/acme/widgets/actions/runs/900",
            "https://github.com/acme/widgets/actions/runs/latest/job/41",
            "https://github.com/acme/widgets/runs/41",
        ] {
            assert_eq!(ActionsJob::of(Some(41), Some(not_a_job)), None);
        }
        assert_eq!(ActionsJob::of(Some(41), None), None);
        assert_eq!(ActionsJob::of(None, Some(job)), None);
    }
}