spar-cli 0.1.2

Two AI coding agents alternate implementing and reviewing GitHub issues until a PR converges.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
//! git and gh. Every outbound string passes through the style and concision
//! gates before it reaches GitHub.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde::Deserialize;
use serde_json::Value;

use crate::config::{Config, Followups, StateStore};
use crate::error::Result;
use crate::model::{Issue, IssueRef, ItemKind, PersistedState, PrRef, PrView};
use crate::proc::{self, ExecOpts};
use crate::style::{self, Style};
use crate::textsim;
use crate::{bail, logdim, spar_err};

/// gh returns newest first, so its `--limit` cannot be used to take the lowest
/// numbered items: it would slice the newest N and then sorting that slice
/// silently drops the older ones. Fetch a generous page, sort, then truncate.
pub const FETCH_CEILING: usize = 500;

/// An unclosed HTML comment on purpose. The payload is written after it and
/// terminated with `-->`, so GitHub renders the whole block as nothing.
pub const STATE_MARKER: &str = "<!-- spar:state";

const WORKTREE_DIR: &str = ".spar-worktrees";
const STATE_DIR: &str = ".spar";

#[derive(Debug)]
pub struct Repo {
    root: PathBuf,
    pub style: Style,
    pub branch_prefix: String,
    pub state_store: StateStore,
    pub followups: Followups,
}

impl Repo {
    pub fn open(root: impl AsRef<Path>, cfg: &Config) -> Result<Self> {
        let root =
            std::fs::canonicalize(root.as_ref()).unwrap_or_else(|_| root.as_ref().to_path_buf());
        // A linked worktree has a `.git` file rather than a directory, and a
        // bare-ish layout can have neither, so ask git instead of guessing.
        let inside = proc::run_str(
            &["git", "rev-parse", "--is-inside-work-tree"],
            &ExecOpts::new().cwd(&root).check(false).timeout_secs(30),
        )
        .unwrap_or_default();
        if inside.trim() != "true" {
            bail!("not a git repository: {}", root.display());
        }
        let repo = Self {
            root,
            style: cfg.style.clone(),
            branch_prefix: cfg.loop_cfg.branch_prefix.clone(),
            state_store: cfg.loop_cfg.state_store,
            followups: cfg.loop_cfg.followups,
        };
        repo.self_exclude();
        Ok(repo)
    }

    /// Keep spar's own scratch directories out of the target repo's
    /// `git status`.
    ///
    /// Written to `.git/info/exclude`, never to a tracked `.gitignore`: this is
    /// somebody else's repository and spar has no business committing to it.
    /// Best effort and silent on failure, because a read-only git directory is
    /// not a reason to abandon a run.
    fn self_exclude(&self) {
        let git_dir = self.git_try(&["rev-parse", "--path-format=absolute", "--git-common-dir"]);
        let git_dir = git_dir.trim();
        if git_dir.is_empty() {
            return;
        }
        let path = Path::new(git_dir).join("info").join("exclude");
        let existing = std::fs::read_to_string(&path).unwrap_or_default();

        let wanted = [format!("/{WORKTREE_DIR}/"), format!("/{STATE_DIR}/")];
        let missing: Vec<&String> = wanted
            .iter()
            .filter(|line| !existing.lines().any(|l| l.trim() == line.as_str()))
            .collect();
        if missing.is_empty() {
            return;
        }

        use std::io::Write;
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        let mut block = String::new();
        if !existing.is_empty() && !existing.ends_with('\n') {
            block.push('\n');
        }
        block.push_str("\n# added by spar: its worktrees and run state\n");
        for line in missing {
            block.push_str(line);
            block.push('\n');
        }
        if let Ok(mut file) = std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
        {
            let _ = file.write_all(block.as_bytes());
        }
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    // -- gates ------------------------------------------------------------

    /// Scrub, then verify. A leak here reaches GitHub, so it is a hard error
    /// rather than a warning: silent partial compliance is how a style rule
    /// erodes over a long run.
    pub fn clean(&self, text: &str) -> Result<String> {
        let out = style::scrub(text, &self.style);
        let bad = style::violations(&out, &self.style);
        if !bad.is_empty() {
            bail!(
                "style gate could not clean text ({}): {}",
                bad.join(", "),
                style::clip(&out, 300)
            );
        }
        Ok(out)
    }

    /// Clean, and hold to a length budget. For anything a model wrote.
    pub fn clean_body(&self, text: &str) -> Result<String> {
        self.clean(&style::body(text, &self.style))
    }

    /// The same, with an issue's far larger budget and its exemption for code.
    pub fn clean_issue_body(&self, text: &str) -> Result<String> {
        self.clean(&style::issue_body(text, &self.style))
    }

    /// The single transform every outbound title goes through.
    ///
    /// Scrub first, clip second, and never the other way round. Clipping first
    /// lets the scrub lengthen the result past the budget (an em dash becomes
    /// two characters), so a second pass would clip again and produce a
    /// different string. That broke follow-up deduplication silently: the
    /// lookup searched for one title while GitHub had stored another, no match
    /// was ever found, and a fresh duplicate issue was filed every review
    /// round. Doing it in this order makes the transform idempotent, which the
    /// tests assert.
    pub fn clean_title(&self, text: &str) -> Result<String> {
        Ok(style::title(&self.clean(text)?, &self.style))
    }

    // -- git --------------------------------------------------------------

    fn git_opts(&self, cwd: Option<&Path>, check: bool) -> ExecOpts {
        ExecOpts::new()
            .cwd(cwd.unwrap_or(&self.root))
            .check(check)
            .timeout_secs(600)
    }

    pub fn git(&self, args: &[&str]) -> Result<String> {
        self.git_at(None, args)
    }

    pub fn git_at(&self, cwd: Option<&Path>, args: &[&str]) -> Result<String> {
        let mut argv = vec!["git".to_string()];
        argv.extend(args.iter().map(|s| s.to_string()));
        proc::run(&argv, &self.git_opts(cwd, true))
    }

    /// Run git, tolerating failure. Returns whatever landed on stdout.
    pub fn git_try(&self, args: &[&str]) -> String {
        self.git_try_at(None, args)
    }

    pub fn git_try_at(&self, cwd: Option<&Path>, args: &[&str]) -> String {
        let mut argv = vec!["git".to_string()];
        argv.extend(args.iter().map(|s| s.to_string()));
        proc::run(&argv, &self.git_opts(cwd, false)).unwrap_or_default()
    }

    /// The base branch the remote actually points at, rather than assuming
    /// `main`. Falls back to the configured value when there is no origin.
    pub fn default_branch(&self, configured: &str) -> String {
        let refname = self.git_try(&["symbolic-ref", "refs/remotes/origin/HEAD"]);
        match refname.trim().rsplit('/').next() {
            Some(name) if !name.is_empty() => name.to_string(),
            _ => configured.to_string(),
        }
    }

    // -- branch naming and ownership --------------------------------------
    //
    // Branch names default to `issue-N`, which is exactly what a person would
    // name a branch by hand. Ownership therefore cannot be inferred from the
    // name, so every branch spar creates is recorded and cleanup only ever
    // touches what is in that record.

    pub fn branch_for_issue(&self, issue: i64) -> String {
        format!("{}issue-{issue}", self.branch_prefix)
    }

    pub fn branch_for_pr(&self, number: i64) -> String {
        format!("{}pr-{number}", self.branch_prefix)
    }

    fn ledger_path(&self) -> PathBuf {
        self.root.join(STATE_DIR).join("branches.json")
    }

    pub fn known_branches(&self) -> BTreeMap<String, BranchRecord> {
        std::fs::read_to_string(self.ledger_path())
            .ok()
            .and_then(|text| serde_json::from_str(&text).ok())
            .unwrap_or_default()
    }

    pub fn record_branch(&self, branch: &str, kind: &str, number: i64) {
        let mut data = self.known_branches();
        data.insert(
            branch.to_string(),
            BranchRecord {
                kind: kind.to_string(),
                number,
            },
        );
        if let Err(e) = write_json_atomic(&self.ledger_path(), &data) {
            logdim!("could not record branch {branch}: {e}");
        }
    }

    pub fn forget_branch(&self, branch: &str) {
        let mut data = self.known_branches();
        if data.remove(branch).is_none() {
            return;
        }
        if let Err(e) = write_json_atomic(&self.ledger_path(), &data) {
            logdim!("could not update the branch record: {e}");
        }
    }

    // -- worktrees --------------------------------------------------------

    fn worktree_path(&self, name: &str) -> PathBuf {
        self.root.join(WORKTREE_DIR).join(name)
    }

    /// Isolate an issue so a failed run cannot poison the next one's base.
    pub fn worktree_add(&self, issue: i64, base: &str) -> Result<(PathBuf, String)> {
        let branch = self.branch_for_issue(issue);
        let path = self.worktree_path(&format!("issue-{issue}"));

        self.git_try(&["fetch", "origin", base]);

        // Never rebuild a branch that already carries work.
        //
        // `run_issue` sends an issue with an open pull request to the resume
        // path, so reaching here with a remote branch ahead of the base means
        // commits were pushed that no open PR accounts for. Rebuilding would
        // force push over them, and the lease is no protection: the remote
        // tracking ref survives the local branch being deleted, so it still
        // matches and the push succeeds.
        self.git_try(&["fetch", "origin", &branch]);
        let remote_branch = format!("origin/{branch}");
        if self.rev_exists(&self.root, &remote_branch) {
            let range = format!("origin/{base}..{remote_branch}");
            let ahead: u32 = self
                .git_try(&["rev-list", "--count", &range])
                .trim()
                .parse()
                .unwrap_or(0);
            if ahead > 0 {
                bail!(
                    "origin/{branch} already has {ahead} commit(s) that are not on {base}, and no \
                     open pull request accounts for them. Rebuilding it would force push over \
                     that work.\nOpen a pull request for the branch and run `spar resume <pr>` to \
                     continue it, or delete it with `git push origin --delete {branch}` if it is \
                     stale."
                );
            }
        }

        self.worktree_remove(issue);
        self.git_try(&["branch", "-D", &branch]);

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| spar_err!("could not create {}: {e}", parent.display()))?;
        }

        let path_str = path.display().to_string();
        let remote_start = format!("origin/{base}");
        let created = self
            .git(&["worktree", "add", "-b", &branch, &path_str, &remote_start])
            .or_else(|_| self.git(&["worktree", "add", "-b", &branch, &path_str, base]));

        // Recorded on both paths: an unrecorded branch is one cleanup will
        // never remove, and the fallback creates a branch just the same.
        created.map_err(|e| {
            spar_err!(
                "could not create a worktree for issue #{issue}. {}\nIs `{base}` a real branch, \
                 and does `origin` exist?",
                e.last_line()
            )
        })?;
        self.record_branch(&branch, "issue", issue);
        Ok((path, branch))
    }

    pub fn worktree_remove(&self, issue: i64) {
        self.remove_worktree_at(&self.worktree_path(&format!("issue-{issue}")));
    }

    fn remove_worktree_at(&self, path: &Path) {
        let path_str = path.display().to_string();
        self.git_try(&["worktree", "remove", "--force", &path_str]);
        if path.is_dir() {
            let _ = std::fs::remove_dir_all(path);
        }
        self.git_try(&["worktree", "prune"]);
    }

    /// Check an existing PR branch out into an isolated worktree.
    pub fn worktree_for_pr(&self, pr: &PrView) -> Result<(PathBuf, String)> {
        let head = pr.head_ref_name.clone();
        if head.trim().is_empty() {
            bail!("PR #{} has no head branch to check out", pr.number);
        }
        let path = self.worktree_path(&format!("pr-{}", pr.number));
        let local = self.branch_for_pr(pr.number);

        self.git(&["fetch", "origin", &head]).map_err(|e| {
            spar_err!(
                "could not fetch the branch behind PR #{}: {}",
                pr.number,
                e.last_line()
            )
        })?;
        self.remove_worktree_at(&path);
        self.git_try(&["branch", "-D", &local]);

        let path_str = path.display().to_string();
        let start = format!("origin/{head}");
        self.git(&["worktree", "add", "-B", &local, &path_str, &start])?;
        self.record_branch(&local, "pr", pr.number);
        Ok((path, head))
    }

    /// Check a pull request's head out read only, detached, with no branch.
    ///
    /// Fetches `refs/pull/N/head`, which GitHub serves for every pull request
    /// including one from a fork whose branch is not in this repository at all.
    /// That is what makes reviewing an outside contribution possible when
    /// pushing to it is not.
    ///
    /// Detached on purpose. Review only mode has nothing to push, and a branch
    /// would only invite something to try.
    pub fn worktree_for_pr_head(&self, number: i64) -> Result<PathBuf> {
        let path = self.worktree_path(&format!("review-{number}"));
        let local_ref = review_ref(number);
        let refspec = format!("+refs/pull/{number}/head:{local_ref}");

        self.git(&["fetch", "origin", &refspec]).map_err(|e| {
            spar_err!(
                "could not fetch the head of PR #{number}. {}\nGitHub serves refs/pull/N/head for \
                 every pull request, so this usually means the number is wrong or `origin` does \
                 not point at the repository the PR is on.",
                e.last_line()
            )
        })?;

        if let Some(parent) = path.parent() {
            std::fs::create_dir_all(parent)
                .map_err(|e| spar_err!("could not create {}: {e}", parent.display()))?;
        }
        self.remove_worktree_at(&path);
        let path_str = path.display().to_string();
        self.git(&["worktree", "add", "--detach", &path_str, &local_ref])?;
        Ok(path)
    }

    pub fn release_review_worktree(&self, number: i64) {
        self.remove_worktree_at(&self.worktree_path(&format!("review-{number}")));
        self.git_try(&["update-ref", "-d", &review_ref(number)]);
    }

    pub fn release_pr_worktree(&self, number: i64) {
        let path = self.worktree_path(&format!("pr-{number}"));
        self.remove_worktree_at(&path);
        let local = self.branch_for_pr(number);
        self.git_try(&["branch", "-D", &local]);
        self.forget_branch(&local);
    }

    // -- branch state -----------------------------------------------------

    /// What to diff against: the remote tracking branch when it resolves, the
    /// local branch when it does not.
    ///
    /// This is not a nicety. Every "did the agent do anything" check hangs off
    /// this ref, and `git log` against a ref that does not exist fails silently
    /// and reads as "no commits". A checkout whose `origin/main` was never
    /// fetched would report every implementation as abandoned and throw the
    /// work away.
    pub fn base_ref(&self, cwd: &Path, base: &str) -> String {
        let remote = format!("origin/{base}");
        if self.rev_exists(cwd, &remote) {
            return remote;
        }
        if self.rev_exists(cwd, base) {
            logdim!("origin/{base} does not resolve, comparing against local {base}");
            return base.to_string();
        }
        logdim!("neither origin/{base} nor {base} resolves; results will be unreliable");
        remote
    }

    fn rev_exists(&self, cwd: &Path, refname: &str) -> bool {
        let spec = format!("{refname}^{{commit}}");
        !self
            .git_try_at(Some(cwd), &["rev-parse", "--verify", "--quiet", &spec])
            .trim()
            .is_empty()
    }

    pub fn has_changes(&self, cwd: &Path, base: &str) -> bool {
        let range = format!("{}..HEAD", self.base_ref(cwd, base));
        !self
            .git_try_at(Some(cwd), &["log", &range, "--oneline"])
            .trim()
            .is_empty()
    }

    pub fn diff_stat(&self, cwd: &Path, base: &str) -> String {
        let range = format!("{}...HEAD", self.base_ref(cwd, base));
        let full = self.git_try_at(Some(cwd), &["diff", &range, "--shortstat"]);
        full.trim().to_string()
    }

    /// Scrub commit messages that slipped past the prompt.
    ///
    /// `git filter-branch` calls back into this same binary, so there is no
    /// interpreter to find and no second copy of the rules to drift.
    pub fn rewrite_commits_if_needed(&self, cwd: &Path, base: &str) -> Result<()> {
        let range = format!("{}..HEAD", self.base_ref(cwd, base));
        let raw = self.git_try_at(Some(cwd), &["log", &range, "--format=%H%x00%B%x1e"]);

        let offenders = raw
            .split('\x1e')
            .filter_map(|entry| entry.split_once('\0'))
            .filter(|(_, body)| !style::violations(body, &self.style).is_empty())
            .count();
        if offenders == 0 {
            return Ok(());
        }
        logdim!("{offenders} commit message(s) violated style rules, rewriting");

        let exe = self_binary()?;
        let filter = format!("{} scrub-filter", sh_quote(&exe.display().to_string()));

        let argv: Vec<String> = [
            "git",
            "filter-branch",
            "-f",
            "--msg-filter",
            &filter,
            &range,
        ]
        .iter()
        .map(|s| s.to_string())
        .collect();
        let opts = ExecOpts::new()
            .cwd(cwd)
            .check(false)
            .timeout_secs(600)
            .env("FILTER_BRANCH_SQUELCH_WARNING", "1")
            .env("SPAR_BAN_EM_DASH", bool_env(self.style.ban_em_dash))
            .env(
                "SPAR_BAN_AI_ATTRIBUTION",
                bool_env(self.style.ban_ai_attribution),
            );
        let _ = proc::run(&argv, &opts);

        let after = self.git_try_at(Some(cwd), &["log", &range, "--format=%B"]);
        if !style::violations(&after, &self.style).is_empty() {
            bail!(
                "commit messages still violate style rules after a rewrite. Fix them by hand in \
                 {} and rerun.",
                cwd.display()
            );
        }
        Ok(())
    }

    /// Push by explicit refspec from HEAD.
    ///
    /// A resumed PR is checked out under a local name (`pr-N`) that does not
    /// match its remote branch, so pushing by branch name would resolve the
    /// wrong local ref or fail outright.
    pub fn push(&self, cwd: &Path, branch: &str) -> Result<()> {
        let refspec = format!("HEAD:{branch}");
        self.git_at(
            Some(cwd),
            &["push", "--force-with-lease", "origin", &refspec],
        )
        .map(|_| ())
        .map_err(|e| {
            spar_err!(
                "could not push to origin/{branch}. {}\nCheck push access and whether the \
                     branch moved under you.",
                e.last_line()
            )
        })
    }

    // -- gh ---------------------------------------------------------------

    pub fn gh(&self, args: &[&str]) -> Result<String> {
        self.gh_at(None, args)
    }

    pub fn gh_at(&self, cwd: Option<&Path>, args: &[&str]) -> Result<String> {
        let mut argv = vec!["gh".to_string()];
        argv.extend(args.iter().map(|s| s.to_string()));
        proc::run(
            &argv,
            &ExecOpts::new()
                .cwd(cwd.unwrap_or(&self.root))
                .timeout_secs(300),
        )
    }

    pub fn gh_try(&self, args: &[&str]) -> String {
        let mut argv = vec!["gh".to_string()];
        argv.extend(args.iter().map(|s| s.to_string()));
        proc::run(
            &argv,
            &ExecOpts::new()
                .cwd(&self.root)
                .check(false)
                .timeout_secs(300),
        )
        .unwrap_or_default()
    }

    pub fn fetch_issues(&self, numbers: &[i64]) -> Result<Vec<Issue>> {
        let mut issues = Vec::new();
        for number in numbers {
            let text = self
                .gh(&[
                    "issue",
                    "view",
                    &number.to_string(),
                    "--json",
                    "number,title,body,labels,state,url",
                ])
                .map_err(|e| spar_err!("could not read issue #{number}: {}", e.last_line()))?;
            let issue: Issue = serde_json::from_str(&text)
                .map_err(|e| spar_err!("unexpected shape for issue #{number}: {e}"))?;
            if issue.is_closed() {
                crate::log!("issue #{number} is closed, skipping");
                continue;
            }
            issues.push(issue);
        }
        if issues.is_empty() {
            bail!("no open issues to work on");
        }
        Ok(issues)
    }

    fn open_numbers(&self, kind: &str, limit: usize) -> Result<Vec<i64>> {
        #[derive(Deserialize)]
        struct Row {
            number: i64,
        }
        let text = self.gh(&[
            kind,
            "list",
            "--state",
            "open",
            "--limit",
            &FETCH_CEILING.to_string(),
            "--json",
            "number",
        ])?;
        let rows: Vec<Row> = serde_json::from_str(text.trim()).unwrap_or_default();
        let mut numbers: Vec<i64> = rows.into_iter().map(|r| r.number).collect();
        numbers.sort_unstable();

        let noun = if kind == "issue" { "issues" } else { "PRs" };
        if numbers.len() >= FETCH_CEILING {
            crate::log!(
                "more than {FETCH_CEILING} open {noun}; only the first {FETCH_CEILING} were \
                 considered."
            );
        }
        if numbers.len() > limit {
            crate::log!(
                "{} open {noun}, taking the {limit} lowest numbered. Raise --limit or name them \
                 explicitly.",
                numbers.len()
            );
            numbers.truncate(limit);
        }
        Ok(numbers)
    }

    /// Open issues, lowest numbered first. `gh issue list` excludes PRs.
    pub fn list_open_issues(&self, limit: usize) -> Result<Vec<i64>> {
        self.open_numbers("issue", limit)
    }

    pub fn list_open_prs(&self, limit: usize) -> Result<Vec<i64>> {
        self.open_numbers("pr", limit)
    }

    pub fn pr_for_branch(&self, branch: &str) -> Option<PrRef> {
        let text = self.gh_try(&[
            "pr",
            "list",
            "--head",
            branch,
            "--state",
            "open",
            "--json",
            "number,url,title",
        ]);
        serde_json::from_str::<Vec<PrRef>>(text.trim())
            .ok()
            .and_then(|mut v| {
                if v.is_empty() {
                    None
                } else {
                    Some(v.remove(0))
                }
            })
    }

    /// Whether a number names an issue or a pull request.
    ///
    /// `gh issue view` happily returns a pull request when handed its number,
    /// so it cannot be used to tell them apart. The issues API carries both and
    /// marks a pull request with a `pull_request` key, which is definitive.
    pub fn item_kind(&self, number: i64) -> Result<ItemKind> {
        let path = format!("repos/{{owner}}/{{repo}}/issues/{number}");
        let text = self
            .gh(&[
                "api",
                &path,
                "--jq",
                "if .pull_request then \"pr\" else \"issue\" end",
            ])
            .map_err(|e| {
                spar_err!(
                    "no issue or pull request #{number} in this repository. {}",
                    e.last_line()
                )
            })?;
        match text.trim() {
            "pr" => Ok(ItemKind::Pr),
            "issue" => Ok(ItemKind::Issue),
            other => Err(spar_err!(
                "could not tell whether #{number} is an issue or a pull request (got {other:?})"
            )),
        }
    }

    /// An open pull request that would close this issue, whoever opened it.
    ///
    /// spar's own branch naming is checked first because it is exact and cheap.
    /// Falling back to GitHub's own issue linkage is what lets spar pick up a
    /// pull request a person started on a branch named anything at all.
    pub fn open_pr_for_issue(&self, issue: i64) -> Option<PrRef> {
        if let Some(pr) = self.pr_for_branch(&self.branch_for_issue(issue)) {
            return Some(pr);
        }
        let text = self.gh_try(&[
            "pr",
            "list",
            "--state",
            "open",
            "--limit",
            &FETCH_CEILING.to_string(),
            "--json",
            "number,url,title,closingIssuesReferences",
        ]);
        find_linked_pr(&text, issue)
    }

    pub fn pr_view(&self, number: i64) -> Result<PrView> {
        let text = self.gh(&[
            "pr",
            "view",
            &number.to_string(),
            "--json",
            "number,url,title,headRefName,baseRefName,state,closingIssuesReferences,isCrossRepository",
        ])?;
        serde_json::from_str(&text).map_err(|e| spar_err!("unexpected shape for PR #{number}: {e}"))
    }

    pub fn pr_state(&self, number: i64) -> String {
        let text = self.gh_try(&["pr", "view", &number.to_string(), "--json", "state"]);
        serde_json::from_str::<Value>(text.trim())
            .ok()
            .and_then(|v| v.get("state").and_then(Value::as_str).map(str::to_string))
            .unwrap_or_default()
    }

    pub fn create_pr(
        &self,
        cwd: &Path,
        branch: &str,
        base: &str,
        title: &str,
        body: &str,
    ) -> Result<PrRef> {
        let title = self.clean_title(title)?;
        let body = self.clean(body)?;
        self.gh_at(
            Some(cwd),
            &[
                "pr", "create", "--base", base, "--head", branch, "--title", &title, "--body",
                &body,
            ],
        )
        .map_err(|e| spar_err!("could not open a PR for {branch}. {}", e.last_line()))?;
        self.pr_for_branch(branch).ok_or_else(|| {
            spar_err!("PR creation reported success but none was found for {branch}")
        })
    }

    pub fn comment_pr(&self, number: i64, body: &str) -> Result<()> {
        let body = self.clean(body)?;
        self.gh(&["pr", "comment", &number.to_string(), "--body", &body])
            .map(|_| ())
    }

    pub fn comment_issue(&self, number: i64, body: &str) -> Result<()> {
        let body = self.clean(body)?;
        self.gh(&["issue", "comment", &number.to_string(), "--body", &body])
            .map(|_| ())
    }

    /// Comment, then close as not planned.
    ///
    /// Only ever called when both agents independently declined the issue: one
    /// agent's opinion is not enough to close somebody's report.
    pub fn close_issue(&self, number: i64, body: &str) -> Result<()> {
        self.comment_issue(number, body)?;
        let n = number.to_string();
        if self
            .gh(&["issue", "close", &n, "--reason", "not planned"])
            .is_ok()
        {
            return Ok(());
        }
        // Older gh builds do not take --reason.
        self.gh(&["issue", "close", &n]).map(|_| ()).map_err(|e| {
            spar_err!(
                "commented on #{number} but could not close it: {}",
                e.last_line()
            )
        })
    }

    pub fn create_issue(&self, title: &str, body: &str) -> Result<String> {
        let title = self.clean_title(title)?;
        let body = self.clean_issue_body(body)?;
        Ok(self
            .gh(&["issue", "create", "--title", &title, "--body", &body])?
            .trim()
            .to_string())
    }
}

/// An issue that already covers what spar was about to file.
#[derive(Debug, Clone)]
pub struct ExistingIssue {
    pub number: i64,
    pub url: String,
    pub title: String,
    pub body: String,
    pub open: bool,
}

impl Repo {
    /// An issue that already describes this defect, however it was worded.
    ///
    /// Exact title matching let duplicates through: two agents, or two runs a
    /// week apart, never word one defect identically. A real run filed two
    /// duplicates that way, and each had to be closed by hand afterwards.
    /// Titles alone are too thin to match on, so this compares titles and
    /// bodies together.
    pub fn find_similar_issue(&self, title: &str, body: &str) -> Option<ExistingIssue> {
        #[derive(Deserialize)]
        #[serde(rename_all = "camelCase")]
        struct Row {
            number: i64,
            #[serde(default)]
            title: String,
            #[serde(default)]
            url: String,
            #[serde(default)]
            body: String,
            #[serde(default)]
            state: String,
        }
        if title.trim().is_empty() {
            return None;
        }
        // Search on the title's own words: GitHub's index is the cheap way to
        // narrow the field before comparing properly.
        let query: String = title
            .chars()
            .filter(|c| !matches!(c, '"' | '\'' | '\n' | '\r'))
            .take(120)
            .collect();
        let text = self.gh_try(&[
            "issue",
            "list",
            "--state",
            "all",
            "--limit",
            "100",
            "--search",
            query.trim(),
            "--json",
            "number,title,url,body,state",
        ]);
        let rows: Vec<Row> = serde_json::from_str(text.trim()).unwrap_or_default();
        let wanted = format!("{title} {body}");

        rows.into_iter()
            .find(|row| {
                let theirs = format!("{} {}", row.title, row.body);
                row.title.trim().eq_ignore_ascii_case(title.trim())
                    || textsim::same_subject(&wanted, &theirs)
            })
            .map(|row| ExistingIssue {
                number: row.number,
                url: row.url,
                title: row.title,
                open: row.state.eq_ignore_ascii_case("open"),
                body: row.body,
            })
    }

    /// Avoid filing a duplicate when a follow-up already exists.
    pub fn find_issue_by_title(&self, title: &str) -> Option<String> {
        #[derive(Deserialize)]
        struct Row {
            title: String,
            url: String,
        }
        let needle = title.trim().to_lowercase();
        if needle.is_empty() {
            return None;
        }
        // Quotes and newlines would be read as search syntax rather than text.
        let query: String = title
            .chars()
            .filter(|c| !matches!(c, '"' | '\'' | '\n' | '\r'))
            .take(120)
            .collect();
        let text = self.gh_try(&[
            "issue",
            "list",
            "--state",
            "all",
            "--limit",
            "100",
            "--search",
            query.trim(),
            "--json",
            "number,title,url",
        ]);
        serde_json::from_str::<Vec<Row>>(text.trim())
            .ok()?
            .into_iter()
            .find(|row| row.title.trim().to_lowercase() == needle)
            .map(|row| row.url)
    }

    /// Squash merge, tolerating cleanup failures after a successful merge.
    ///
    /// `gh pr merge --delete-branch` exits non-zero when it cannot delete the
    /// local branch, which happens *after* the merge has already landed.
    /// Treating that as a failure reports work as lost when it is not.
    pub fn merge_pr(&self, number: i64) -> Result<()> {
        let n = number.to_string();
        match self.gh(&["pr", "merge", &n, "--squash", "--delete-branch"]) {
            Ok(_) => Ok(()),
            Err(e) => {
                if self.pr_state(number) == "MERGED" {
                    logdim!(
                        "PR #{number} merged; branch cleanup did not finish: {}",
                        e.last_line()
                    );
                    Ok(())
                } else {
                    Err(spar_err!("could not merge PR #{number}. {}", e.last_line()))
                }
            }
        }
    }

    // -- follow-ups -------------------------------------------------------

    /// Append a follow-up to a local note instead of the tracker.
    ///
    /// Deduplicated on the title, matching the issue path. Returns a display
    /// string, or None when it was already recorded. The body arrives with its
    /// provenance already stamped by the caller, so nothing is added here.
    pub fn append_local_followup(&self, title: &str, body: &str) -> Option<String> {
        let path = self.root.join(STATE_DIR).join("followups.md");
        let heading = format!("## {}", title.trim());
        if let Ok(existing) = std::fs::read_to_string(&path) {
            if existing.contains(&heading) {
                logdim!("follow-up already noted: {title}");
                return None;
            }
        }
        if let Some(parent) = path.parent() {
            let _ = std::fs::create_dir_all(parent);
        }
        use std::io::Write;
        // The caller already stamped the provenance into the body. Adding
        // "From #N." here as well printed it twice, in two different wordings.
        let entry = format!("{heading}\n\n{}\n\n", body.trim());
        match std::fs::OpenOptions::new()
            .create(true)
            .append(true)
            .open(&path)
        {
            Ok(mut file) => {
                let _ = file.write_all(entry.as_bytes());
                Some(format!("note: {}", title.trim()))
            }
            Err(e) => {
                logdim!("could not write {}: {e}", path.display());
                None
            }
        }
    }

    // -- resumable state --------------------------------------------------
    //
    // Custody cannot be read from GitHub authorship: every agent commits and
    // comments as the same git identity, so `author` is always the human who
    // ran spar. State is kept on disk by default and can additionally travel in
    // a PR comment, which is what lets a run be resumed from another machine.

    pub fn state_path(&self, number: i64) -> PathBuf {
        self.root
            .join(STATE_DIR)
            .join("state")
            .join(format!("pr-{number}.json"))
    }

    fn read_local_state(&self, number: i64) -> Option<PersistedState> {
        let path = self.state_path(number);
        let text = std::fs::read_to_string(&path).ok()?;
        match serde_json::from_str(&text) {
            Ok(state) => Some(state),
            Err(_) => {
                logdim!("could not read {}, starting fresh", path.display());
                None
            }
        }
    }

    pub fn read_state(&self, pr: &PrView) -> Option<PersistedState> {
        if let Some(local) = self.read_local_state(pr.number) {
            return Some(local);
        }
        if self.state_store.writes_pr() {
            return self.read_pr_state(pr.number);
        }
        None
    }

    fn read_pr_state(&self, number: i64) -> Option<PersistedState> {
        for body in self.state_comment_bodies(number).into_iter().rev() {
            if let Some(state) = parse_state_comment(&body) {
                return Some(state);
            }
        }
        None
    }

    pub fn write_state(&self, number: i64, state: &PersistedState) -> Result<()> {
        if self.state_store.writes_local() {
            write_json_atomic(&self.state_path(number), state)?;
        }
        if self.state_store.writes_pr() {
            self.write_pr_state(number, state)?;
        }
        Ok(())
    }

    fn write_pr_state(&self, number: i64, state: &PersistedState) -> Result<()> {
        // Not run through clean(): this is structured data, and scrubbing would
        // corrupt refutation text stored in the ledger. It sits inside an
        // unclosed HTML comment so GitHub renders it as nothing.
        let body = format!(
            "{STATE_MARKER}\n{}\n-->",
            serde_json::to_string_pretty(state)?
        );
        if let Some(id) = self.state_comment_id(number) {
            let path = format!("repos/{{owner}}/{{repo}}/issues/comments/{id}");
            let field = format!("body={body}");
            self.gh_try(&["api", "-X", "PATCH", &path, "-f", &field, "--silent"]);
            return Ok(());
        }
        self.gh(&["pr", "comment", &number.to_string(), "--body", &body])
            .map(|_| ())
    }

    fn comments_json(&self, number: i64) -> Vec<Value> {
        let path = format!("repos/{{owner}}/{{repo}}/issues/{number}/comments");
        parse_comment_pages(&self.gh_try(&["api", "--paginate", &path]))
    }

    fn state_comments(&self, number: i64) -> Vec<(i64, String)> {
        self.comments_json(number)
            .into_iter()
            .filter_map(|c| {
                let body = c.get("body").and_then(Value::as_str)?.to_string();
                if !body.contains("spar:state") {
                    return None;
                }
                let id = c.get("id").and_then(Value::as_i64)?;
                Some((id, body))
            })
            .collect()
    }

    fn state_comment_bodies(&self, number: i64) -> Vec<String> {
        self.state_comments(number)
            .into_iter()
            .map(|(_, b)| b)
            .collect()
    }

    fn state_comment_id(&self, number: i64) -> Option<i64> {
        self.state_comments(number).last().map(|(id, _)| *id)
    }

    /// Drop state once the PR is finished and there is nothing to resume.
    pub fn clear_state(&self, number: i64) {
        let path = self.state_path(number);
        let _ = std::fs::remove_file(&path);
        let _ = std::fs::remove_file(path.with_extension("json.tmp"));
    }

    // -- housekeeping -----------------------------------------------------

    /// Remove state files whose PR is merged or closed.
    pub fn prune_state(&self) -> Vec<String> {
        let base = self.root.join(STATE_DIR).join("state");
        let Ok(entries) = std::fs::read_dir(&base) else {
            return Vec::new();
        };
        let mut names: Vec<String> = entries
            .flatten()
            .filter_map(|e| e.file_name().to_str().map(str::to_string))
            .filter(|n| n.starts_with("pr-") && n.ends_with(".json"))
            .collect();
        names.sort();

        let mut removed = Vec::new();
        for name in names {
            let Ok(number) = name[3..name.len() - 5].parse::<i64>() else {
                continue;
            };
            if is_finished(&self.pr_state(number)) {
                let _ = std::fs::remove_file(base.join(&name));
                removed.push(format!("state {name}"));
            }
        }
        removed
    }

    /// Delete state comments from PRs that are finished.
    ///
    /// Open PRs are left alone: their state may still be live.
    pub fn prune_pr_state(&self, numbers: Option<Vec<i64>>) -> Vec<String> {
        #[derive(Deserialize)]
        struct Row {
            number: i64,
        }
        let numbers = numbers.unwrap_or_else(|| {
            let text = self.gh_try(&[
                "pr", "list", "--state", "all", "--limit", "200", "--json", "number",
            ]);
            serde_json::from_str::<Vec<Row>>(text.trim())
                .unwrap_or_default()
                .into_iter()
                .map(|r| r.number)
                .collect()
        });

        let mut removed = Vec::new();
        for number in numbers {
            if !is_finished(&self.pr_state(number)) {
                continue;
            }
            for (id, _) in self.state_comments(number) {
                let path = format!("repos/{{owner}}/{{repo}}/issues/comments/{id}");
                self.gh_try(&["api", "-X", "DELETE", &path, "--silent"]);
                removed.push(format!("state comment on PR #{number}"));
            }
        }
        removed
    }

    /// Drop worktrees whose PR is finished, then the branches they left behind.
    ///
    /// With auto_merge off, which is the default, a run ends at "approved", so
    /// nothing would ever clean these up on its own and they accumulate one per
    /// run. A stranded worktree also holds its branch checked out, which makes
    /// a later `gh pr merge --delete-branch` fail to clean up.
    pub fn prune_worktrees(&self, force_all: bool) -> Vec<String> {
        let base = self.root.join(WORKTREE_DIR);
        let mut removed = Vec::new();

        if let Ok(entries) = std::fs::read_dir(&base) {
            let mut names: Vec<String> = entries
                .flatten()
                .filter(|e| e.path().is_dir())
                .filter_map(|e| e.file_name().to_str().map(str::to_string))
                .collect();
            names.sort();

            for name in names {
                // A review worktree is detached and owns no branch, so it is
                // tied to the pull request only by its directory name.
                if let Some(rest) = name.strip_prefix("review-") {
                    let number: i64 = rest.parse().unwrap_or(-1);
                    if !(force_all || is_finished(&self.pr_state(number))) {
                        continue;
                    }
                    self.release_review_worktree(number);
                    removed.push(name);
                    continue;
                }
                let branch = format!("{}{name}", self.branch_prefix);
                if !(force_all || self.worktree_is_done(&branch)) {
                    continue;
                }
                self.remove_worktree_at(&base.join(&name));
                self.git_try(&["branch", "-D", &branch]);
                self.forget_branch(&branch);
                removed.push(name);
            }
        }
        if !removed.is_empty() {
            self.git_try(&["worktree", "prune"]);
        }
        removed.extend(self.prune_branches(force_all));
        removed
    }

    /// Delete leftover branches spar created whose worktree is already gone.
    ///
    /// Deletion is driven by the ledger of branches spar actually created, not
    /// by a name pattern. Names default to `issue-N`, which is exactly what a
    /// person would call a branch themselves, so a name alone can never
    /// establish ownership. This is the data loss guard.
    pub fn prune_branches(&self, force_all: bool) -> Vec<String> {
        let branches: Vec<String> = self.known_branches().keys().cloned().collect();
        if branches.is_empty() {
            return Vec::new();
        }

        let checked_out: Vec<String> = self
            .git_try(&["worktree", "list", "--porcelain"])
            .lines()
            .filter_map(|l| l.strip_prefix("branch refs/heads/").map(str::to_string))
            .collect();

        // %(refname:short) is ambiguous when a tag shares the branch name (it
        // yields "heads/..."), so take the full ref and strip it here.
        let existing: Vec<String> = self
            .git_try(&["for-each-ref", "refs/heads/", "--format=%(refname)"])
            .lines()
            .filter_map(|l| l.trim().strip_prefix("refs/heads/").map(str::to_string))
            .collect();

        let mut removed = Vec::new();
        for branch in branches {
            if !existing.contains(&branch) {
                self.forget_branch(&branch); // already gone, drop the record
                continue;
            }
            if checked_out.contains(&branch) {
                continue;
            }
            if !(force_all || self.worktree_is_done(&branch)) {
                continue;
            }
            match self.git(&["branch", "-D", &branch]) {
                Ok(_) => {
                    self.forget_branch(&branch);
                    removed.push(format!("branch {branch}"));
                }
                Err(e) => {
                    // A branch that silently survives pruning looks like a spar
                    // bug, so the name and git's own reason have to be said.
                    logdim!("could not delete {branch}: {}", e.last_line());
                }
            }
        }
        removed
    }

    /// True when the PR behind this branch is merged or closed.
    fn worktree_is_done(&self, branch: &str) -> bool {
        #[derive(Deserialize)]
        struct Row {
            state: String,
        }
        let entry = branch
            .strip_prefix(self.branch_prefix.as_str())
            .unwrap_or(branch);
        if let Some(rest) = entry.strip_prefix("pr-") {
            return is_finished(&self.pr_state(rest.parse().unwrap_or(-1)));
        }
        if entry.starts_with("issue-") {
            let text = self.gh_try(&[
                "pr", "list", "--head", branch, "--state", "all", "--json", "state",
            ]);
            let rows: Vec<Row> = serde_json::from_str(text.trim()).unwrap_or_default();
            return !rows.is_empty() && rows.iter().all(|r| is_finished(&r.state));
        }
        false
    }
}

// ---------------------------------------------------------------------------
// Free helpers
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, serde::Serialize, Deserialize)]
pub struct BranchRecord {
    pub kind: String,
    pub number: i64,
}

/// Where a pull request's fetched head is parked. Under `refs/spar/` rather
/// than `refs/heads/` so it can never be mistaken for a branch, or pushed.
pub fn review_ref(number: i64) -> String {
    format!("refs/spar/pr-{number}")
}

pub fn is_finished(state: &str) -> bool {
    matches!(state.trim().to_uppercase().as_str(), "MERGED" | "CLOSED")
}

/// Write JSON through a temporary file and rename, so a kill cannot leave a
/// truncated state file behind.
pub fn write_json_atomic<T: serde::Serialize>(path: &Path, value: &T) -> Result<()> {
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .map_err(|e| spar_err!("could not create {}: {e}", parent.display()))?;
    }
    let tmp = path.with_extension(format!(
        "{}.tmp",
        path.extension().and_then(|e| e.to_str()).unwrap_or("json")
    ));
    std::fs::write(&tmp, serde_json::to_vec_pretty(value)?)
        .map_err(|e| spar_err!("could not write {}: {e}", tmp.display()))?;
    std::fs::rename(&tmp, path)
        .map_err(|e| spar_err!("could not replace {}: {e}", path.display()))?;
    Ok(())
}

/// Among the open pull requests gh listed, the first that would close `issue`.
///
/// Separated from the gh call so the real payload shape can be tested. GitHub
/// returns far more per linked issue than the number, and silently failing to
/// parse it would look exactly like "no pull request exists", which is the
/// answer that makes spar implement over the top of somebody's work.
pub fn find_linked_pr(json: &str, issue: i64) -> Option<PrRef> {
    #[derive(Deserialize)]
    #[serde(rename_all = "camelCase")]
    struct Row {
        number: i64,
        #[serde(default)]
        url: String,
        #[serde(default)]
        title: String,
        #[serde(default)]
        closing_issues_references: Vec<IssueRef>,
    }

    serde_json::from_str::<Vec<Row>>(json.trim())
        .ok()?
        .into_iter()
        .find(|row| {
            row.closing_issues_references
                .iter()
                .any(|linked| linked.number == issue)
        })
        .map(|row| PrRef {
            number: row.number,
            url: row.url,
            title: row.title,
        })
}

/// Flatten whatever `gh api --paginate` printed into a list of comments.
///
/// Current gh merges array pages into one array. Older builds concatenated one
/// document per page. A streaming parser reads either, and unlike splitting the
/// text on a bracket pair it cannot be fooled by a comment body that happens to
/// contain one, which would otherwise make a resume silently start over.
pub fn parse_comment_pages(text: &str) -> Vec<Value> {
    let mut out = Vec::new();
    for value in serde_json::Deserializer::from_str(text.trim()).into_iter::<Value>() {
        match value {
            Ok(Value::Array(items)) => out.extend(items),
            Ok(other) => out.push(other),
            Err(_) => break,
        }
    }
    out
}

/// Extract the payload from a state comment. The marker is followed by JSON and
/// terminated with `-->`.
pub fn parse_state_comment(body: &str) -> Option<PersistedState> {
    let marker = body.find(STATE_MARKER)?;
    let start = body[marker..].find('{')? + marker;
    let end = body.rfind('}')?;
    if end <= start {
        return None;
    }
    match serde_json::from_str(&body[start..=end]) {
        Ok(state) => Some(state),
        Err(_) => {
            logdim!("found a spar state comment but could not parse it");
            None
        }
    }
}

/// Where this binary lives, so `git filter-branch` can call back into it.
///
/// `SPAR_SELF_BIN` overrides the answer. That matters for the integration
/// tests, whose `current_exe` is the test harness rather than spar, and for
/// anyone who ships spar behind a wrapper script.
pub fn self_binary() -> Result<PathBuf> {
    if let Some(path) = std::env::var_os("SPAR_SELF_BIN") {
        let path = PathBuf::from(path);
        if proc::is_executable(&path) {
            return Ok(path);
        }
        bail!(
            "SPAR_SELF_BIN is set to {}, which is not executable",
            path.display()
        );
    }
    std::env::current_exe()
        .map_err(|e| spar_err!("could not locate the spar binary for a commit rewrite: {e}"))
}

fn bool_env(value: bool) -> &'static str {
    if value {
        "1"
    } else {
        "0"
    }
}

/// Wrap a string for a POSIX shell. `git filter-branch` takes its filter as a
/// shell command, and an install path with a space in it is not exotic.
pub fn sh_quote(text: &str) -> String {
    format!("'{}'", text.replace('\'', r"'\''"))
}

/// Style rules for the `scrub-filter` subcommand, which runs in a child process
/// spawned by git and so cannot see the parent's config.
pub fn style_from_env() -> Style {
    let flag = |key: &str| !matches!(std::env::var(key).as_deref(), Ok("0"));
    Style {
        ban_em_dash: flag("SPAR_BAN_EM_DASH"),
        ban_ai_attribution: flag("SPAR_BAN_AI_ATTRIBUTION"),
        ..Style::permissive()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::StateStore;
    use crate::model::{Ledger, Status};

    fn repo_for_titles() -> Repo {
        Repo {
            root: PathBuf::from("/nonexistent"),
            style: Style::default(),
            branch_prefix: String::new(),
            state_store: StateStore::Local,
            followups: crate::config::Followups::Issues,
        }
    }

    /// Follow-up deduplication compares a title it computed against the title
    /// GitHub stored. If those two transforms can disagree, the check never
    /// matches and every review round files another copy of the same issue.
    #[test]
    fn clean_title_is_idempotent_even_when_the_scrub_lengthens_it() {
        let repo = repo_for_titles();
        for raw in [
            "Retry loop spins \u{2014} Retry-After parses to zero",
            "plain title",
            "  spread   over\nlines  ",
            "\u{1F916} Generated with something",
            &format!("a \u{2014} {}", "very long title ".repeat(20)),
            &"x".repeat(300),
            &format!("{} \u{2014} end", "y".repeat(88)),
            // Exactly the budget, with two spaceless dashes. The scrub turns
            // each "a\u{2014}b" into "a, b", so clip-then-scrub lands one
            // character over budget per dash and a second pass clips again,
            // producing a different string. Scrub-then-clip cannot.
            &{
                let tail = "a\u{2014}b c\u{2014}d";
                let pad = Style::default().max_title_chars - tail.chars().count();
                format!("{}{tail}", "w".repeat(pad))
            },
        ] {
            let once = repo.clean_title(raw).unwrap();
            let twice = repo.clean_title(&once).unwrap();
            assert_eq!(once, twice, "not idempotent for {raw:?}");
            assert!(
                once.chars().count() <= repo.style.max_title_chars,
                "over budget: {once:?}"
            );
            assert!(style::violations(&once, &repo.style).is_empty(), "{once:?}");
        }
    }

    #[test]
    fn a_title_with_an_em_dash_survives_as_readable_text() {
        let repo = repo_for_titles();
        assert_eq!(
            "Retry loop spins, Retry-After parses to zero",
            repo.clean_title("Retry loop spins \u{2014} Retry-After parses to zero")
                .unwrap()
        );
    }

    #[test]
    fn sh_quote_survives_a_quote() {
        assert_eq!(r"'a'\''b'", sh_quote("a'b"));
    }

    #[test]
    fn sh_quote_wraps_a_space() {
        assert_eq!(
            "'/Applications/My App/spar'",
            sh_quote("/Applications/My App/spar")
        );
    }

    #[test]
    fn finished_states_are_recognised_case_insensitively() {
        assert!(is_finished("MERGED"));
        assert!(is_finished("closed"));
        assert!(!is_finished("OPEN"));
        assert!(!is_finished(""));
    }

    fn state() -> PersistedState {
        PersistedState {
            version: 1,
            round: 4,
            next_actor: "codex".into(),
            status: Status::Pending,
            ledger: Ledger::new(),
            filed: vec![],
        }
    }

    #[test]
    fn a_state_comment_round_trips() {
        let body = format!(
            "{STATE_MARKER}\n{}\n-->",
            serde_json::to_string(&state()).unwrap()
        );
        let back = parse_state_comment(&body).unwrap();
        assert_eq!(4, back.round);
        assert_eq!("codex", back.next_actor);
    }

    /// It must render as nothing, so PRs are not littered with machine state.
    #[test]
    fn the_state_block_is_an_html_comment() {
        let body = format!(
            "{STATE_MARKER}\n{}\n-->",
            serde_json::to_string(&state()).unwrap()
        );
        assert!(body.starts_with("<!--"));
        assert!(body.trim_end().ends_with("-->"));
        assert!(!body[..body.find('{').unwrap()].contains("-->"));
    }

    #[test]
    fn an_unrelated_json_block_is_not_state() {
        assert!(parse_state_comment("here is a snippet\n```json\n{\"round\": 99}\n```").is_none());
    }

    #[test]
    fn a_malformed_state_comment_is_none_not_a_panic() {
        assert!(parse_state_comment(&format!("{STATE_MARKER}\n{{not json\n-->")).is_none());
    }

    #[test]
    fn atomic_write_leaves_no_temp_file() {
        let dir = std::env::temp_dir().join(format!("spar-atomic-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("state").join("pr-7.json");
        write_json_atomic(&path, &state()).unwrap();
        let files: Vec<String> = std::fs::read_dir(path.parent().unwrap())
            .unwrap()
            .flatten()
            .filter_map(|e| e.file_name().to_str().map(str::to_string))
            .collect();
        assert_eq!(vec!["pr-7.json".to_string()], files);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn atomic_write_overwrites_rather_than_accumulating() {
        let dir = std::env::temp_dir().join(format!("spar-overwrite-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("pr-7.json");
        for round in 1..4 {
            let mut s = state();
            s.round = round;
            write_json_atomic(&path, &s).unwrap();
        }
        let back: PersistedState =
            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
        assert_eq!(3, back.round);
        let _ = std::fs::remove_dir_all(&dir);
    }

    #[test]
    fn style_from_env_defaults_to_enforcing() {
        std::env::remove_var("SPAR_BAN_EM_DASH");
        std::env::remove_var("SPAR_BAN_AI_ATTRIBUTION");
        let style = style_from_env();
        assert!(style.ban_em_dash && style.ban_ai_attribution);
        assert!(
            !style.terse,
            "the commit filter must not truncate a commit message"
        );
    }
}

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

    #[test]
    fn a_single_merged_array_is_read() {
        let pages = parse_comment_pages(r#"[{"id":1,"body":"a"},{"id":2,"body":"b"}]"#);
        assert_eq!(2, pages.len());
        assert_eq!(Some(2), pages[1]["id"].as_i64());
    }

    #[test]
    fn concatenated_pages_from_an_older_gh_are_read_too() {
        let pages = parse_comment_pages(r#"[{"id":1}][{"id":2}]"#);
        assert_eq!(2, pages.len());
    }

    /// A comment body containing a bracket pair used to split the payload into
    /// two invalid halves, so no state comment was found and a resume silently
    /// started from round one.
    #[test]
    fn a_comment_body_containing_a_bracket_pair_is_not_mistaken_for_a_page_break() {
        let text = r#"[{"id":1,"body":"see [the docs][ref] for why"},{"id":2,"body":"ok"}]"#;
        let pages = parse_comment_pages(text);
        assert_eq!(2, pages.len(), "{pages:?}");
        assert!(pages[0]["body"].as_str().unwrap().contains("[ref]"));
    }

    #[test]
    fn empty_output_is_no_comments_not_a_panic() {
        assert!(parse_comment_pages("").is_empty());
        assert!(parse_comment_pages("   ").is_empty());
        assert!(parse_comment_pages("[]").is_empty());
    }

    #[test]
    fn a_gh_error_message_on_stdout_yields_nothing_rather_than_garbage() {
        assert!(parse_comment_pages("gh: Not Found (HTTP 404)").is_empty());
    }

    #[test]
    fn state_is_found_in_the_last_matching_comment() {
        let payload = |round: u32| {
            format!(
                "{STATE_MARKER}\n{{\"version\":1,\"round\":{round},\"next_actor\":\"a\",\"status\":\"pending\",\"ledger\":{{}},\"filed\":[]}}\n-->"
            )
        };
        let text = serde_json::to_string(&serde_json::json!([
            {"id": 1, "body": payload(1)},
            {"id": 2, "body": "looks good to me"},
            {"id": 3, "body": payload(5)},
        ]))
        .unwrap();
        let pages = parse_comment_pages(&text);
        let last = pages
            .iter()
            .rev()
            .find_map(|c| parse_state_comment(c["body"].as_str().unwrap_or("")))
            .unwrap();
        assert_eq!(5, last.round);
    }
}

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

    /// The exact shape `gh pr list --json closingIssuesReferences` returns.
    /// It carries an id and a whole repository object per linked issue, and a
    /// parser that chokes on those reports "no pull request", which is the one
    /// answer that makes spar implement over the top of somebody's work.
    const REAL_PAYLOAD: &str = r#"[
      {"number":14252,"title":"fix: reject leading-dash branch names",
       "url":"https://github.com/cli/cli/pull/14252",
       "closingIssuesReferences":[{"id":"I_kwDO","number":14238,
         "repository":{"id":"MDEwOlJl","name":"cli","owner":{"id":"MDEy","login":"cli"}},
         "url":"https://github.com/cli/cli/issues/14238"}]},
      {"number":14217,"title":"another change",
       "url":"https://github.com/cli/cli/pull/14217",
       "closingIssuesReferences":[{"id":"I_kwDO","number":9761,
         "repository":{"id":"MDEwOlJl","name":"cli","owner":{"id":"MDEy","login":"cli"}},
         "url":"https://github.com/cli/cli/issues/9761"}]},
      {"number":14200,"title":"unlinked work",
       "url":"https://github.com/cli/cli/pull/14200","closingIssuesReferences":[]}
    ]"#;

    #[test]
    fn a_linked_pr_is_found_whatever_its_branch_is_called() {
        let pr = find_linked_pr(REAL_PAYLOAD, 14238).expect("should find it");
        assert_eq!(14252, pr.number);
        assert_eq!("https://github.com/cli/cli/pull/14252", pr.url);
    }

    #[test]
    fn the_right_pr_is_picked_out_of_several() {
        assert_eq!(14217, find_linked_pr(REAL_PAYLOAD, 9761).unwrap().number);
    }

    #[test]
    fn an_issue_nobody_is_working_on_finds_nothing() {
        assert!(find_linked_pr(REAL_PAYLOAD, 99999).is_none());
    }

    #[test]
    fn an_unlinked_pr_is_never_matched() {
        // 14200 closes nothing, so no issue number should ever return it.
        for issue in [14200, 0, 1] {
            if let Some(pr) = find_linked_pr(REAL_PAYLOAD, issue) {
                assert_ne!(14200, pr.number, "matched a PR that closes nothing");
            }
        }
    }

    #[test]
    fn empty_or_broken_output_is_none_rather_than_a_panic() {
        assert!(find_linked_pr("", 1).is_none());
        assert!(find_linked_pr("[]", 1).is_none());
        assert!(find_linked_pr("gh: Not Found (HTTP 404)", 1).is_none());
        assert!(find_linked_pr("[{\"number\":", 1).is_none());
    }

    /// A fork PR cannot be pushed to, so the flag has to survive parsing.
    #[test]
    fn pr_view_reads_the_cross_repository_flag() {
        let json = r#"{"number":7,"url":"u","title":"t","headRefName":"patch-1",
                       "baseRefName":"main","state":"OPEN",
                       "closingIssuesReferences":[],"isCrossRepository":true}"#;
        let pr: PrView = serde_json::from_str(json).unwrap();
        assert!(pr.is_cross_repository);
        assert!(pr.is_open());

        let same_repo = json.replace("\"isCrossRepository\":true", "\"isCrossRepository\":false");
        assert!(
            !serde_json::from_str::<PrView>(&same_repo)
                .unwrap()
                .is_cross_repository
        );
    }
}