spar-cli 0.1.1

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
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
//! Alternating custody until a PR converges.
//!
//! Roles are not fixed. Whoever holds the PR may implement, review, fix, or
//! file follow-ups, and then hands custody to the other. An agent never
//! reviews its own most recent edit.
//!
//! Three failure modes are handled explicitly here, because each one breaks a
//! naive loop:
//!
//! - **The nitpick spiral.** Round 6 findings are worse than round 1 findings
//!   and a loop that counts objections cannot tell. Only `blocking` gates.
//! - **Re-litigation.** A refuted point re-raised forever never terminates.
//!   Refutations are hashed into a ledger carried across rounds.
//! - **Approval drift.** Optimising for "get approved" pressures the author
//!   into accepting wrong review comments, so refutation is blessed and the
//!   merge gate is blocking-findings-empty, not reviewer-satisfied.

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

use crate::agent::{self, Agent};
use crate::config::{Config, Followups, PrComments};
use crate::error::{Result, SparError};
use crate::jsonx::finding_key;
use crate::model::{
    Action, Dispute, Finding, Issue, IssueRun, Ledger, LedgerEntry, NextAction, PersistedState,
    PlanItem, PrView, ResponseDoc, Review, Severity, SkippedItem, Status, STATE_VERSION,
};
use crate::repo::Repo;
use crate::style::{self, Style};
use crate::{log, logdim, schema, spar_err};

// ---------------------------------------------------------------------------
// Prompts
// ---------------------------------------------------------------------------

const IMPLEMENT_PROMPT: &str = "\
Implement GitHub issue #{number} in this repository.

Title: {title}

{body}

Do the work, then commit it on the current branch. Make focused commits with
clear messages. Do not push, do not open a PR, and do not merge; the harness
handles that.

End your final message with a line of exactly this form:
SUMMARY: <one sentence under 120 characters saying what changed>
That line becomes the PR description, so write it for the reviewer who has to
read it, and say what changed rather than that you changed something.

If after reading the code you conclude this issue should not be implemented,
make no commits and explain why in your final message, beginning with
NOT_WORTH_DOING.";

const REVIEW_PROMPT: &str = "\
Review the changes on this branch against `{base}`. They implement issue
#{number}: {title}

Review thoroughly: correctness, edge cases, error handling, security, and
whether the change actually resolves the issue. Read surrounding code, do not
only read the diff.

Label every finding by severity, and be honest about which is which:
- blocking: the PR should not merge as is. Real defects only.
- non-blocking: a genuine improvement that need not gate this PR.
- nit: style or taste.

Confirm anything you label blocking before you label it. Run the code,
reproduce the failure, or point at the exact line that breaks, and say in the
detail what you did to confirm it. An unverified blocking finding is worse than
one you never raised: it stalls a good PR and teaches the author to stop
believing you. If you suspect a problem but could not confirm it, say so and
label it non-blocking.

Set in_scope=false for a real problem that exists but is not caused by this PR.
Those become follow-up issues rather than review comments.

Then choose next_action:
- merge: no blocking findings, the PR is good.
- fix_myself: there are blocking findings and you will fix them directly.
- hand_back: there are blocking findings the author should address.
{settled}";

const FIX_PROMPT: &str = "\
You reviewed this branch and chose to fix the blocking findings yourself.
Implement those fixes now and commit them.

Your findings:
{findings}

Commit your changes. Do not push, do not merge.";

const RESPOND_PROMPT: &str = "\
Here is a review of your PR for issue #{number}.

{findings}

For each point, choose exactly one disposition:
- fixed: the point is valid and in scope. Fix it and commit.
- refuted: the point is wrong, or not worth acting on. Explain why. Refuting is
  a legitimate outcome; do not accept a review comment you believe is incorrect
  just to get the PR approved.
- filed_issue: the point is valid but unrelated to this PR. Supply
  new_issue_title and new_issue_body; the harness files it and skips duplicates.

Copy each finding's title and file across exactly as given, so your answer can
be matched back to the review.

Commit any fixes. Do not push, do not merge.";

/// A worktree is only worth keeping when a person has to look at it locally.
/// Anything else strands a checked-out branch that blocks
/// `gh pr merge --delete-branch`, and since auto_merge is off by default,
/// keeping it on anything but "merged" leaks one per run.
fn should_release(cfg: &Config, status: Status) -> bool {
    if !cfg.loop_cfg.worktrees || cfg.loop_cfg.keep_worktrees {
        return false;
    }
    !matches!(status, Status::Escalated | Status::Error)
}

// ---------------------------------------------------------------------------
// One issue, start to finish
// ---------------------------------------------------------------------------

pub fn run_issue(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    item: &PlanItem,
    issue: &Issue,
    ledger: &mut Ledger,
) -> IssueRun {
    // Continue an existing PR rather than implementing over the top of it.
    //
    // Without this, a second `spar run 42` deletes the local branch, rebuilds
    // it from the base, implements from scratch, and force pushes. The lease
    // holds because the remote tracking ref survives the local branch being
    // deleted, so the push succeeds and the previous round's work is gone from
    // the PR with nothing to say it ever existed.
    if let Some(existing) = repo.open_pr_for_issue(item.issue) {
        log!(
            "#{}: {} is already open, continuing it instead of implementing again",
            item.issue,
            existing.url
        );
        return resume_pr(agents, cfg, repo, existing.number, None);
    }

    let mut state = IssueRun::new(item.issue, item.title.clone());
    let base = cfg.base_branch().to_string();

    let prepared = if cfg.loop_cfg.worktrees {
        repo.worktree_add(item.issue, &base)
    } else {
        let branch = repo.branch_for_issue(item.issue);
        let start = format!("origin/{base}");
        repo.git(&["checkout", "-B", &branch, &start])
            .map(|_| (repo.root().to_path_buf(), branch))
    };

    let (work_dir, branch) = match prepared {
        Ok(pair) => pair,
        Err(e) => {
            state.status = Status::Error;
            state.notes.push(e.to_string());
            log!("#{} failed: {e}", item.issue);
            return state;
        }
    };

    let outcome = implement_and_review(
        agents, cfg, repo, item, issue, ledger, &mut state, &work_dir, &branch,
    );
    if let Err(e) = outcome {
        state.status = Status::Error;
        state.notes.push(e.to_string());
        log!("#{} failed: {e}", item.issue);
    }

    if should_release(cfg, state.status) {
        repo.worktree_remove(item.issue);
    }
    state
}

#[allow(clippy::too_many_arguments)]
fn implement_and_review(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    item: &PlanItem,
    issue: &Issue,
    ledger: &mut Ledger,
    state: &mut IssueRun,
    work_dir: &Path,
    branch: &str,
) -> Result<()> {
    let number = item.issue;
    let holder = cfg.first_implementor.clone();
    let implementor = agent::find(agents, &holder)?;
    let base = cfg.base_branch().to_string();

    log!("#{number}: {holder} implementing");
    let body: String = issue.body_text().trim().chars().take(6000).collect();
    let prompt = IMPLEMENT_PROMPT
        .replace("{number}", &number.to_string())
        .replace("{title}", &item.title)
        .replace("{body}", &body);
    let out = implementor.ask(
        &prompt,
        work_dir,
        cfg.effort_for_round(&implementor.spec, 1).as_deref(),
    )?;

    if out.to_uppercase().contains("NOT_WORTH_DOING") || !repo.has_changes(work_dir, &base) {
        state.status = Status::Abandoned;
        let reason = style::body(&out, &repo.style);
        state.notes.push(reason.clone());
        if let Err(e) = repo.comment_issue(number, &reason) {
            logdim!("could not comment on #{number}: {e}");
        }
        return Ok(());
    }

    repo.rewrite_commits_if_needed(work_dir, &base)?;
    repo.push(work_dir, branch)?;

    let pr = match repo.pr_for_branch(branch) {
        Some(existing) => existing,
        None => {
            let summary = extract_summary(&out).unwrap_or_else(|| item.title.clone());
            let body = pr_body(number, &summary, &repo.style);
            repo.create_pr(
                work_dir,
                branch,
                &base,
                &format!("{} (#{number})", item.title),
                &body,
            )?
        }
    };
    state.pr = Some(pr.url.clone());
    log!("#{number}: PR {}", pr.url);

    let ctx = LoopCtx {
        work_dir: work_dir.to_path_buf(),
        branch: branch.to_string(),
        pr_number: pr.number,
        label: format!("#{number}"),
        subject: number,
        title: item.title.clone(),
        start_round: 1,
        holder: cfg.other(&holder),
        release: Release::Issue(number),
    };
    review_loop(agents, cfg, repo, &ctx, state, ledger)
}

// ---------------------------------------------------------------------------
// Resuming an existing PR
// ---------------------------------------------------------------------------

/// Pick up an existing PR and continue the loop.
///
/// The PR need not have been created by spar. Anything with a branch and a diff
/// can be reviewed, including work a person or a different tool started, which
/// is also the cheapest way to adopt spar: no agent writes a feature from
/// scratch, it only reviews what already exists.
pub fn resume_pr(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    pr_number: i64,
    holder_override: Option<&str>,
) -> IssueRun {
    let failed = |e: SparError| {
        log!("PR #{pr_number} failed: {e}");
        let mut state = IssueRun::new(pr_number, format!("PR #{pr_number}"));
        state.status = Status::Error;
        state.notes.push(e.to_string());
        state
    };

    let pr = match repo.pr_view(pr_number) {
        Ok(pr) => pr,
        Err(e) => return failed(e),
    };

    // A pull request from a fork cannot be pushed to, so the loop that fixes
    // things cannot run on it. Reviewing it is still the useful thing, and it
    // is what a maintainer wants from an outside contribution anyway, so do
    // that rather than refusing.
    if pr.is_cross_repository {
        log!("PR #{pr_number} comes from a fork, reviewing it without changing it");
        return crate::review_only::review_pr(agents, cfg, repo, pr_number, false);
    }

    match resume_inner(agents, cfg, repo, pr, holder_override) {
        Ok(state) => state,
        Err(e) => failed(e),
    }
}

fn resume_inner(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    pr: PrView,
    holder_override: Option<&str>,
) -> Result<IssueRun> {
    let pr_number = pr.number;
    if !pr.is_open() {
        return Err(spar_err!("PR #{pr_number} is {}", pr.state.to_lowercase()));
    }

    let subject = pr
        .closing_issues_references
        .first()
        .map(|r| r.number)
        .unwrap_or(pr_number);

    let saved = repo.read_state(&pr);
    let mut ledger: Ledger = saved.as_ref().map(|s| s.ledger.clone()).unwrap_or_default();
    let start_round = saved.as_ref().map(|s| s.round + 1).unwrap_or(1);

    let default_holder = cfg.other(&cfg.first_implementor);
    let mut holder = holder_override
        .map(str::to_string)
        .or_else(|| saved.as_ref().map(|s| s.next_actor.clone()))
        .unwrap_or_else(|| default_holder.clone());
    if !cfg.has_agent(&holder) {
        log!("state named unknown agent '{holder}', using {default_holder}");
        holder = default_holder;
    }

    match &saved {
        Some(_) => log!(
            "PR #{pr_number}: resuming at round {start_round}, {} settled point(s), next up {holder}",
            ledger.len()
        ),
        None => log!("PR #{pr_number}: no prior spar state, starting fresh with {holder}"),
    }

    let mut state = IssueRun::new(subject, pr.title.clone());
    state.pr = Some(pr.url.clone());
    if let Some(s) = &saved {
        state.filed = s.filed.clone();
    }

    let (work_dir, branch) = repo.worktree_for_pr(&pr)?;
    let ctx = LoopCtx {
        work_dir,
        branch,
        pr_number,
        label: format!("PR #{pr_number}"),
        subject,
        title: pr.title.clone(),
        start_round,
        holder,
        release: Release::Pr(pr_number),
    };

    let outcome = review_loop(agents, cfg, repo, &ctx, &mut state, &mut ledger);
    if let Err(e) = outcome {
        state.status = Status::Error;
        state.notes.push(e.to_string());
        log!("PR #{pr_number} failed: {e}");
    }
    if should_release(cfg, state.status) {
        repo.release_pr_worktree(pr_number);
    }
    Ok(state)
}

// ---------------------------------------------------------------------------
// The loop
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy)]
enum Release {
    Issue(i64),
    Pr(i64),
}

struct LoopCtx {
    work_dir: PathBuf,
    branch: String,
    pr_number: i64,
    label: String,
    subject: i64,
    title: String,
    start_round: u32,
    holder: String,
    release: Release,
}

impl LoopCtx {
    fn release(&self, repo: &Repo) {
        match self.release {
            Release::Issue(n) => repo.worktree_remove(n),
            Release::Pr(n) => repo.release_pr_worktree(n),
        }
    }
}

fn review_loop(
    agents: &[Agent],
    cfg: &Config,
    repo: &Repo,
    ctx: &LoopCtx,
    state: &mut IssueRun,
    ledger: &mut Ledger,
) -> Result<()> {
    let base = cfg.base_branch().to_string();
    let mut holder = ctx.holder.clone();

    // `max_rounds` is a budget for this invocation, not a lifetime cap on the
    // pull request. Running spar again on a PR that already spent its rounds is
    // a deliberate act by a person who has looked at it, so it gets a fresh
    // budget rather than an error telling them to raise a number they cannot
    // see from the outside.
    let (first, last_allowed) = round_window(ctx.start_round, cfg.loop_cfg.max_rounds);
    let mut last_round = first.saturating_sub(1);

    for round in first..=last_allowed {
        last_round = round;
        state.rounds = round;
        let reviewer = agent::find(agents, &holder)?;
        let effort = cfg.effort_for_round(&reviewer.spec, round);
        log!(
            "{}: round {round}, {holder} reviewing ({})",
            ctx.label,
            effort.as_deref().unwrap_or("default effort")
        );

        let prompt = REVIEW_PROMPT
            .replace("{base}", &base)
            .replace("{number}", &ctx.subject.to_string())
            .replace("{title}", &ctx.title)
            .replace("{settled}", &settled_block(ledger));
        let review: Review = reviewer.review(
            &base,
            &prompt,
            &schema::review(),
            &ctx.work_dir,
            effort.as_deref(),
        )?;

        let blocking: Vec<Finding> = review
            .findings
            .iter()
            .filter(|f| f.blocks())
            .cloned()
            .collect();

        if repo.style.pr_comments == PrComments::Rounds {
            if let Err(e) = repo.comment_pr(
                ctx.pr_number,
                &review_comment(&holder, round, &review, &repo.style),
            ) {
                logdim!("could not post the review comment: {e}");
            }
        }

        // Filed every round, not only on approval: a run that escalates or runs
        // out of rounds would otherwise drop these on the floor. Filing
        // deduplicates by title, so repeats across rounds are free.
        file_out_of_scope(repo, &review.findings, ctx.subject, state);
        file_nonblocking(
            repo,
            &review.findings,
            ctx.subject,
            state,
            cfg.loop_cfg.file_nits,
        );

        if check_relitigation(ledger, &blocking, state) {
            state.status = Status::Escalated;
            post_outcome(
                repo,
                ctx.pr_number,
                state,
                ledger,
                Ending::Deadlocked(&blocking),
            );
            persist(
                repo,
                ctx.pr_number,
                state,
                ledger,
                round,
                &cfg.other(&holder),
            );
            return Ok(());
        }

        if blocking.is_empty() {
            state.status = Status::Approved;
            post_outcome(repo, ctx.pr_number, state, ledger, Ending::Approved);
            persist(
                repo,
                ctx.pr_number,
                state,
                ledger,
                round,
                &cfg.other(&holder),
            );
            if cfg.loop_cfg.auto_merge {
                // Release the worktree first. `gh pr merge --delete-branch`
                // fails if anything still has the branch checked out, and it
                // fails *after* merging, so the merge lands while the command
                // reports failure.
                ctx.release(repo);
                repo.merge_pr(ctx.pr_number)?;
                state.status = Status::Merged;
                repo.clear_state(ctx.pr_number); // nothing left to resume
                log!("{}: merged", ctx.label);
            } else {
                log!("{}: approved, awaiting human merge", ctx.label);
            }
            return Ok(());
        }

        if review.next_action == NextAction::FixMyself {
            log!("{}: {holder} fixing its own findings", ctx.label);
            let prompt = FIX_PROMPT.replace("{findings}", &findings_for_prompt(&blocking));
            reviewer.ask(&prompt, &ctx.work_dir, effort.as_deref())?;
        } else {
            let author_name = cfg.other(&holder);
            let author = agent::find(agents, &author_name)?;
            log!(
                "{}: handing {} finding(s) to {author_name}",
                ctx.label,
                blocking.len()
            );
            let prompt = RESPOND_PROMPT
                .replace("{number}", &ctx.subject.to_string())
                .replace("{findings}", &findings_for_prompt(&blocking));
            let response: ResponseDoc = author.ask_json(
                &prompt,
                &schema::response(),
                &ctx.work_dir,
                cfg.effort_for_round(&author.spec, round).as_deref(),
            )?;
            apply_dispositions(
                repo,
                &response,
                &blocking,
                ledger,
                state,
                round,
                ctx.subject,
                ctx.pr_number,
                &author_name,
            );
        }

        repo.rewrite_commits_if_needed(&ctx.work_dir, &base)?;
        repo.push(&ctx.work_dir, &ctx.branch)?;
        holder = cfg.other(&holder);
        persist(repo, ctx.pr_number, state, ledger, round, &holder);
    }

    state.status = Status::Escalated;
    state
        .notes
        .push(exhausted_note(ctx.start_round, last_round));
    post_outcome(repo, ctx.pr_number, state, ledger, Ending::OutOfRounds);
    persist(repo, ctx.pr_number, state, ledger, last_round, &holder);
    Ok(())
}

/// The inclusive range of round numbers this invocation will work through.
///
/// Round numbers keep counting up across sessions so the ledger and the PR
/// history stay coherent, while the budget resets each time a person chooses to
/// run spar again.
fn round_window(start_round: u32, budget: u32) -> (u32, u32) {
    (start_round, start_round + budget.saturating_sub(1))
}

/// How many rounds this invocation spent, and how many the PR has seen in
/// total. A resumed PR that stops at round 8 did not have 8 rounds of budget,
/// and saying so would misreport both the cost and the history.
fn spent(start_round: u32, last_round: u32) -> (u32, u32) {
    (last_round.saturating_sub(start_round) + 1, last_round)
}

fn exhausted_note(start_round: u32, last_round: u32) -> String {
    let (this_run, total) = spent(start_round, last_round);
    if this_run == total {
        format!("no convergence after {this_run} rounds")
    } else {
        format!("no convergence after {this_run} more rounds ({total} in total)")
    }
}

fn persist(
    repo: &Repo,
    pr_number: i64,
    state: &IssueRun,
    ledger: &Ledger,
    round: u32,
    next_actor: &str,
) {
    let payload = PersistedState {
        version: STATE_VERSION,
        round,
        next_actor: next_actor.to_string(),
        status: state.status,
        ledger: ledger.clone(),
        filed: state.filed.clone(),
    };
    if let Err(e) = repo.write_state(pr_number, &payload) {
        logdim!("could not persist state for PR #{pr_number}: {e}");
    }
}

// ---------------------------------------------------------------------------
// The ledger
// ---------------------------------------------------------------------------

fn settled_block(ledger: &Ledger) -> String {
    if ledger.is_empty() {
        return String::new();
    }
    let lines: Vec<String> = ledger
        .values()
        .map(|e| format!("- {}: refuted because {}", e.title, e.reasoning))
        .collect();
    format!(
        "\nThe following points were already raised and refuted. Treat them as settled. Do not \
         raise them again unless you have new evidence:\n{}",
        lines.join("\n")
    )
}

/// A point refuted and then raised twice more goes to a person rather than
/// looping forever.
fn check_relitigation(ledger: &mut Ledger, blocking: &[Finding], state: &mut IssueRun) -> bool {
    let mut escalate = false;
    for finding in blocking {
        let key = finding_key(&finding.title, &finding.file);
        if let Some(entry) = ledger.get_mut(&key) {
            entry.reraised += 1;
            if entry.reraised >= 2 {
                state.notes.push(format!(
                    "'{}' was refuted and re-raised twice; escalating.",
                    finding.title
                ));
                escalate = true;
            }
        }
    }
    escalate
}

fn normalise(text: &str) -> String {
    text.to_lowercase()
        .chars()
        .filter(|c| c.is_ascii_alphanumeric() || c.is_whitespace())
        .collect::<String>()
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ")
}

/// Match a disposition back to the finding it answers, so the ledger key it
/// records is the same key the next round's finding will hash to. Without this
/// the re-litigation guard is dead code for any finding that names a file.
/// Whether two titles name the same point, ignoring wording noise.
pub(crate) fn same_point(a: &str, b: &str) -> bool {
    normalise(a) == normalise(b)
}

fn matching_finding<'a>(findings: &'a [Finding], title: &str) -> Option<&'a Finding> {
    let wanted = normalise(title);
    findings.iter().find(|f| normalise(&f.title) == wanted)
}

#[allow(clippy::too_many_arguments)]
fn apply_dispositions(
    repo: &Repo,
    response: &ResponseDoc,
    blocking: &[Finding],
    ledger: &mut Ledger,
    state: &mut IssueRun,
    round: u32,
    subject: i64,
    pr_number: i64,
    author: &str,
) {
    let mut fixed = Vec::new();
    let mut refuted = Vec::new();
    let mut filed = Vec::new();

    for d in &response.dispositions {
        let source = matching_finding(blocking, &d.title);
        let file = source
            .map(|f| f.file.clone())
            .filter(|f| !f.trim().is_empty())
            .unwrap_or_else(|| d.file.clone());
        // Hash the *reviewer's* wording, not the author's. `matching_finding`
        // is deliberately looser than `finding_key` (it ignores hyphens, dots,
        // slashes, and underscores), so an author who writes "multibyte" where
        // the reviewer wrote "multi-byte" matches here and yet hashes to a
        // different key. Recording that key means next round's lookup misses
        // and the re-litigation guard tracks nothing at all.
        let canonical = source.map(|f| f.title.as_str()).unwrap_or(d.title.as_str());
        let title = style::title(canonical, &repo.style);

        match d.action {
            Action::Refuted => {
                let reasoning = style::summary(&d.reasoning, &repo.style);
                ledger.insert(
                    finding_key(canonical, &file),
                    LedgerEntry {
                        title: title.clone(),
                        file: file.clone(),
                        reasoning: reasoning.clone(),
                        round,
                        reraised: 0,
                    },
                );
                state.disputes.push(Dispute {
                    title: title.clone(),
                    reasoning: reasoning.clone(),
                });
                refuted.push(format!("{title}. {reasoning}"));
            }
            Action::FiledIssue => {
                let new_title = d
                    .new_issue_title
                    .clone()
                    .filter(|t| !t.trim().is_empty())
                    .unwrap_or_else(|| d.title.clone());
                let new_body = d
                    .new_issue_body
                    .clone()
                    .filter(|b| !b.trim().is_empty())
                    .unwrap_or_else(|| d.reasoning.clone());
                if let Some(url) = file_followup(repo, &new_title, &new_body, subject) {
                    state.filed.push(url.clone());
                    filed.push(url);
                }
            }
            Action::Fixed => fixed.push(title),
        }
    }

    if repo.style.pr_comments == PrComments::Rounds {
        let comment = disposition_comment(author, response, &fixed, &refuted, &filed, &repo.style);
        if let Some(text) = comment {
            if let Err(e) = repo.comment_pr(pr_number, &text) {
                logdim!("could not post the disposition comment: {e}");
            }
        }
    }
}

// ---------------------------------------------------------------------------
// Follow-ups
// ---------------------------------------------------------------------------

/// Record a finding that is real but out of scope for this PR.
///
/// On your own repository an issue is the right home. On a large repository
/// that is not yours it is somebody else's notification and somebody else's
/// triage queue, so `local` keeps the same information in `.spar/followups.md`
/// and `none` drops it.
fn file_followup(repo: &Repo, title: &str, body: &str, source: i64) -> Option<String> {
    if repo.followups == Followups::None {
        return None;
    }
    // The exact string that will land on GitHub. Searching for anything else
    // means the duplicate check can never hit, and every round files another
    // copy of the same follow-up.
    let title = match repo.clean_title(title) {
        Ok(title) => title,
        Err(e) => {
            logdim!("could not clean a follow-up title: {e}");
            return None;
        }
    };
    if title.trim().is_empty() {
        return None;
    }
    let body = format!(
        "{}\n\nFound while working on #{source}.",
        style::body(body, &repo.style)
    );

    if repo.followups == Followups::Local {
        return repo.append_local_followup(&title, &body);
    }
    if let Some(existing) = repo.find_issue_by_title(&title) {
        logdim!("follow-up already exists: {existing}");
        return None;
    }
    match repo.create_issue(&title, &body) {
        Ok(url) => Some(url),
        Err(e) => {
            logdim!("could not file a follow-up for '{title}': {e}");
            None
        }
    }
}

fn file_out_of_scope(repo: &Repo, findings: &[Finding], subject: i64, state: &mut IssueRun) {
    for finding in findings.iter().filter(|f| !f.in_scope) {
        if let Some(url) = file_followup(repo, &finding.title, &finding.detail, subject) {
            state.filed.push(url);
        }
    }
}

/// Non-blocking findings become follow-ups so they do not gate the merge.
///
/// Nits are excluded by default. On a shared repository a filed nit is somebody
/// else's notification and somebody else's triage queue: an early run on a
/// production codebase opened an issue titled "Log wording". Worth saying in
/// the PR thread, not worth an issue.
fn file_nonblocking(
    repo: &Repo,
    findings: &[Finding],
    subject: i64,
    state: &mut IssueRun,
    file_nits: bool,
) {
    for finding in findings {
        let keep = match finding.severity {
            Severity::NonBlocking => true,
            Severity::Nit => file_nits,
            Severity::Blocking => false,
        };
        if !keep || !finding.in_scope {
            continue;
        }
        if let Some(url) = file_followup(repo, &finding.title, &finding.detail, subject) {
            state.filed.push(url);
        }
    }
}

// ---------------------------------------------------------------------------
// What a human actually reads
// ---------------------------------------------------------------------------
//
// spar composes every comment itself from structured fields, rather than
// forwarding whatever prose a model produced. That is the only reliable way to
// keep a PR thread readable: the model supplies facts, the harness supplies the
// shape, and each field is held to a budget on the way out.

fn bullets(lines: &[String]) -> String {
    lines
        .iter()
        .map(|l| format!("- {l}"))
        .collect::<Vec<_>>()
        .join("\n")
}

fn located(finding: &Finding, style: &Style) -> String {
    let title = style::title(&finding.title, style);
    match finding.where_at() {
        "general" => title,
        file => format!("{title} ({file})"),
    }
}

/// How the run ended, which is the only thing about the run a reader needs.
pub enum Ending<'a> {
    /// Nothing blocks a merge.
    Approved,
    /// The round budget ran out. The last round's fixes were pushed but never
    /// reviewed, which is the part a maintainer has to know.
    OutOfRounds,
    /// A point was refuted and raised again anyway. Nobody is going to break
    /// the tie but a person.
    Deadlocked(&'a [Finding]),
}

/// Post the one comment a run leaves behind, if it has anything to say.
///
/// Everything spar used to write here was an account of its own working: which
/// agent spoke, which round it was, how many findings of each severity, that it
/// had stopped. None of that is about the code. Worse, the running commentary
/// could contradict itself, ending a thread with "5 fixed" immediately followed
/// by "no convergence", which reads as a failure rather than as fixes nobody
/// has checked yet.
///
/// So the loop is silent and this says what is left: what is unresolved, what
/// was argued down, and where the follow-ups went.
pub fn post_outcome(
    repo: &Repo,
    pr_number: i64,
    state: &IssueRun,
    ledger: &Ledger,
    ending: Ending<'_>,
) {
    if repo.style.pr_comments != PrComments::Outcome {
        return;
    }
    let Some(text) = outcome_comment(state, ledger, &ending, &repo.style) else {
        return;
    };
    if let Err(e) = repo.comment_pr(pr_number, &text) {
        logdim!("could not post the outcome comment: {e}");
    }
}

/// Why a point was refuted: this run's disputes first, then the ledger, which
/// is what survives across a resume.
fn refutation_of(finding: &Finding, state: &IssueRun, ledger: &Ledger) -> Option<String> {
    if let Some(d) = state
        .disputes
        .iter()
        .find(|d| same_point(&d.title, &finding.title))
    {
        if !d.reasoning.trim().is_empty() {
            return Some(d.reasoning.clone());
        }
    }
    ledger
        .get(&finding_key(&finding.title, &finding.file))
        .map(|entry| entry.reasoning.clone())
        .filter(|r| !r.trim().is_empty())
}

/// `#123` from a filed issue URL, falling back to the URL when it does not look
/// like one. Shorter, and GitHub renders it as a link either way.
fn as_reference(url: &str) -> String {
    match url.rsplit('/').next().and_then(|n| n.parse::<u64>().ok()) {
        Some(number) => format!("#{number}"),
        None => url.to_string(),
    }
}

pub fn outcome_comment(
    state: &IssueRun,
    ledger: &Ledger,
    ending: &Ending<'_>,
    style: &Style,
) -> Option<String> {
    let mut out: Vec<String> = Vec::new();
    // Points rendered in the deadlock block, so the refutation list below does
    // not print the same title a second time.
    let mut already: Vec<String> = Vec::new();

    match ending {
        Ending::Approved => {
            if state.disputes.is_empty() && state.filed.is_empty() {
                // A clean approval with nothing outstanding needs no comment.
                // The absence of objections is the message.
                return None;
            }
            out.push("Reviewed, nothing blocking a merge.".into());
        }
        Ending::OutOfRounds => out.push(
            "Not signed off: the last round of fixes was pushed but has not been reviewed.".into(),
        ),
        Ending::Deadlocked(points) => {
            // Rendered once, with the argument attached. A deadlocked point is
            // by definition one that was refuted earlier, so the reasoning is
            // the whole reason a person is being asked to look. On a resumed
            // run `state.disputes` is empty (only `filed` is restored), so the
            // ledger is the only place that argument survives.
            let lines: Vec<String> = points
                .iter()
                .map(|f| {
                    let where_at = match f.where_at() {
                        "general" => String::new(),
                        file => format!(" ({file})"),
                    };
                    let title = style::title(&f.title, style);
                    already.push(title.clone());
                    match refutation_of(f, state, ledger) {
                        Some(reason) => format!(
                            "{title}{where_at}. Refuted as: {}",
                            style::summary(&reason, style)
                        ),
                        None => format!("{title}{where_at}"),
                    }
                })
                .collect();
            out.push("Needs your decision. The reviewers could not settle this:".into());
            out.push(bullets(&lines));
        }
    }

    let disputes: Vec<&crate::model::Dispute> = state
        .disputes
        .iter()
        .filter(|d| !already.iter().any(|t| same_point(t, &d.title)))
        .collect();
    if !disputes.is_empty() {
        // The one thing invisible anywhere else. The diff shows what was fixed;
        // nothing shows what was argued down, or why.
        let lines: Vec<String> = disputes
            .iter()
            .map(|d| {
                format!(
                    "{}. {}",
                    style::title(&d.title, style),
                    style::sentence(&d.reasoning, style)
                )
            })
            .collect();
        out.push(format!("Raised and refuted:\n{}", bullets(&lines)));
    }

    if !state.filed.is_empty() {
        let refs: Vec<String> = state.filed.iter().map(|u| as_reference(u)).collect();
        out.push(format!("Filed separately: {}", refs.join(", ")));
    }

    Some(out.join("\n\n"))
}

/// The PR body: what it closes, one sentence of what changed, and the diffstat.
/// GitHub already shows the file list, so repeating it is noise.
pub fn pr_body(issue: i64, summary: &str, style: &Style) -> String {
    let mut parts = vec![format!("Closes #{issue}")];
    let summary = style::summary(summary, style);
    if !summary.is_empty() {
        parts.push(summary);
    }
    parts.join("\n\n")
}

/// The last `SUMMARY:` line an implementor emitted, if it left one.
pub fn extract_summary(text: &str) -> Option<String> {
    text.lines()
        .rev()
        .find_map(|line| {
            let trimmed = line.trim().trim_start_matches(['*', '#', '-', ' ']);
            trimmed
                .strip_prefix("SUMMARY:")
                .or_else(|| trimmed.strip_prefix("Summary:"))
        })
        .map(|s| {
            s.trim()
                .trim_start_matches(['*', '_', ':', ' '])
                .trim()
                .to_string()
        })
        .filter(|s| !s.is_empty())
}

/// One review, as a reviewer would write it if they were in a hurry: a count
/// line, a sentence, and one bullet per finding. Only blocking findings carry
/// their detail, because only those are something the author has to act on now.
pub fn review_comment(holder: &str, round: u32, review: &Review, style: &Style) -> String {
    let by = |severity: Severity| -> Vec<&Finding> {
        review
            .findings
            .iter()
            .filter(|f| f.severity == severity && f.in_scope)
            .collect()
    };
    let blocking = by(Severity::Blocking);
    let non_blocking = by(Severity::NonBlocking);
    let nits = by(Severity::Nit);
    let out_of_scope: Vec<&Finding> = review.findings.iter().filter(|f| !f.in_scope).collect();

    let mut counts = Vec::new();
    if !blocking.is_empty() {
        counts.push(format!("{} blocking", blocking.len()));
    }
    if !non_blocking.is_empty() {
        counts.push(format!("{} non-blocking", non_blocking.len()));
    }
    if !nits.is_empty() {
        counts.push(format!("{} nit", nits.len()));
    }
    if !out_of_scope.is_empty() {
        counts.push(format!("{} out of scope", out_of_scope.len()));
    }
    let headline = if counts.is_empty() {
        "no findings".to_string()
    } else {
        counts.join(", ")
    };

    let _ = (holder, round, headline);
    let mut out = Vec::new();
    let summary = style::summary(&review.summary, style);
    if !summary.is_empty() {
        out.push(summary);
    }

    if !blocking.is_empty() {
        let lines: Vec<String> = blocking
            .iter()
            .map(|f| {
                let detail = style::detail(&f.detail, style);
                if detail.is_empty() {
                    located(f, style)
                } else {
                    format!("{}. {detail}", located(f, style))
                }
            })
            .collect();
        out.push(format!("blocking\n{}", bullets(&lines)));
    }

    // Everything below is filed as a follow-up, so the thread only needs the
    // title: the detail lives on the issue where it can be acted on.
    for (label, group) in [
        ("non-blocking", &non_blocking),
        ("nits", &nits),
        ("out of scope", &out_of_scope),
    ] {
        if group.is_empty() {
            continue;
        }
        let lines: Vec<String> = group.iter().map(|f| located(f, style)).collect();
        out.push(format!("{label}\n{}", bullets(&lines)));
    }

    out.join("\n\n")
}

/// One response to a review. Refutations carry their reasoning because that is
/// the whole argument; fixes are a list of titles because the diff says the
/// rest.
pub fn disposition_comment(
    author: &str,
    response: &ResponseDoc,
    fixed: &[String],
    refuted: &[String],
    filed: &[String],
    style: &Style,
) -> Option<String> {
    if fixed.is_empty() && refuted.is_empty() && filed.is_empty() {
        return None;
    }
    let mut counts = Vec::new();
    if !fixed.is_empty() {
        counts.push(format!("{} fixed", fixed.len()));
    }
    if !refuted.is_empty() {
        counts.push(format!("{} refuted", refuted.len()));
    }
    if !filed.is_empty() {
        counts.push(format!("{} filed", filed.len()));
    }

    let _ = (author, counts);
    let mut out = Vec::new();
    let summary = style::summary(&response.summary, style);
    if !summary.is_empty() {
        out.push(summary);
    }
    if !refuted.is_empty() {
        out.push(format!("refuted\n{}", bullets(refuted)));
    }
    if !fixed.is_empty() {
        out.push(format!("fixed\n{}", bullets(fixed)));
    }
    if !filed.is_empty() {
        out.push(format!("filed\n{}", bullets(filed)));
    }
    Some(out.join("\n\n"))
}

/// What is posted on an issue both agents declined.
/// What is posted on an issue both reviewers declined.
///
/// Just the reasons. GitHub already shows that it was closed as not planned,
/// and which model held which opinion is a fact about the run rather than about
/// the issue. Duplicates are collapsed, since two reviewers reaching the same
/// conclusion often reach it in the same words.
pub fn skip_comment(item: &SkippedItem, style: &Style) -> String {
    let mut lines: Vec<String> = Vec::new();
    for reason in item.reasons.values() {
        let text = style::sentence(reason, style);
        if !text.is_empty() && !lines.iter().any(|seen| same_point(seen, &text)) {
            lines.push(text);
        }
    }
    bullets(&lines)
}

/// Findings as a model should see them: full detail, since this one is not for
/// a human to read.
pub(crate) fn findings_for_prompt(findings: &[Finding]) -> String {
    if findings.is_empty() {
        return "(none)".to_string();
    }
    findings
        .iter()
        .map(|f| {
            let scope = if f.in_scope { "" } else { " [out of scope]" };
            format!(
                "- [{}]{scope} {} ({})\n  {}",
                f.severity,
                f.title,
                f.where_at(),
                f.detail
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

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

    fn style() -> Style {
        Style::default()
    }

    fn finding(severity: &str, title: &str, detail: &str, file: &str, in_scope: bool) -> Finding {
        Finding {
            severity: Severity::parse_lenient(severity).unwrap(),
            title: title.into(),
            detail: detail.into(),
            file: file.into(),
            in_scope,
        }
    }

    fn review(summary: &str, findings: Vec<Finding>) -> Review {
        Review {
            verdict: Verdict::Approve,
            next_action: NextAction::Merge,
            summary: summary.into(),
            findings,
        }
    }

    // -- worktree release ------------------------------------------------

    fn cfg_with(worktrees: bool, keep: bool) -> Config {
        let text = "[agents.a]\ncommand = [\"x\"]\n[agents.b]\ncommand = [\"y\"]\n";
        let mut cfg = crate::config::parse(text).unwrap();
        cfg.loop_cfg.worktrees = worktrees;
        cfg.loop_cfg.keep_worktrees = keep;
        cfg
    }

    #[test]
    fn a_worktree_is_released_on_every_finished_outcome() {
        let cfg = cfg_with(true, false);
        for status in [Status::Approved, Status::Merged, Status::Abandoned] {
            assert!(should_release(&cfg, status), "{status}");
        }
    }

    /// Releasing only on "merged" leaked one worktree per run, because
    /// auto_merge is off by default and runs end at "approved".
    #[test]
    fn a_worktree_is_kept_only_where_a_human_has_to_look() {
        let cfg = cfg_with(true, false);
        assert!(!should_release(&cfg, Status::Escalated));
        assert!(!should_release(&cfg, Status::Error));
    }

    #[test]
    fn the_keep_flag_overrides_everything() {
        assert!(!should_release(&cfg_with(true, true), Status::Approved));
    }

    #[test]
    fn nothing_is_released_when_worktrees_are_off() {
        assert!(!should_release(&cfg_with(false, false), Status::Approved));
    }

    // -- round budget ----------------------------------------------------

    /// A fresh PR gets rounds 1 through max_rounds.
    #[test]
    fn a_fresh_run_starts_at_one() {
        assert_eq!((1, 3), round_window(1, 3));
        assert_eq!((1, 5), round_window(1, 5));
    }

    /// The budget is per invocation, not a lifetime cap. Running spar again on
    /// a PR that already spent five rounds gives it five more, because a person
    /// looked at it and chose to.
    #[test]
    fn a_resumed_run_gets_a_full_fresh_budget() {
        assert_eq!((6, 10), round_window(6, 5));
        assert_eq!((11, 13), round_window(11, 3));
    }

    #[test]
    fn a_budget_of_one_is_a_single_round() {
        assert_eq!((6, 6), round_window(6, 1));
    }

    #[test]
    fn round_numbers_keep_counting_across_sessions() {
        // Three sessions of three rounds each land on 1..3, 4..6, 7..9.
        let mut start = 1;
        let mut seen = Vec::new();
        for _ in 0..3 {
            let (first, last) = round_window(start, 3);
            seen.push((first, last));
            start = last + 1;
        }
        assert_eq!(vec![(1, 3), (4, 6), (7, 9)], seen);
    }

    // -- the ledger ------------------------------------------------------

    fn ledger_with(title: &str, file: &str) -> Ledger {
        let mut ledger = Ledger::new();
        ledger.insert(
            finding_key(title, file),
            LedgerEntry {
                title: title.into(),
                file: file.into(),
                reasoning: "no".into(),
                round: 1,
                reraised: 0,
            },
        );
        ledger
    }

    #[test]
    fn a_point_refuted_and_re_raised_twice_escalates() {
        let mut ledger = ledger_with("nit about naming", "a.rs");
        let mut state = IssueRun::new(1, "t");
        let blocking = vec![finding("blocking", "nit about naming", "d", "a.rs", true)];
        assert!(!check_relitigation(&mut ledger, &blocking, &mut state));
        assert!(check_relitigation(&mut ledger, &blocking, &mut state));
    }

    #[test]
    fn an_untracked_finding_does_not_escalate() {
        let mut state = IssueRun::new(1, "t");
        let blocking = vec![finding("blocking", "brand new", "d", "a.rs", true)];
        assert!(!check_relitigation(
            &mut Ledger::new(),
            &blocking,
            &mut state
        ));
    }

    /// The key a refutation records has to be the key the next round's finding
    /// hashes to. Recording it without the file made the guard dead code for
    /// every finding that named one, which is nearly all of them.
    #[test]
    fn a_refutation_lands_on_the_key_the_next_round_will_look_up() {
        let blocking = vec![finding("blocking", "Unbounded loop", "d", "src/x.rs", true)];
        let recorded = finding_key(&blocking[0].title, &blocking[0].file);

        let matched = matching_finding(&blocking, "unbounded loop!").expect("should match");
        assert_eq!(recorded, finding_key("unbounded loop!", &matched.file));
    }

    /// `matching_finding` ignores hyphens, dots, slashes, and underscores;
    /// `finding_key` keeps them. A disposition that differs only in those
    /// characters therefore matches its finding while hashing to a different
    /// key, so recording the author's wording made the guard track nothing.
    #[test]
    fn the_ledger_key_uses_the_reviewers_wording_not_the_authors() {
        let findings = vec![finding(
            "blocking",
            "Panic on multi-byte input",
            "d",
            "src/style.rs",
            true,
        )];
        let reworded = "Panic on multibyte input";

        let source = matching_finding(&findings, reworded).expect("still matches");
        assert_ne!(
            finding_key(reworded, &source.file),
            finding_key(&source.title, &source.file),
            "the two spellings must genuinely hash apart, or this test proves nothing"
        );

        // What apply_dispositions records, and what the next round looks up.
        let recorded = finding_key(&source.title, &source.file);
        let looked_up = finding_key(&findings[0].title, &findings[0].file);
        assert_eq!(recorded, looked_up);
    }

    #[test]
    fn a_disposition_matches_its_finding_despite_wording_noise() {
        let findings = vec![finding(
            "blocking",
            "Unbounded loop!",
            "d",
            "src/x.rs",
            true,
        )];
        assert!(matching_finding(&findings, "unbounded loop").is_some());
        assert!(matching_finding(&findings, "something else").is_none());
    }

    #[test]
    fn the_settled_block_is_empty_when_nothing_is_settled() {
        assert_eq!("", settled_block(&Ledger::new()));
    }

    #[test]
    fn the_settled_block_names_each_refutation() {
        let block = settled_block(&ledger_with("a point", "x.rs"));
        assert!(block.contains("a point"));
        assert!(block.contains("settled"));
    }

    // -- brevity ---------------------------------------------------------

    #[test]
    /// No agent name, no round number, and no count of things listed below.
    /// The reader wants the review, not an account of who produced it.
    fn a_clean_review_is_just_the_verdict() {
        let text = review_comment("codex", 1, &review("Looks correct.", vec![]), &style());
        assert_eq!("Looks correct.", text);
    }

    #[test]
    fn a_review_leads_with_the_counts() {
        let text = review_comment(
            "codex",
            2,
            &review(
                "One real problem.",
                vec![
                    finding(
                        "blocking",
                        "Loop never terminates",
                        "Confirmed by running it.",
                        "src/a.rs",
                        true,
                    ),
                    finding("non-blocking", "Name is vague", "d", "src/b.rs", true),
                    finding("nit", "Log wording", "d", "", true),
                ],
            ),
            &style(),
        );
        assert!(text.starts_with("One real problem."), "{text}");
        assert!(!text.contains("codex"), "no agent name: {text}");
        assert!(!text.contains("round 2"), "no round number: {text}");
    }

    /// Only blocking findings carry their detail into the thread. Everything
    /// else is filed, and the detail belongs on the issue.
    #[test]
    fn only_blocking_findings_carry_their_detail() {
        let text = review_comment(
            "codex",
            1,
            &review(
                "s",
                vec![
                    finding("blocking", "Loop", "BLOCKING DETAIL", "a.rs", true),
                    finding("non-blocking", "Name", "NONBLOCKING DETAIL", "b.rs", true),
                ],
            ),
            &style(),
        );
        assert!(text.contains("BLOCKING DETAIL"), "{text}");
        assert!(!text.contains("NONBLOCKING DETAIL"), "{text}");
    }

    #[test]
    fn a_verbose_model_is_clipped_not_forwarded() {
        let long_summary = "This is a very thorough summary. ".repeat(40);
        let long_detail = "Here is an extremely long explanation. ".repeat(40);
        let text = review_comment(
            "codex",
            1,
            &review(
                &long_summary,
                vec![finding("blocking", "T", &long_detail, "a.rs", true)],
            ),
            &style(),
        );
        assert!(
            text.len() < 900,
            "review comment was {} chars:\n{text}",
            text.len()
        );
    }

    #[test]
    fn a_general_finding_has_no_empty_parenthesis() {
        let text = review_comment(
            "codex",
            1,
            &review("s", vec![finding("blocking", "Something", "d", "", true)]),
            &style(),
        );
        assert!(!text.contains("()"), "{text}");
        assert!(!text.contains("(general)"), "{text}");
    }

    #[test]
    fn out_of_scope_findings_are_counted_separately() {
        let text = review_comment(
            "codex",
            1,
            &review(
                "s",
                vec![finding("blocking", "Old bug", "d", "a.rs", false)],
            ),
            &style(),
        );
        assert!(text.contains("out of scope"), "{text}");
        assert!(text.contains("Old bug"), "{text}");
    }

    #[test]
    fn a_disposition_comment_leads_with_counts_and_keeps_refutations() {
        let response = ResponseDoc {
            summary: "Two of three were right.".into(),
            dispositions: vec![],
        };
        let text = disposition_comment(
            "claude",
            &response,
            &["Fixed thing".to_string()],
            &["Wrong thing. Because the caller already checks.".to_string()],
            &[],
            &style(),
        )
        .unwrap();
        assert!(text.starts_with("Two of three were right."), "{text}");
        assert!(!text.contains("claude"), "no agent name: {text}");
        assert!(
            text.contains("Because the caller already checks."),
            "{text}"
        );
    }

    #[test]
    fn an_empty_disposition_comment_is_not_posted() {
        let response = ResponseDoc {
            summary: "s".into(),
            dispositions: vec![],
        };
        assert!(disposition_comment("claude", &response, &[], &[], &[], &style()).is_none());
    }

    #[test]
    /// Two parts, not three. GitHub renders the file count and the plus and
    /// minus figures in the header, immediately above whatever spar writes.
    fn a_pr_body_is_what_it_closes_and_what_changed() {
        let body = pr_body(42, "Retry on a 429 instead of failing.", &style());
        assert_eq!("Closes #42\n\nRetry on a 429 instead of failing.", body);
    }

    #[test]
    fn a_pr_body_survives_a_missing_summary_and_diffstat() {
        assert_eq!("Closes #7", pr_body(7, "", &style()));
    }

    #[test]
    fn the_summary_line_is_lifted_out_of_the_final_message() {
        let out = "I did some work.\n\nSUMMARY: Retry on a 429 instead of failing.\n";
        assert_eq!(
            Some("Retry on a 429 instead of failing.".to_string()),
            extract_summary(out)
        );
    }

    #[test]
    fn a_decorated_summary_line_still_parses() {
        assert_eq!(
            Some("Did a thing.".to_string()),
            extract_summary("**SUMMARY:** Did a thing.")
        );
    }

    #[test]
    fn a_missing_summary_line_is_none() {
        assert_eq!(None, extract_summary("no marker here"));
    }

    #[test]
    fn the_last_summary_line_wins() {
        let out = "SUMMARY: first draft\nmore work\nSUMMARY: final answer";
        assert_eq!(Some("final answer".to_string()), extract_summary(out));
    }

    #[test]
    fn a_skip_comment_is_only_the_reasoning() {
        let item = SkippedItem {
            issue: 3,
            title: "t".into(),
            reasons: [
                ("claude".to_string(), "Already fixed in 1.2.".to_string()),
                ("codex".to_string(), "Duplicate of #2.".to_string()),
            ]
            .into_iter()
            .collect(),
        };
        let text = skip_comment(&item, &style());
        assert!(text.contains("Already fixed in 1.2."), "{text}");
        assert!(text.contains("Duplicate of #2."), "{text}");
        assert!(
            !text.contains("claude") && !text.contains("codex"),
            "{text}"
        );
        assert!(!text.to_lowercase().contains("not scheduled"), "{text}");
        assert!(text.lines().count() <= 3, "{text}");
    }

    #[test]
    fn findings_for_a_model_keep_full_detail() {
        let long = "x".repeat(2000);
        let text = findings_for_prompt(&[finding("blocking", "T", &long, "a.rs", true)]);
        assert!(
            text.contains(&long),
            "a model needs the whole finding, only humans need brevity"
        );
    }

    #[test]
    fn findings_for_a_model_are_never_empty() {
        assert_eq!("(none)", findings_for_prompt(&[]));
    }
}

#[cfg(test)]
mod outcome_tests {
    use super::*;
    use crate::model::{Dispute, Severity};

    fn style() -> Style {
        Style::default()
    }

    fn state_with(disputes: Vec<(&str, &str)>, filed: Vec<&str>) -> IssueRun {
        let mut s = IssueRun::new(482, "t");
        s.disputes = disputes
            .into_iter()
            .map(|(title, reasoning)| Dispute {
                title: title.into(),
                reasoning: reasoning.into(),
            })
            .collect();
        s.filed = filed.into_iter().map(String::from).collect();
        s
    }

    fn finding(title: &str, file: &str) -> Finding {
        Finding {
            severity: Severity::Blocking,
            title: title.into(),
            detail: "d".into(),
            file: file.into(),
            in_scope: true,
        }
    }

    /// The absence of objections is the message. A PR that reviewed cleanly and
    /// filed nothing should leave no trace in the thread at all.
    #[test]
    fn a_clean_approval_says_nothing() {
        let state = state_with(vec![], vec![]);
        assert!(outcome_comment(&state, &Ledger::new(), &Ending::Approved, &style()).is_none());
    }

    #[test]
    fn an_approval_that_filed_follow_ups_links_them() {
        let state = state_with(
            vec![],
            vec![
                "https://github.com/you/thing/issues/485",
                "https://github.com/you/thing/issues/486",
            ],
        );
        let text = outcome_comment(&state, &Ledger::new(), &Ending::Approved, &style()).unwrap();
        assert!(text.contains("Filed separately: #485, #486"), "{text}");
    }

    /// The real PR ended with "5 fixed" followed by "no convergence", which
    /// reads as a contradiction. What a maintainer needs is that the fixes went
    /// in and nobody checked them.
    #[test]
    fn running_out_of_rounds_says_what_that_means_for_the_reader() {
        let state = state_with(vec![], vec![]);
        let text = outcome_comment(&state, &Ledger::new(), &Ending::OutOfRounds, &style()).unwrap();
        assert!(text.contains("has not been reviewed"), "{text}");
        assert!(
            !text.to_lowercase().contains("round 3"),
            "no round numbers: {text}"
        );
        assert!(!text.to_lowercase().contains("convergence"), "{text}");
    }

    #[test]
    fn a_deadlock_names_the_point_they_could_not_settle() {
        let state = state_with(vec![], vec![]);
        let points = [finding("Retry loop never terminates", "src/net.rs:88")];
        let text = outcome_comment(
            &state,
            &Ledger::new(),
            &Ending::Deadlocked(&points),
            &style(),
        )
        .unwrap();
        assert!(
            text.contains("Retry loop never terminates (src/net.rs:88)"),
            "{text}"
        );
        assert!(text.contains("could not settle"), "{text}");
    }

    /// The diff records what was fixed. Nothing records what was argued down.
    #[test]
    fn refutations_survive_because_nothing_else_carries_them() {
        let state = state_with(
            vec![(
                "Error is swallowed",
                "the caller already validates the file",
            )],
            vec![],
        );
        let text = outcome_comment(&state, &Ledger::new(), &Ending::Approved, &style()).unwrap();
        assert!(text.contains("Raised and refuted:"), "{text}");
        assert!(
            text.contains("The caller already validates the file"),
            "{text}"
        );
    }

    #[test]
    fn no_agent_names_counts_or_round_numbers_reach_the_thread() {
        let state = state_with(
            vec![("A point", "a reason")],
            vec!["https://github.com/you/thing/issues/485"],
        );
        for ending in [Ending::Approved, Ending::OutOfRounds] {
            let text = outcome_comment(&state, &Ledger::new(), &ending, &style()).unwrap();
            let lower = text.to_lowercase();
            for banned in ["claude", "codex", "blocking,", "nit,", " fixed."] {
                assert!(
                    !lower.contains(banned),
                    "{banned:?} leaked into the thread:\n{text}"
                );
            }
            // "the last round of fixes" is prose. "round 3" is narration.
            for n in 1..9 {
                assert!(
                    !lower.contains(&format!("round {n}")),
                    "a round number leaked into the thread:\n{text}"
                );
            }
        }
    }

    #[test]
    fn the_whole_comment_stays_short() {
        let state = state_with(
            vec![("A point", &"long reasoning ".repeat(40))],
            vec!["https://github.com/you/thing/issues/485"],
        );
        let text = outcome_comment(&state, &Ledger::new(), &Ending::OutOfRounds, &style()).unwrap();
        assert!(text.len() < 600, "{} chars:\n{text}", text.len());
    }

    #[test]
    fn a_url_that_is_not_an_issue_link_is_left_alone() {
        assert_eq!(
            "#485",
            as_reference("https://github.com/you/thing/issues/485")
        );
        assert_eq!("note: something", as_reference("note: something"));
    }
}