fallow-cli 2.81.0

CLI for fallow, Rust-native codebase intelligence for TypeScript and JavaScript
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
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use fallow_config::OutputFormat;
use serde_json::Value;

use crate::api::{ResponseBodyReader, sanitize_network_error, try_api_agent};
use crate::error::emit_error;

pub enum CiCommand {
    ReconcileReview {
        provider: CiProvider,
        target: Option<String>,
        envelope: PathBuf,
        repo: Option<String>,
        project_id: Option<String>,
        api_url: Option<String>,
        dry_run: bool,
    },
}

#[derive(Clone, Copy, Debug)]
pub enum CiProvider {
    Github,
    Gitlab,
}

pub fn run(command: CiCommand, output: OutputFormat) -> ExitCode {
    match command {
        CiCommand::ReconcileReview {
            provider,
            target,
            envelope,
            repo,
            project_id,
            api_url,
            dry_run,
        } => reconcile_review(
            provider,
            target.as_deref(),
            &envelope,
            ReconcileOptions {
                repo: repo.as_deref(),
                project_id: project_id.as_deref(),
                api_url: api_url.as_deref(),
                dry_run,
            },
            output,
        ),
    }
}

#[derive(Clone, Copy)]
struct ReconcileOptions<'a> {
    repo: Option<&'a str>,
    project_id: Option<&'a str>,
    api_url: Option<&'a str>,
    dry_run: bool,
}

fn reconcile_review(
    provider: CiProvider,
    target: Option<&str>,
    envelope: &Path,
    opts: ReconcileOptions<'_>,
    output: OutputFormat,
) -> ExitCode {
    let envelope = match read_envelope(envelope) {
        Ok(value) => value,
        Err(e) => {
            return emit_error(&e, 2, output);
        }
    };
    let current = envelope_fingerprints(&envelope);
    let state = match provider {
        CiProvider::Github => match load_github_state(target, opts) {
            Ok(state) => Some(state),
            Err(e) if opts.dry_run => {
                let plan = ReconcilePlan::without_provider(&current, e);
                return emit_reconcile_result(
                    provider,
                    target,
                    &envelope,
                    opts,
                    &plan,
                    &ApplyResult::default(),
                );
            }
            Err(e) => return emit_error(&e, crate::api::NETWORK_EXIT_CODE, output),
        },
        CiProvider::Gitlab => match load_gitlab_state(target, opts) {
            Ok(state) => Some(state),
            Err(e) if opts.dry_run => {
                let plan = ReconcilePlan::without_provider(&current, e);
                return emit_reconcile_result(
                    provider,
                    target,
                    &envelope,
                    opts,
                    &plan,
                    &ApplyResult::default(),
                );
            }
            Err(e) => return emit_error(&e, crate::api::NETWORK_EXIT_CODE, output),
        },
    };
    let Some(state) = state else {
        return emit_error(
            "internal error: provider state was not loaded for review reconciliation",
            2,
            output,
        );
    };
    let plan = PlannedReconcile::new(&current, &state);

    let applied = if opts.dry_run {
        ApplyResult::default()
    } else {
        match provider {
            CiProvider::Github => apply_github_reconcile(&plan, target, opts),
            CiProvider::Gitlab => apply_gitlab_reconcile(&plan, target, opts),
        }
    };

    emit_reconcile_result(provider, target, &envelope, opts, &plan.plan, &applied)
}

#[expect(
    clippy::cast_possible_truncation,
    reason = "comment / fingerprint counts on a single PR are bounded well below u32::MAX"
)]
fn emit_reconcile_result(
    provider: CiProvider,
    target: Option<&str>,
    envelope: &Value,
    opts: ReconcileOptions<'_>,
    plan: &ReconcilePlan,
    applied: &ApplyResult,
) -> ExitCode {
    let envelope_struct = crate::output_envelope::ReviewReconcileOutput {
        schema: crate::output_envelope::ReviewReconcileSchema::V1,
        provider: match provider {
            CiProvider::Github => crate::output_envelope::ReviewProvider::Github,
            CiProvider::Gitlab => crate::output_envelope::ReviewProvider::Gitlab,
        },
        target: target.map(str::to_owned),
        dry_run: opts.dry_run,
        comments: envelope_comments_len(envelope) as u32,
        current_fingerprints: plan.current.len() as u32,
        existing_fingerprints: plan.existing.len() as u32,
        new_fingerprints: plan.new.len() as u32,
        stale_fingerprints: plan.stale.len() as u32,
        new: plan.new.clone(),
        stale: plan.stale.clone(),
        provider_warning: plan.provider_warning.clone(),
        resolution_comments_posted: applied.resolution_comments_posted as u32,
        threads_resolved: applied.threads_resolved as u32,
        apply_hint: applied.hint(),
        apply_errors: applied.errors.clone(),
        failed_fingerprints: applied.failed_fingerprints.iter().cloned().collect(),
        unapplied_fingerprints: applied.unapplied_fingerprints.iter().cloned().collect(),
    };
    match serde_json::to_value(&envelope_struct) {
        Ok(value) => crate::report::emit_json(&value, "review reconcile"),
        Err(e) => emit_error(
            &format!("JSON serialization error: {e}"),
            2,
            fallow_config::OutputFormat::Json,
        ),
    }
}

fn read_envelope(path: &Path) -> Result<Value, String> {
    let data = std::fs::read_to_string(path)
        .map_err(|e| format!("failed to read review envelope '{}': {e}", path.display()))?;
    serde_json::from_str(&data)
        .map_err(|e| format!("failed to parse review envelope '{}': {e}", path.display()))
}

fn envelope_comments_len(value: &Value) -> usize {
    value
        .get("comments")
        .and_then(Value::as_array)
        .map_or(0, Vec::len)
}

fn envelope_fingerprints(value: &Value) -> BTreeSet<String> {
    value
        .get("comments")
        .and_then(Value::as_array)
        .into_iter()
        .flatten()
        .filter_map(|comment| comment.get("fingerprint").and_then(Value::as_str))
        .filter(|fingerprint| !fingerprint.trim().is_empty())
        .map(str::to_owned)
        .collect()
}

#[derive(Debug, Default)]
struct ProviderState {
    fingerprints: BTreeSet<String>,
    github_comments_by_fingerprint: BTreeMap<String, Vec<u64>>,
    github_threads_by_fingerprint: BTreeMap<String, Vec<String>>,
    github_resolved_markers: BTreeSet<String>,
    gitlab_discussions_by_fingerprint: BTreeMap<String, Vec<String>>,
    gitlab_resolved_markers: BTreeSet<String>,
}

#[derive(Debug, Default)]
struct ReconcilePlan {
    current: Vec<String>,
    existing: Vec<String>,
    new: Vec<String>,
    stale: Vec<String>,
    provider_warning: Option<String>,
}

impl ReconcilePlan {
    fn without_provider(current: &BTreeSet<String>, warning: String) -> Self {
        Self {
            current: current.iter().cloned().collect(),
            new: current.iter().cloned().collect(),
            provider_warning: Some(warning),
            ..Self::default()
        }
    }
}

fn reconcile_sets(current: &BTreeSet<String>, existing: &BTreeSet<String>) -> ReconcilePlan {
    ReconcilePlan {
        current: current.iter().cloned().collect(),
        existing: existing.iter().cloned().collect(),
        new: current.difference(existing).cloned().collect(),
        stale: existing.difference(current).cloned().collect(),
        provider_warning: None,
    }
}

#[derive(Debug)]
struct PlannedReconcile<'state> {
    plan: ReconcilePlan,
    state: &'state ProviderState,
}

impl<'state> PlannedReconcile<'state> {
    fn new(current: &BTreeSet<String>, state: &'state ProviderState) -> Self {
        Self {
            plan: reconcile_sets(current, &state.fingerprints),
            state,
        }
    }
}

#[derive(Debug, Default)]
struct ApplyResult {
    resolution_comments_posted: usize,
    threads_resolved: usize,
    errors: Vec<String>,
    failed_fingerprints: BTreeSet<String>,
    unapplied_fingerprints: BTreeSet<String>,
}

impl ApplyResult {
    fn hint(&self) -> Option<String> {
        (!self.errors.is_empty()).then(|| {
            "Reconcile apply stopped before all stale fingerprints were applied. Refresh provider state and rerun the job; fingerprints listed in unapplied_fingerprints were not fully applied.".to_owned()
        })
    }

    fn record_failure(
        &mut self,
        failure: ApplyFailure,
        unapplied: impl IntoIterator<Item = String>,
    ) {
        self.errors.push(failure.message);
        self.failed_fingerprints.insert(failure.fingerprint);
        self.unapplied_fingerprints.extend(unapplied);
    }
}

#[derive(Debug)]
struct ApplyFailure {
    fingerprint: String,
    message: String,
}

impl ApplyFailure {
    fn new(fingerprint: impl Into<String>, message: impl Into<String>) -> Self {
        Self {
            fingerprint: fingerprint.into(),
            message: message.into(),
        }
    }
}

fn load_github_state(
    target: Option<&str>,
    opts: ReconcileOptions<'_>,
) -> Result<ProviderState, String> {
    let pr = require_target("GitHub pull request", target)?;
    let repo = opts
        .repo
        .map(str::to_owned)
        .or_else(|| std::env::var("GH_REPO").ok())
        .or_else(|| std::env::var("GITHUB_REPOSITORY").ok())
        .ok_or_else(|| {
            "GitHub reconciliation requires --repo, GH_REPO, or GITHUB_REPOSITORY".to_owned()
        })?;
    let token = github_token()?;
    let api = opts
        .api_url
        .unwrap_or("https://api.github.com")
        .trim_end_matches('/');
    let agent = try_api_agent().map_err(|err| err.to_string())?;
    let mut state = ProviderState::default();

    for page in 1..=100 {
        let url = format!("{api}/repos/{repo}/pulls/{pr}/comments?per_page=100&page={page}");
        let value = github_get_json(&agent, &url, &token)?;
        let comments = value
            .as_array()
            .ok_or_else(|| "GitHub review comments response was not an array".to_owned())?;
        if comments.is_empty() {
            break;
        }
        for comment in comments {
            let body = comment.get("body").and_then(Value::as_str).unwrap_or("");
            if let Some(fingerprint) = extract_fallow_fingerprint(body) {
                state.fingerprints.insert(fingerprint.clone());
                if let Some(id) = comment.get("id").and_then(Value::as_u64) {
                    state
                        .github_comments_by_fingerprint
                        .entry(fingerprint)
                        .or_default()
                        .push(id);
                }
            }
            // Only honour resolved-fingerprint markers when the comment was
            // posted by a bot. A human commenter who pastes the marker into
            // their own comment could otherwise trick the apply step into
            // skipping a real "Resolved in `<sha>`" reply on a stale finding.
            if is_github_bot_comment(comment)
                && let Some(fingerprint) = extract_marker(body, "fallow-resolved-fingerprint:")
            {
                state.github_resolved_markers.insert(fingerprint);
            }
        }
        if comments.len() < 100 {
            break;
        }
    }

    load_github_review_threads(&mut state, &agent, &repo, pr, &token, api)?;
    Ok(state)
}

fn load_github_review_threads(
    state: &mut ProviderState,
    agent: &ureq::Agent,
    repo: &str,
    pr: &str,
    token: &str,
    api: &str,
) -> Result<(), String> {
    let (owner, name) = repo
        .split_once('/')
        .ok_or_else(|| format!("GitHub repo must be owner/name, got '{repo}'"))?;
    let number = pr
        .parse::<u64>()
        .map_err(|_| format!("GitHub PR must be numeric, got '{pr}'"))?;
    let mut cursor: Option<String> = None;
    for _ in 0..100 {
        let query = r"
query($owner:String!, $name:String!, $number:Int!, $cursor:String) {
  repository(owner:$owner, name:$name) {
    pullRequest(number:$number) {
      reviewThreads(first:100, after:$cursor) {
        nodes {
          id
          isResolved
          comments(first:50) {
            nodes { body }
          }
        }
        pageInfo { hasNextPage endCursor }
      }
    }
  }
}";
        let payload = serde_json::json!({
            "query": query,
            "variables": {
                "owner": owner,
                "name": name,
                "number": number,
                "cursor": cursor,
            }
        });
        let value = github_post_json(agent, &format!("{api}/graphql"), token, &payload)?;
        if value.get("errors").is_some() {
            return Err(format!(
                "GitHub GraphQL reviewThreads query failed: {value}"
            ));
        }
        let threads = value
            .pointer("/data/repository/pullRequest/reviewThreads/nodes")
            .and_then(Value::as_array)
            .ok_or_else(|| "GitHub reviewThreads response did not contain nodes".to_owned())?;
        for thread in threads {
            if thread
                .get("isResolved")
                .and_then(Value::as_bool)
                .unwrap_or(false)
            {
                continue;
            }
            let Some(thread_id) = thread.get("id").and_then(Value::as_str) else {
                continue;
            };
            let comments = thread
                .pointer("/comments/nodes")
                .and_then(Value::as_array)
                .into_iter()
                .flatten();
            for comment in comments {
                let body = comment.get("body").and_then(Value::as_str).unwrap_or("");
                if let Some(fingerprint) = extract_fallow_fingerprint(body) {
                    state.fingerprints.insert(fingerprint.clone());
                    state
                        .github_threads_by_fingerprint
                        .entry(fingerprint)
                        .or_default()
                        .push(thread_id.to_owned());
                }
            }
        }
        let page_info = value
            .pointer("/data/repository/pullRequest/reviewThreads/pageInfo")
            .unwrap_or(&Value::Null);
        if !page_info
            .get("hasNextPage")
            .and_then(Value::as_bool)
            .unwrap_or(false)
        {
            break;
        }
        cursor = page_info
            .get("endCursor")
            .and_then(Value::as_str)
            .map(str::to_owned);
    }
    Ok(())
}

fn apply_github_reconcile(
    plan: &PlannedReconcile<'_>,
    target: Option<&str>,
    opts: ReconcileOptions<'_>,
) -> ApplyResult {
    let mut result = ApplyResult::default();
    let pr = target.unwrap_or_default();
    let repo = opts
        .repo
        .map(str::to_owned)
        .or_else(|| std::env::var("GH_REPO").ok())
        .or_else(|| std::env::var("GITHUB_REPOSITORY").ok())
        .unwrap_or_default();
    let token = match github_token() {
        Ok(token) => token,
        Err(e) => {
            result.errors.push(e);
            return result;
        }
    };
    let api = opts
        .api_url
        .unwrap_or("https://api.github.com")
        .trim_end_matches('/');
    let agent = match try_api_agent() {
        Ok(agent) => agent,
        Err(err) => {
            result.errors.push(err.to_string());
            return result;
        }
    };
    let sha = std::env::var("GITHUB_SHA")
        .ok()
        .or_else(|| std::env::var("PR_HEAD_SHA").ok());
    let operations = stage_github_operations(plan, sha.as_deref());

    if let Err(failure) = preflight_github_operations(&operations, &agent, &repo, &token, api) {
        result.record_failure(
            failure,
            operations
                .iter()
                .map(GithubApplyOperation::fingerprint_owned),
        );
        return result;
    }

    for (index, operation) in operations.iter().enumerate() {
        if let Err(failure) =
            apply_github_operation(operation, &agent, &repo, pr, &token, api, &mut result)
        {
            result.record_failure(
                failure,
                operations[index..]
                    .iter()
                    .map(GithubApplyOperation::fingerprint_owned),
            );
            return result;
        }
    }
    result
}

#[derive(Debug)]
enum GithubApplyOperation {
    Reply {
        fingerprint: String,
        comment_id: u64,
        body: String,
    },
    ResolveThread {
        fingerprint: String,
        thread_id: String,
    },
}

impl GithubApplyOperation {
    fn fingerprint(&self) -> &str {
        match self {
            Self::Reply { fingerprint, .. } | Self::ResolveThread { fingerprint, .. } => {
                fingerprint
            }
        }
    }

    fn fingerprint_owned(&self) -> String {
        self.fingerprint().to_owned()
    }
}

fn stage_github_operations(
    plan: &PlannedReconcile<'_>,
    sha: Option<&str>,
) -> Vec<GithubApplyOperation> {
    let mut operations = Vec::new();
    for fingerprint in &plan.plan.stale {
        // Idempotency: check the (fingerprint, sha) marker, not the bare
        // fingerprint. Re-runs on the same commit must not post duplicate
        // "Resolved in `<sha>`" replies; legacy markers without a SHA suffix
        // still match on bare fingerprint to keep first-run-after-upgrade
        // clean.
        let marker_key = resolved_marker_key(fingerprint, sha);
        let already_resolved = plan.state.github_resolved_markers.contains(&marker_key)
            || plan.state.github_resolved_markers.contains(fingerprint);
        if !already_resolved {
            for comment_id in plan
                .state
                .github_comments_by_fingerprint
                .get(fingerprint)
                .into_iter()
                .flatten()
            {
                let body = resolved_body(fingerprint, sha);
                operations.push(GithubApplyOperation::Reply {
                    fingerprint: fingerprint.clone(),
                    comment_id: *comment_id,
                    body,
                });
            }
        }
        for thread_id in plan
            .state
            .github_threads_by_fingerprint
            .get(fingerprint)
            .into_iter()
            .flatten()
        {
            operations.push(GithubApplyOperation::ResolveThread {
                fingerprint: fingerprint.clone(),
                thread_id: thread_id.clone(),
            });
        }
    }
    operations
}

fn preflight_github_operations(
    operations: &[GithubApplyOperation],
    agent: &ureq::Agent,
    repo: &str,
    token: &str,
    api: &str,
) -> Result<(), ApplyFailure> {
    let mut comment_ids = BTreeMap::<u64, String>::new();
    let mut thread_ids = BTreeMap::<String, String>::new();
    for operation in operations {
        match operation {
            GithubApplyOperation::Reply {
                fingerprint,
                comment_id,
                ..
            } => {
                comment_ids
                    .entry(*comment_id)
                    .or_insert_with(|| fingerprint.clone());
            }
            GithubApplyOperation::ResolveThread {
                fingerprint,
                thread_id,
            } => {
                thread_ids
                    .entry(thread_id.clone())
                    .or_insert_with(|| fingerprint.clone());
            }
        }
    }

    for (comment_id, fingerprint) in comment_ids {
        let url = format!("{api}/repos/{repo}/pulls/comments/{comment_id}");
        github_get_json(agent, &url, token).map_err(|err| {
            ApplyFailure::new(
                fingerprint,
                format!("GitHub preflight failed for review comment {comment_id}: {err}"),
            )
        })?;
    }

    for (thread_id, fingerprint) in thread_ids {
        let payload = serde_json::json!({
            "query": "query($threadId:ID!){node(id:$threadId){... on PullRequestReviewThread{id isResolved}}}",
            "variables": { "threadId": thread_id },
        });
        let value =
            github_post_json(agent, &format!("{api}/graphql"), token, &payload).map_err(|err| {
                ApplyFailure::new(
                    fingerprint.clone(),
                    format!("GitHub preflight failed for review thread {thread_id}: {err}"),
                )
            })?;
        if value.get("errors").is_some() || value.pointer("/data/node/id").is_none() {
            return Err(ApplyFailure::new(
                fingerprint,
                format!("GitHub preflight failed for review thread {thread_id}: {value}"),
            ));
        }
    }

    Ok(())
}

fn apply_github_operation(
    operation: &GithubApplyOperation,
    agent: &ureq::Agent,
    repo: &str,
    pr: &str,
    token: &str,
    api: &str,
    result: &mut ApplyResult,
) -> Result<(), ApplyFailure> {
    match operation {
        GithubApplyOperation::Reply {
            fingerprint,
            comment_id,
            body,
        } => {
            let payload = serde_json::json!({ "body": body });
            let url = format!("{api}/repos/{repo}/pulls/{pr}/comments/{comment_id}/replies");
            github_post_json(agent, &url, token, &payload).map_err(|err| {
                ApplyFailure::new(
                    fingerprint.clone(),
                    format!("GitHub failed to post resolution reply for {fingerprint}: {err}"),
                )
            })?;
            result.resolution_comments_posted += 1;
        }
        GithubApplyOperation::ResolveThread {
            fingerprint,
            thread_id,
        } => {
            let payload = serde_json::json!({
                "query": "mutation($threadId:ID!){resolveReviewThread(input:{threadId:$threadId}){thread{id isResolved}}}",
                "variables": { "threadId": thread_id },
            });
            let value = github_post_json(agent, &format!("{api}/graphql"), token, &payload)
                .map_err(|err| {
                    ApplyFailure::new(
                        fingerprint.clone(),
                        format!("GitHub failed to resolve review thread {thread_id}: {err}"),
                    )
                })?;
            if value.get("errors").is_some() {
                return Err(ApplyFailure::new(
                    fingerprint.clone(),
                    format!("GitHub resolveReviewThread failed for {fingerprint}: {value}"),
                ));
            }
            result.threads_resolved += 1;
        }
    }
    Ok(())
}

fn load_gitlab_state(
    target: Option<&str>,
    opts: ReconcileOptions<'_>,
) -> Result<ProviderState, String> {
    let mr = require_target("GitLab merge request", target)?;
    let project_id = opts
        .project_id
        .map(str::to_owned)
        .or_else(|| std::env::var("CI_PROJECT_ID").ok())
        .ok_or_else(|| "GitLab reconciliation requires --project-id or CI_PROJECT_ID".to_owned())?;
    let token = std::env::var("GITLAB_TOKEN")
        .map_err(|_| "GitLab reconciliation requires GITLAB_TOKEN".to_owned())?;
    let api = opts
        .api_url
        .map(str::to_owned)
        .or_else(|| std::env::var("CI_API_V4_URL").ok())
        .unwrap_or_else(|| "https://gitlab.com/api/v4".to_owned());
    let api = api.trim_end_matches('/').to_owned();
    let agent = try_api_agent().map_err(|err| err.to_string())?;
    let mut state = ProviderState::default();

    for page in 1..=100 {
        let url = format!(
            "{api}/projects/{}/merge_requests/{mr}/discussions?per_page=100&page={page}",
            url_encode_path_segment(&project_id)
        );
        let value = gitlab_get_json(&agent, &url, &token)?;
        let discussions = value
            .as_array()
            .ok_or_else(|| "GitLab discussions response was not an array".to_owned())?;
        if discussions.is_empty() {
            break;
        }
        for discussion in discussions {
            let Some(discussion_id) = discussion.get("id").and_then(Value::as_str) else {
                continue;
            };
            let notes = discussion
                .get("notes")
                .and_then(Value::as_array)
                .into_iter()
                .flatten();
            for note in notes {
                let body = note.get("body").and_then(Value::as_str).unwrap_or("");
                if let Some(fingerprint) = extract_fallow_fingerprint(body) {
                    state.fingerprints.insert(fingerprint.clone());
                    state
                        .gitlab_discussions_by_fingerprint
                        .entry(fingerprint)
                        .or_default()
                        .push(discussion_id.to_owned());
                }
                // Same authorship gate as GitHub: only honour resolved
                // markers from bot-authored notes so a human cannot suppress
                // legitimate "Resolved in `<sha>`" replies by impersonating the
                // marker in their own comment.
                if is_gitlab_bot_note(note)
                    && let Some(fingerprint) = extract_marker(body, "fallow-resolved-fingerprint:")
                {
                    state.gitlab_resolved_markers.insert(fingerprint);
                }
            }
        }
        if discussions.len() < 100 {
            break;
        }
    }
    Ok(state)
}

fn apply_gitlab_reconcile(
    plan: &PlannedReconcile<'_>,
    target: Option<&str>,
    opts: ReconcileOptions<'_>,
) -> ApplyResult {
    let mut result = ApplyResult::default();
    let mr = target.unwrap_or_default();
    let project_id = opts
        .project_id
        .map(str::to_owned)
        .or_else(|| std::env::var("CI_PROJECT_ID").ok())
        .unwrap_or_default();
    let Ok(token) = std::env::var("GITLAB_TOKEN") else {
        result
            .errors
            .push("GitLab reconciliation requires GITLAB_TOKEN".to_owned());
        return result;
    };
    let api = opts
        .api_url
        .map(str::to_owned)
        .or_else(|| std::env::var("CI_API_V4_URL").ok())
        .unwrap_or_else(|| "https://gitlab.com/api/v4".to_owned());
    let api = api.trim_end_matches('/').to_owned();
    let agent = match try_api_agent() {
        Ok(agent) => agent,
        Err(err) => {
            result.errors.push(err.to_string());
            return result;
        }
    };
    let sha = std::env::var("CI_COMMIT_SHA").ok();
    let encoded_project = url_encode_path_segment(&project_id);
    let operations = stage_gitlab_operations(plan, sha.as_deref());

    if let Err(failure) =
        preflight_gitlab_operations(&operations, &agent, &encoded_project, mr, &token, &api)
    {
        result.record_failure(
            failure,
            operations
                .iter()
                .map(GitlabApplyOperation::fingerprint_owned),
        );
        return result;
    }

    for (index, operation) in operations.iter().enumerate() {
        if let Err(failure) = apply_gitlab_operation(
            operation,
            &agent,
            &encoded_project,
            mr,
            &token,
            &api,
            &mut result,
        ) {
            result.record_failure(
                failure,
                operations[index..]
                    .iter()
                    .map(GitlabApplyOperation::fingerprint_owned),
            );
            return result;
        }
    }
    result
}

#[derive(Debug)]
enum GitlabApplyOperation {
    Note {
        fingerprint: String,
        discussion_id: String,
        body: String,
    },
    ResolveDiscussion {
        fingerprint: String,
        discussion_id: String,
    },
}

impl GitlabApplyOperation {
    fn fingerprint(&self) -> &str {
        match self {
            Self::Note { fingerprint, .. } | Self::ResolveDiscussion { fingerprint, .. } => {
                fingerprint
            }
        }
    }

    fn fingerprint_owned(&self) -> String {
        self.fingerprint().to_owned()
    }
}

fn stage_gitlab_operations(
    plan: &PlannedReconcile<'_>,
    sha: Option<&str>,
) -> Vec<GitlabApplyOperation> {
    let mut operations = Vec::new();
    for fingerprint in &plan.plan.stale {
        // Idempotency: same approach as GitHub apply. (fingerprint, sha)
        // marker, with bare-fingerprint legacy fallback.
        let marker_key = resolved_marker_key(fingerprint, sha);
        let already_resolved = plan.state.gitlab_resolved_markers.contains(&marker_key)
            || plan.state.gitlab_resolved_markers.contains(fingerprint);
        for discussion_id in plan
            .state
            .gitlab_discussions_by_fingerprint
            .get(fingerprint)
            .into_iter()
            .flatten()
        {
            if !already_resolved {
                let body = resolved_body(fingerprint, sha);
                operations.push(GitlabApplyOperation::Note {
                    fingerprint: fingerprint.clone(),
                    discussion_id: discussion_id.clone(),
                    body,
                });
            }
            operations.push(GitlabApplyOperation::ResolveDiscussion {
                fingerprint: fingerprint.clone(),
                discussion_id: discussion_id.clone(),
            });
        }
    }
    operations
}

fn preflight_gitlab_operations(
    operations: &[GitlabApplyOperation],
    agent: &ureq::Agent,
    encoded_project: &str,
    mr: &str,
    token: &str,
    api: &str,
) -> Result<(), ApplyFailure> {
    let mut discussion_ids = BTreeMap::<String, String>::new();
    for operation in operations {
        match operation {
            GitlabApplyOperation::Note {
                fingerprint,
                discussion_id,
                ..
            }
            | GitlabApplyOperation::ResolveDiscussion {
                fingerprint,
                discussion_id,
            } => {
                discussion_ids
                    .entry(discussion_id.clone())
                    .or_insert_with(|| fingerprint.clone());
            }
        }
    }
    for (discussion_id, fingerprint) in discussion_ids {
        let url = format!(
            "{api}/projects/{encoded_project}/merge_requests/{mr}/discussions/{discussion_id}"
        );
        gitlab_get_json(agent, &url, token).map_err(|err| {
            ApplyFailure::new(
                fingerprint,
                format!("GitLab preflight failed for discussion {discussion_id}: {err}"),
            )
        })?;
    }
    Ok(())
}

fn apply_gitlab_operation(
    operation: &GitlabApplyOperation,
    agent: &ureq::Agent,
    encoded_project: &str,
    mr: &str,
    token: &str,
    api: &str,
    result: &mut ApplyResult,
) -> Result<(), ApplyFailure> {
    match operation {
        GitlabApplyOperation::Note {
            fingerprint,
            discussion_id,
            body,
        } => {
            let payload = serde_json::json!({ "body": body });
            let url = format!(
                "{api}/projects/{encoded_project}/merge_requests/{mr}/discussions/{discussion_id}/notes"
            );
            gitlab_post_json(agent, &url, token, &payload).map_err(|err| {
                ApplyFailure::new(
                    fingerprint.clone(),
                    format!("GitLab failed to post resolution note for {fingerprint}: {err}"),
                )
            })?;
            result.resolution_comments_posted += 1;
        }
        GitlabApplyOperation::ResolveDiscussion {
            fingerprint,
            discussion_id,
        } => {
            let payload = serde_json::json!({ "resolved": true });
            let url = format!(
                "{api}/projects/{encoded_project}/merge_requests/{mr}/discussions/{discussion_id}"
            );
            gitlab_put_json(agent, &url, token, &payload).map_err(|err| {
                ApplyFailure::new(
                    fingerprint.clone(),
                    format!("GitLab failed to resolve discussion {discussion_id}: {err}"),
                )
            })?;
            result.threads_resolved += 1;
        }
    }
    Ok(())
}

fn require_target<'a>(label: &str, target: Option<&'a str>) -> Result<&'a str, String> {
    target
        .filter(|value| !value.trim().is_empty())
        .ok_or_else(|| format!("{label} id is required"))
}

fn github_token() -> Result<String, String> {
    std::env::var("GH_TOKEN")
        .or_else(|_| std::env::var("GITHUB_TOKEN"))
        .map_err(|_| "GitHub reconciliation requires GH_TOKEN or GITHUB_TOKEN".to_owned())
}

fn github_get_json(agent: &ureq::Agent, url: &str, token: &str) -> Result<Value, String> {
    with_rate_limit_retry("GitHub", || {
        agent
            .get(url)
            .header("Authorization", &format!("Bearer {token}"))
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", "2022-11-28")
            .header("User-Agent", "fallow-cli")
            .call()
    })
}

fn github_post_json(
    agent: &ureq::Agent,
    url: &str,
    token: &str,
    payload: &Value,
) -> Result<Value, String> {
    with_rate_limit_retry("GitHub", || {
        agent
            .post(url)
            .header("Authorization", &format!("Bearer {token}"))
            .header("Accept", "application/vnd.github+json")
            .header("X-GitHub-Api-Version", "2022-11-28")
            .header("User-Agent", "fallow-cli")
            .send_json(payload)
    })
}

fn gitlab_get_json(agent: &ureq::Agent, url: &str, token: &str) -> Result<Value, String> {
    with_rate_limit_retry("GitLab", || {
        agent
            .get(url)
            .header("PRIVATE-TOKEN", token)
            .header("User-Agent", "fallow-cli")
            .call()
    })
}

fn gitlab_post_json(
    agent: &ureq::Agent,
    url: &str,
    token: &str,
    payload: &Value,
) -> Result<Value, String> {
    with_rate_limit_retry("GitLab", || {
        agent
            .post(url)
            .header("PRIVATE-TOKEN", token)
            .header("Content-Type", "application/json")
            .header("User-Agent", "fallow-cli")
            .send_json(payload)
    })
}

fn gitlab_put_json(
    agent: &ureq::Agent,
    url: &str,
    token: &str,
    payload: &Value,
) -> Result<Value, String> {
    with_rate_limit_retry("GitLab", || {
        agent
            .put(url)
            .header("PRIVATE-TOKEN", token)
            .header("Content-Type", "application/json")
            .header("User-Agent", "fallow-cli")
            .send_json(payload)
    })
}

/// Maximum per-attempt sleep, even when the server's `Retry-After` is larger.
///
/// A misbehaving server (or a malicious upstream proxy) sending
/// `Retry-After: 86400` would otherwise stall the runner for a whole day.
/// 60s is enough headroom for genuine GitHub / GitLab rate-limit recovery
/// while bounding worst-case workflow latency at `RETRY_MAX_WAIT_SECONDS *
/// FALLOW_API_RETRIES = 180s` for the default retry count.
const RETRY_MAX_WAIT_SECONDS: u64 = 60;

/// Return `true` for HTTP statuses worth retrying (rate-limit + transient
/// 5xx). Persistent server faults (`500`, `501`) and all 4xx other than `429`
/// surface immediately so a real bug doesn't burn the full retry budget.
const fn should_retry_status(status: u16) -> bool {
    status == 429 || matches!(status, 502..=504)
}

/// Wrap an HTTP request closure with rate-limit + transient-5xx retry.
///
/// Mirrors the bash `gh_api_retry` / `curl_retry` helpers in the action and
/// CI scripts so the binary is no less robust than the bash glue around it
/// when a workflow re-runs against a rate-limited GitHub Enterprise or a
/// GitLab instance under load. Retries on `429 Too Many Requests` and on
/// `502/503/504` (Bad Gateway, Service Unavailable, Gateway Timeout); other
/// 5xx codes (`500`, `501`, ...) surface immediately so persistent server
/// faults don't burn the full retry budget.
///
/// `FALLOW_API_RETRIES` (default 3) caps the total attempts; `FALLOW_API_RETRY_DELAY`
/// (default 2s) is the floor between attempts. The actual sleep uses
/// `Retry-After` from the server when present, falling back to the floor;
/// either way it's clamped to `RETRY_MAX_WAIT_SECONDS` so a runaway server
/// can't strand the runner.
fn with_rate_limit_retry<F>(provider: &str, mut op: F) -> Result<Value, String>
where
    F: FnMut() -> Result<http::Response<ureq::Body>, ureq::Error>,
{
    let max_attempts = retries_from_env();
    let floor_delay = retry_delay_from_env();
    let mut attempt: u32 = 0;
    loop {
        attempt += 1;
        match op() {
            Ok(mut response) => {
                let status = response.status().as_u16();
                if should_retry_status(status) && attempt < max_attempts {
                    let wait = compute_retry_wait(response.headers(), floor_delay, provider);
                    let label = if status == 429 {
                        "rate-limited"
                    } else {
                        "transient server error"
                    };
                    eprintln!(
                        "fallow: {provider} {label} ({status}); retrying in {wait}s ({attempt}/{max_attempts})"
                    );
                    std::thread::sleep(std::time::Duration::from_secs(wait));
                    continue;
                }
                return read_json_response(&mut response, provider);
            }
            Err(e) => {
                return Err(sanitize_network_error(&format!(
                    "{provider} request failed: {e}"
                )));
            }
        }
    }
}

/// Pick a sleep duration for a 429 retry attempt.
///
/// Precedence (highest first):
/// 1. `Retry-After` integer-seconds, clamped to `[1, RETRY_MAX_WAIT_SECONDS]`.
/// 2. `Retry-After` HTTP-date: not parsed; emit a one-time warning and fall
///    back to the floor delay so the user knows their server's Retry-After
///    contract was ignored.
/// 3. `floor_delay` from `FALLOW_API_RETRY_DELAY`, clamped to the ceiling.
fn compute_retry_wait(headers: &http::HeaderMap, floor_delay: u64, provider: &str) -> u64 {
    if let Some(seconds) = parse_retry_after(headers) {
        return seconds.clamp(1, RETRY_MAX_WAIT_SECONDS);
    }
    if let Some(raw) = headers
        .get("Retry-After")
        .and_then(|value| value.to_str().ok())
    {
        eprintln!(
            "fallow: {provider} returned non-numeric Retry-After {raw:?}; \
             falling back to {floor_delay}s floor"
        );
    }
    floor_delay.clamp(1, RETRY_MAX_WAIT_SECONDS)
}

fn retries_from_env() -> u32 {
    std::env::var("FALLOW_API_RETRIES")
        .ok()
        .and_then(|value| value.parse::<u32>().ok())
        .filter(|value| *value > 0)
        .unwrap_or(3)
}

fn retry_delay_from_env() -> u64 {
    std::env::var("FALLOW_API_RETRY_DELAY")
        .ok()
        .and_then(|value| value.parse::<u64>().ok())
        .unwrap_or(2)
}

fn parse_retry_after(headers: &http::HeaderMap) -> Option<u64> {
    let header = headers.get("Retry-After")?;
    let raw = header.to_str().ok()?.trim();
    raw.parse::<u64>().ok()
}

fn read_json_response(
    response: &mut impl ResponseBodyReader,
    provider: &str,
) -> Result<Value, String> {
    if !(200..300).contains(&response.status()) {
        let status = response.status();
        let body = response.read_to_string().unwrap_or_default();
        return Err(format!(
            "{provider} request failed with HTTP {status}: {}",
            body.trim()
        ));
    }
    response
        .read_json::<Value>()
        .map_err(|e| format!("{provider} response was not valid JSON: {e}"))
}

/// Determine whether a GitHub PR review comment was authored by a bot account.
///
/// We trust resolved-fingerprint markers only from bot identities so a human
/// commenter can't paste `<!-- fallow-resolved-fingerprint: <fp> -->` into
/// their own comment and trick the apply step into skipping a legitimate
/// "Resolved in `<sha>`" reply on a stale finding.
///
/// GitHub identifies bot identities through `user.type == "Bot"` (e.g.
/// `github-actions[bot]`, `dependabot[bot]`, custom GitHub Apps). The
/// fallback `FALLOW_BOT_LOGIN` env var lets self-hosted runners pin a
/// specific human-account login that posts on behalf of fallow when no Bot
/// type is available (uncommon but supported for legacy setups).
fn is_github_bot_comment(comment: &Value) -> bool {
    let user = comment.get("user");
    let user_type = user.and_then(|u| u.get("type")).and_then(Value::as_str);
    if user_type == Some("Bot") {
        return true;
    }
    let login = user.and_then(|u| u.get("login")).and_then(Value::as_str);
    if let Some(login) = login
        && let Ok(allow) = std::env::var("FALLOW_BOT_LOGIN")
        && !allow.trim().is_empty()
        && login == allow.trim()
    {
        return true;
    }
    false
}

/// Determine whether a GitLab MR discussion note was authored by a bot.
///
/// GitLab marks bot-authored notes with `system: true` (system-generated)
/// or, for project access tokens, the author's `bot: true` flag. Personal
/// access tokens posting on behalf of a human carry the human's identity;
/// callers that use a PAT must set `FALLOW_BOT_LOGIN` to the human's
/// username (or the project access token's bot username) to opt in.
fn is_gitlab_bot_note(note: &Value) -> bool {
    if note.get("system").and_then(Value::as_bool).unwrap_or(false) {
        return true;
    }
    let author = note.get("author");
    if author
        .and_then(|a| a.get("bot"))
        .and_then(Value::as_bool)
        .unwrap_or(false)
    {
        return true;
    }
    let username = author
        .and_then(|a| a.get("username"))
        .and_then(Value::as_str);
    if let Some(username) = username
        && let Ok(allow) = std::env::var("FALLOW_BOT_LOGIN")
        && !allow.trim().is_empty()
        && username == allow.trim()
    {
        return true;
    }
    false
}

fn extract_marker(body: &str, marker: &str) -> Option<String> {
    let rest = body.split(marker).nth(1)?.trim_start();
    let value = rest
        .split(|c: char| c.is_ascii_whitespace() || c == '<')
        .next()?
        .trim_matches('-')
        .trim();
    (!value.is_empty()).then(|| value.to_owned())
}

/// Extract a fallow fingerprint from any v1 or v2 marker shape in `body`.
/// v2 (`<!-- fallow-fingerprint:v2: <fp> -->`) wins over v1 because the v2
/// marker's text also matches the v1 substring search, so the v2-first
/// check has to run first or the v1 fallback would skip past `v2:` and
/// return the literal `"v2:"` as the extracted fingerprint.
///
/// Returns the raw fingerprint string with any kind prefix preserved
/// (`merged:<hex>` stays `merged:<hex>`). Consumers match the returned
/// string against the comment's `fingerprint` field verbatim.
fn extract_fallow_fingerprint(body: &str) -> Option<String> {
    extract_marker(body, "fallow-fingerprint:v2:")
        .or_else(|| extract_marker(body, "fallow-fingerprint:"))
}

/// Compute the idempotency marker for a (fingerprint, sha) pair. The marker
/// is what we look up to decide whether a resolution comment for this
/// fingerprint at this commit already exists, so re-runs of the workflow on
/// the same commit don't post duplicate "Resolved in `<sha>`" comments.
fn resolved_marker_key(fingerprint: &str, sha: Option<&str>) -> String {
    match sha.and_then(|value| value.get(..7)) {
        Some(short) => format!("{fingerprint}@{short}"),
        None => fingerprint.to_owned(),
    }
}

fn resolved_body(fingerprint: &str, sha: Option<&str>) -> String {
    let marker = resolved_marker_key(fingerprint, sha);
    match sha.and_then(|value| value.get(..7)) {
        Some(short) => {
            format!("Resolved in `{short}`.\n\n<!-- fallow-resolved-fingerprint: {marker} -->")
        }
        None => format!("Resolved.\n\n<!-- fallow-resolved-fingerprint: {marker} -->"),
    }
}

fn url_encode_path_segment(value: &str) -> String {
    let mut out = String::new();
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(char::from(byte));
            }
            _ => {
                use std::fmt::Write as _;
                write!(&mut out, "%{byte:02X}").expect("write to string");
            }
        }
    }
    out
}

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

    #[test]
    fn extracts_fingerprint_marker() {
        assert_eq!(
            extract_marker(
                "**error**\n\n<!-- fallow-fingerprint: abc123 -->",
                "fallow-fingerprint:",
            )
            .as_deref(),
            Some("abc123")
        );
    }

    #[test]
    fn extracts_fingerprint_from_v2_marker() {
        // v2 marker shape introduced in issue #528.
        assert_eq!(
            extract_fallow_fingerprint(
                "**error**\n\n<!-- fallow-fingerprint:v2: abc1234567890def -->"
            )
            .as_deref(),
            Some("abc1234567890def")
        );
        // merged: shape on hashed-composite merged comments.
        assert_eq!(
            extract_fallow_fingerprint(
                "**error**\n\n<!-- fallow-fingerprint:v2: merged:0123456789abcdef -->"
            )
            .as_deref(),
            Some("merged:0123456789abcdef")
        );
    }

    #[test]
    fn extract_fallow_fingerprint_falls_back_to_v1_shape() {
        // v1 historical marker. Reconcile-review must still recognize it
        // during the migration window so consumers can re-process backlogs
        // posted by older fallow versions.
        assert_eq!(
            extract_fallow_fingerprint("**error**\n\n<!-- fallow-fingerprint: abc123 -->")
                .as_deref(),
            Some("abc123")
        );
    }

    #[test]
    fn extract_fallow_fingerprint_does_not_match_unrelated_body() {
        assert_eq!(extract_fallow_fingerprint("plain comment body"), None);
        // A body that contains the literal "fallow-fingerprint:v2:" but no
        // closing marker shape still returns the trimmed token, which is
        // intentional: extract_marker is forgiving by design and the
        // reconcile path treats any non-empty extraction as a potential
        // match (consumers cross-check against the typed `fingerprint`
        // field on their side to filter false positives). The dedicated
        // anti-spoofing layer is `marker_regex` running on the consumer
        // side, not this internal helper.
        assert_eq!(
            extract_fallow_fingerprint("fallow-fingerprint:v2: deadbeef").as_deref(),
            Some("deadbeef")
        );
    }

    #[test]
    fn computes_reconcile_sets() {
        let current = BTreeSet::from(["a".to_owned(), "b".to_owned()]);
        let existing = BTreeSet::from(["b".to_owned(), "c".to_owned()]);
        let plan = reconcile_sets(&current, &existing);
        assert_eq!(plan.new, vec!["a"]);
        assert_eq!(plan.stale, vec!["c"]);
    }

    #[test]
    fn encodes_gitlab_project_path_as_one_segment() {
        assert_eq!(url_encode_path_segment("group/project"), "group%2Fproject");
    }

    fn headers_with_retry_after(value: &'static str) -> http::HeaderMap {
        let mut map = http::HeaderMap::new();
        map.insert("Retry-After", http::HeaderValue::from_static(value));
        map
    }

    #[test]
    fn github_bot_check_accepts_bot_user_type() {
        let comment = serde_json::json!({
            "user": { "type": "Bot", "login": "github-actions[bot]" },
        });
        assert!(is_github_bot_comment(&comment));
    }

    #[test]
    fn github_bot_check_rejects_human_user_type() {
        // Critical security test: a human pasting a resolved-fingerprint
        // marker into their own comment must not be honoured.
        let comment = serde_json::json!({
            "user": { "type": "User", "login": "alice" },
            "body": "<!-- fallow-resolved-fingerprint: abc123 -->",
        });
        assert!(!is_github_bot_comment(&comment));
    }

    #[test]
    #[allow(unsafe_code, reason = "test-only env mutation, single-threaded run")]
    fn github_bot_check_accepts_explicit_login_override() {
        let comment = serde_json::json!({
            "user": { "type": "User", "login": "fallow-bot-account" },
        });
        // SAFETY: tests run sequentially within the bin target.
        unsafe {
            std::env::set_var("FALLOW_BOT_LOGIN", "fallow-bot-account");
        }
        assert!(is_github_bot_comment(&comment));
        // SAFETY: see above.
        unsafe {
            std::env::remove_var("FALLOW_BOT_LOGIN");
        }
    }

    #[test]
    fn gitlab_bot_check_accepts_system_and_bot_flag() {
        let system_note = serde_json::json!({ "system": true });
        assert!(is_gitlab_bot_note(&system_note));
        let bot_author = serde_json::json!({
            "system": false,
            "author": { "bot": true, "username": "project-bot" },
        });
        assert!(is_gitlab_bot_note(&bot_author));
    }

    #[test]
    fn gitlab_bot_check_rejects_human_author() {
        // Same security premise as GitHub.
        let human = serde_json::json!({
            "system": false,
            "author": { "bot": false, "username": "alice" },
        });
        assert!(!is_gitlab_bot_note(&human));
    }

    #[test]
    fn parse_retry_after_reads_integer_seconds() {
        assert_eq!(parse_retry_after(&headers_with_retry_after("12")), Some(12));
    }

    #[test]
    fn parse_retry_after_returns_none_for_missing_header() {
        assert_eq!(parse_retry_after(&http::HeaderMap::new()), None);
    }

    #[test]
    fn compute_retry_wait_clamps_huge_retry_after() {
        // A malicious or misconfigured server returning a day-long
        // Retry-After must NOT strand the runner.
        let headers = headers_with_retry_after("86400");
        assert_eq!(
            compute_retry_wait(&headers, 2, "GitHub"),
            RETRY_MAX_WAIT_SECONDS
        );
    }

    #[test]
    fn compute_retry_wait_clamps_zero_retry_after() {
        // A zero Retry-After (no wait) is a server bug; floor at 1s so we
        // don't tight-loop.
        let headers = headers_with_retry_after("0");
        assert_eq!(compute_retry_wait(&headers, 5, "GitLab"), 1);
    }

    #[test]
    fn compute_retry_wait_falls_back_to_floor_for_http_date() {
        // HTTP-date Retry-After values aren't parsed; we fall back to the
        // floor with a stderr warning (asserted via the public delay value).
        let headers = headers_with_retry_after("Wed, 21 Oct 2026 07:28:00 GMT");
        assert_eq!(compute_retry_wait(&headers, 7, "GitHub"), 7);
    }

    #[test]
    fn parse_retry_after_returns_none_for_http_date() {
        // Per RFC 9110 the header may carry an HTTP-date; we don't parse
        // those, the caller falls back to the floor delay.
        assert_eq!(
            parse_retry_after(&headers_with_retry_after("Wed, 21 Oct 2026 07:28:00 GMT")),
            None
        );
    }

    #[test]
    fn should_retry_status_covers_429_and_transient_5xx() {
        // 429 (rate-limit) and 502/503/504 (transient gateway errors) are the
        // statuses both bash gh_api_retry / curl_retry helpers and this
        // function retry on. Reverting the 5xx branch to 429-only would fail
        // the 502/503/504 assertions.
        assert!(should_retry_status(429));
        assert!(should_retry_status(502));
        assert!(should_retry_status(503));
        assert!(should_retry_status(504));
    }

    #[test]
    fn should_retry_status_skips_persistent_5xx_and_4xx() {
        // Persistent server faults (500, 501) and all 4xx other than 429
        // surface immediately so a real bug doesn't burn the full retry
        // budget on the runner.
        assert!(!should_retry_status(500));
        assert!(!should_retry_status(501));
        assert!(!should_retry_status(505));
        assert!(!should_retry_status(400));
        assert!(!should_retry_status(401));
        assert!(!should_retry_status(403));
        assert!(!should_retry_status(404));
        assert!(!should_retry_status(422));
        assert!(!should_retry_status(200));
    }

    #[test]
    fn resolved_marker_key_includes_short_sha() {
        // (fingerprint, sha) marker keeps re-runs idempotent on the same
        // commit while letting a force-push to a new SHA produce a fresh
        // resolution comment.
        assert_eq!(
            resolved_marker_key("abc", Some("1234567890")),
            "abc@1234567"
        );
        assert_eq!(resolved_marker_key("abc", None), "abc");
        assert_ne!(
            resolved_marker_key("abc", Some("1111111")),
            resolved_marker_key("abc", Some("2222222"))
        );
    }

    #[test]
    fn resolved_body_includes_short_sha_and_per_sha_marker() {
        let body = resolved_body("abc", Some("1234567890"));
        assert!(body.contains("`1234567`"));
        // Marker now encodes both fingerprint AND short SHA so re-runs on
        // the same commit can detect prior posts; force-push to new SHA
        // produces a new marker.
        assert!(body.contains("fallow-resolved-fingerprint: abc@1234567"));
    }
}