spar-cli 0.1.7

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
//! Two gates over every string spar sends to GitHub.
//!
//! **Style.** Models comply unreliably with negative instructions, especially
//! over a long run, so prompting is necessary but not sufficient. Every commit
//! message, PR body, and comment is scrubbed deterministically and then
//! re-verified. A leak is a hard error, not a warning.
//!
//! **Shape.** The reader of a PR is a human with other work. What made a thread
//! unreadable was never the length of the findings, it was spar narrating
//! itself: which agent spoke, which round it was, counts of things listed on the
//! next line. So spar composes every comment itself from structured fields, and
//! that is where brevity comes from.
//!
//! The length budgets below are safety valves, not editors. They are sized so
//! that real content is never touched, and when one does fire it completes the
//! sentence in progress rather than stopping mid-thought. Cutting substance was
//! a mistake worth naming: a reader who cannot act on a finding has been given
//! nothing, and the characters saved bought nothing. Brevity is asked for in the
//! prompts, which is free, and enforced only on shape.

use std::sync::LazyLock;

use regex::Regex;

/// Figure dash, en dash, em dash, horizontal bar. The Python original caught
/// only en and em; a model that reaches for U+2015 should not slip through.
const DASHES: &str = r"[\x{2012}-\x{2015}]";

static ATTRIBUTION_LINE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"(?im)^\s*(?:",
        r"co-authored-by:\s*(?:claude|codex|openai|chatgpt|anthropic|gpt).*",
        r"|\x{1F916}?\s*generated with .*",
        r"|.*\bwritten by (?:claude|codex|chatgpt|an? ai)\b.*",
        r"|assisted[- ]by:.*",
        r")\s*$",
    ))
    .expect("attribution line pattern")
});

static ATTRIBUTION_INLINE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(concat!(
        r"(?i)\b(?:",
        r"generated (?:with|by) (?:claude|codex|openai|chatgpt|ai)",
        r"|(?:written|authored|created) (?:with|by) (?:claude|codex|chatgpt|ai)",
        r"|with the help of (?:claude|codex|chatgpt|ai)",
        r"|using (?:claude code|codex|chatgpt)",
        r"|ai[- ]generated",
        r"|as an ai\b",
        r")",
    ))
    .expect("attribution inline pattern")
});

static DASH_RUN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(&format!(r"[ \t]*{DASHES}[ \t]*")).expect("dash pattern"));

static ANY_DASH: LazyLock<Regex> = LazyLock::new(|| Regex::new(DASHES).expect("dash class"));

static TRAILING_SPACE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"(?m)[ \t]+$").expect("trailing space pattern"));

static BLANK_RUN: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"\n{3,}").expect("blank run pattern"));

static HEADING: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^\s{0,3}#{1,6}\s+\S").expect("heading pattern"));

/// Headings that only announce that a body follows. Dropping them costs the
/// reader nothing and saves them a line.
static NOISE_HEADING: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?i)^\s{0,3}#{1,6}\s*(summary|description|overview|context|details?|background)\s*:?\s*$",
    )
    .expect("noise heading pattern")
});

/// Everything the two gates need to know. Mirrors the `[style]` config block.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Style {
    pub ban_em_dash: bool,
    pub ban_ai_attribution: bool,
    /// Enforce the length budgets below. Off means model prose passes through
    /// at whatever length it arrived at.
    pub terse: bool,
    /// A finding's explanatory detail, as shown in the PR thread.
    pub max_detail_chars: usize,
    /// A one-line verdict or disposition summary.
    pub max_summary_chars: usize,
    /// A PR body.
    pub max_body_chars: usize,
    /// A filed issue's body.
    pub max_issue_body_chars: usize,
    /// A finding title, issue title, or PR title.
    pub max_title_chars: usize,
    /// How much of its own working spar narrates into a pull request thread.
    pub pr_comments: crate::config::PrComments,
}

impl Default for Style {
    fn default() -> Self {
        Self {
            ban_em_dash: true,
            ban_ai_attribution: true,
            terse: true,
            max_detail_chars: 2000,
            max_summary_chars: 1200,
            max_body_chars: 2000,
            max_issue_body_chars: 8000,
            max_title_chars: 140,
            pr_comments: crate::config::PrComments::Outcome,
        }
    }
}

impl Style {
    /// Style rules only, no length budgets. Used for text spar composed itself
    /// and has already sized.
    pub fn permissive() -> Self {
        Self {
            terse: false,
            ..Self::default()
        }
    }
}

// ---------------------------------------------------------------------------
// Style gate
// ---------------------------------------------------------------------------

/// Remove banned style artifacts. Idempotent: scrubbing scrubbed text is a
/// no-op, which matters because text passes through here more than once.
pub fn scrub(text: &str, style: &Style) -> String {
    if text.is_empty() {
        return String::new();
    }
    let mut out = text.to_string();

    if style.ban_ai_attribution {
        out = ATTRIBUTION_LINE.replace_all(&out, "").into_owned();
        out = ATTRIBUTION_INLINE.replace_all(&out, "").into_owned();
        out = out.replace('\u{1F916}', "");
    }

    if style.ban_em_dash {
        // "a - b" becomes "a, b". Bounded to spaces and tabs so a dash at the
        // end of a line joins two lines with a comma instead of swallowing the
        // paragraph break after it.
        out = DASH_RUN.replace_all(&out, ", ").into_owned();
    }

    out = TRAILING_SPACE.replace_all(&out, "").into_owned();
    out = BLANK_RUN.replace_all(&out, "\n\n").into_owned();
    out.trim().to_string()
}

/// Anything the scrub should have caught. Used as a post-check, so that a
/// pattern the scrub cannot fix becomes a loud failure rather than a leak.
pub fn violations(text: &str, style: &Style) -> Vec<String> {
    let mut bad = Vec::new();
    if style.ban_em_dash && ANY_DASH.is_match(text) {
        bad.push("em/en dash present".to_string());
    }
    if style.ban_ai_attribution
        && (ATTRIBUTION_LINE.is_match(text) || ATTRIBUTION_INLINE.is_match(text))
    {
        bad.push("AI attribution present".to_string());
    }
    bad
}

// ---------------------------------------------------------------------------
// Concision gate
// ---------------------------------------------------------------------------

/// Collapse to a single line of single-spaced words.
///
/// For a field that is displayed inline, such as a finding title or a one-line
/// verdict. A model that returns a paragraph there would otherwise break the
/// layout of everything around it.
pub fn one_line(text: &str) -> String {
    text.split_whitespace().collect::<Vec<_>>().join(" ")
}

/// How far past a budget it is worth going to finish the sentence in progress.
///
/// A budget is a target, not a guillotine. Stopping mid-clause costs the reader
/// the point being made and gains a handful of characters, which is a bad
/// trade: a real close comment ended "and surviving instances already reconnect
/// and..." and told nobody anything.
const OVERSHOOT: usize = 240;

/// Truncate to roughly `max` characters, ending on a complete sentence.
pub fn clip(text: &str, max: usize) -> String {
    clip_marked(text, max, "...")
}

/// The same, without an ellipsis when it does have to cut.
///
/// For a title, where a trailing "..." reads as broken rather than as
/// shortened. Two issues were filed on a real repository with titles ending in
/// a literal ellipsis, which is how this was found.
pub fn clip_bare(text: &str, max: usize) -> String {
    clip_marked(text, max, "")
}

fn clip_marked(text: &str, max: usize, marker: &str) -> String {
    let trimmed = text.trim();
    if max == 0 {
        return trimmed.to_string();
    }
    let chars: Vec<char> = trimmed.chars().collect();
    if chars.len() <= max {
        return trimmed.to_string();
    }

    let ends_sentence = |i: usize| -> bool {
        matches!(chars[i], '.' | '!' | '?')
            // Look at the real next character, not the end of some window: a
            // period landing on the budget has text after it, and treating that
            // as the end of a sentence cuts a file path in half.
            && chars.get(i + 1).is_none_or(|n| n.is_whitespace())
    };

    // The last sentence that ends at or before the budget, if it keeps enough
    // of the text to be worth reading.
    let within = (0..max).rfind(|i| ends_sentence(*i));
    if let Some(cut) = within {
        if (cut + 1) * 2 >= max {
            return chars[..=cut]
                .iter()
                .collect::<String>()
                .trim_end()
                .to_string();
        }
    }

    // Otherwise finish the sentence that is in progress, so long as it ends
    // somewhere reasonable rather than running on forever. Bounded by the
    // budget as well as by a constant, so a small budget cannot be doubled and
    // doubled again by one long sentence.
    let ceiling = (max + OVERSHOOT.min(max)).min(chars.len());
    if let Some(cut) = (max..ceiling).find(|i| ends_sentence(*i)) {
        return chars[..=cut]
            .iter()
            .collect::<String>()
            .trim_end()
            .to_string();
    }

    // A short complete sentence still beats a long severed one.
    if let Some(cut) = within {
        return chars[..=cut]
            .iter()
            .collect::<String>()
            .trim_end()
            .to_string();
    }

    // No sentence in sight. Cut at a word boundary, and say so unless the
    // caller would rather not.
    let budget = max.saturating_sub(marker.chars().count()).max(1);
    let mut end = budget.min(chars.len());
    while end > 0 && !chars[end - 1].is_whitespace() {
        end -= 1;
    }
    if end == 0 {
        end = budget.min(chars.len());
    }
    let mut out: String = chars[..end]
        .iter()
        .collect::<String>()
        .trim_end()
        .to_string();
    out.push_str(marker);
    out
}

/// Drop a heading whose section holds nothing, and the bare "## Summary" style
/// heading that only announces the body underneath it.
pub fn strip_empty_sections(text: &str) -> String {
    let lines: Vec<&str> = text.lines().collect();
    let mut keep: Vec<&str> = Vec::with_capacity(lines.len());

    let mut i = 0;
    while i < lines.len() {
        let line = lines[i];
        if HEADING.is_match(line) {
            // Everything up to the next heading is this section's body.
            let mut j = i + 1;
            while j < lines.len() && !HEADING.is_match(lines[j]) {
                j += 1;
            }
            let body_is_empty = lines[i + 1..j].iter().all(|l| l.trim().is_empty());
            let only_heading = lines.iter().filter(|l| HEADING.is_match(l)).count() == 1;

            if body_is_empty {
                i = j; // drop the heading and the blank lines under it
                continue;
            }
            if only_heading && NOISE_HEADING.is_match(line) {
                i += 1; // drop the label, keep the body
                continue;
            }
        }
        keep.push(line);
        i += 1;
    }

    let joined = keep.join("\n");
    BLANK_RUN.replace_all(&joined, "\n\n").trim().to_string()
}

/// The full outbound treatment for a block of model prose: strip structural
/// noise, then clip to a budget.
pub fn tighten(text: &str, max: usize, style: &Style) -> String {
    if !style.terse {
        return text.trim().to_string();
    }
    clip(&strip_empty_sections(text), max)
}

/// A filed issue's body.
///
/// An issue is a work item. Somebody picks it up cold, possibly months later,
/// with none of the context the pull request thread had, so the rules that keep
/// a comment short are the wrong rules here. Two things follow.
///
/// A fenced code block is never truncated and never counts against the budget.
/// A snippet cut in half is worse than useless: it is broken markdown and a
/// misleading fragment of code. Steps to reproduce, a stack trace, the offending
/// function: those are the reason the issue is worth filing at all.
///
/// And when prose does have to be dropped, whole blocks go from the end rather
/// than a sentence being cut mid-word. What survives is complete.
pub fn issue_body(text: &str, style: &Style) -> String {
    if !style.terse {
        return text.trim().to_string();
    }
    let cleaned = strip_empty_sections(text);
    let blocks = split_blocks(&cleaned);

    // A runaway model pasting an entire file is still worth stopping, so code
    // is exempt from the prose budget but not from a far looser ceiling.
    let ceiling = style.max_issue_body_chars.saturating_mul(4);

    let mut kept: Vec<String> = Vec::new();
    let mut prose = 0usize;
    let mut total = 0usize;
    for block in &blocks {
        let len = block.text.chars().count();
        if !block.code && prose + len > style.max_issue_body_chars && !kept.is_empty() {
            break;
        }
        if total + len > ceiling {
            // Past the point GitHub itself would take. Shortening a snippet at
            // a line boundary with the fence closed still leaves something
            // usable; dropping it leaves nothing.
            if block.code {
                if let Some(short) = shorten_code(&block.text, ceiling.saturating_sub(total)) {
                    kept.push(short);
                }
            }
            break;
        }
        if !block.code {
            prose += len;
        }
        total += len;
        kept.push(block.text.clone());
    }

    kept.join("\n\n").trim().to_string()
}

/// Keep as many whole lines of a fenced block as fit, and close the fence.
///
/// Only ever reached by a snippet large enough that GitHub would refuse the
/// comment outright. Cutting on a line boundary keeps the code readable and
/// keeps the markdown valid, and the note says plainly that there was more.
fn shorten_code(block: &str, room: usize) -> Option<String> {
    const NOTE: &str = "(snippet shortened)";
    if room < 80 {
        return None;
    }
    let mut lines = block.lines();
    let opener = lines.next()?.to_string();
    let mut out = vec![opener];
    let mut used = out[0].chars().count() + NOTE.len() + 8;

    for line in lines {
        if line.trim_start().starts_with("```") {
            break;
        }
        let len = line.chars().count() + 1;
        if used + len > room {
            break;
        }
        used += len;
        out.push(line.to_string());
    }
    out.push("```".to_string());
    out.push(String::new());
    out.push(NOTE.to_string());
    Some(out.join("\n"))
}

struct Block {
    text: String,
    code: bool,
}

/// Split into paragraphs, keeping every fenced code block whole however many
/// blank lines it contains.
fn split_blocks(text: &str) -> Vec<Block> {
    let mut blocks = Vec::new();
    let mut current: Vec<&str> = Vec::new();
    let mut in_fence = false;
    let mut fence_block = false;

    let flush = |lines: &mut Vec<&str>, code: bool, out: &mut Vec<Block>| {
        let joined = lines.join("\n");
        if !joined.trim().is_empty() {
            out.push(Block {
                text: joined.trim_end().to_string(),
                code,
            });
        }
        lines.clear();
    };

    for line in text.lines() {
        let fence = line.trim_start().starts_with("```");
        if fence {
            if in_fence {
                current.push(line);
                in_fence = false;
                flush(&mut current, true, &mut blocks);
                fence_block = false;
                continue;
            }
            // A fence starts here, so whatever came before is its own block.
            flush(&mut current, false, &mut blocks);
            in_fence = true;
            fence_block = true;
            current.push(line);
            continue;
        }
        if in_fence {
            current.push(line);
            continue;
        }
        if line.trim().is_empty() {
            flush(&mut current, false, &mut blocks);
        } else {
            current.push(line);
        }
    }
    // An unterminated fence is still kept whole rather than split.
    flush(&mut current, fence_block, &mut blocks);
    blocks
}

/// A finding title, issue title, or PR title: always one line, always short.
pub fn title(text: &str, style: &Style) -> String {
    let flat = one_line(text);
    if style.terse {
        clip_bare(&flat, style.max_title_chars)
    } else {
        flat
    }
}

/// Capitalise the first letter, so a model's fragment reads as a sentence when
/// spar sets it after one of its own.
pub fn sentence(text: &str, style: &Style) -> String {
    let one = summary(text, style);
    let mut chars = one.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => one,
    }
}

/// A one-sentence verdict or disposition reason.
pub fn summary(text: &str, style: &Style) -> String {
    let flat = one_line(text);
    if style.terse {
        clip(&flat, style.max_summary_chars)
    } else {
        flat
    }
}

/// A finding's explanation, as it appears in the PR thread. Kept on one line so
/// a bullet stays a bullet.
pub fn detail(text: &str, style: &Style) -> String {
    let flat = one_line(text);
    if style.terse {
        clip(&flat, style.max_detail_chars)
    } else {
        flat
    }
}

/// An issue or PR body. Multi-line is fine here; bloat is not.
pub fn body(text: &str, style: &Style) -> String {
    tighten(text, style.max_body_chars, style)
}

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

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

    // -- style gate ------------------------------------------------------

    #[test]
    fn em_dash_removed() {
        let out = scrub(
            "Fix the parser, it was broken \u{2014} badly \u{2014} on empty input.",
            &s(),
        );
        assert!(!out.contains('\u{2014}'));
        assert!(violations(&out, &s()).is_empty());
    }

    #[test]
    fn en_dash_removed() {
        assert!(!scrub("range 1 \u{2013} 5", &s()).contains('\u{2013}'));
    }

    #[test]
    fn horizontal_bar_removed() {
        assert!(violations(&scrub("a \u{2015} b", &s()), &s()).is_empty());
    }

    #[test]
    fn coauthor_trailer_stripped() {
        let out = scrub(
            "Add retry logic\n\nCo-Authored-By: Claude Opus 5 <noreply@anthropic.com>\n",
            &s(),
        );
        assert!(!out.contains("Co-Authored-By"));
        assert!(out.contains("Add retry logic"));
    }

    #[test]
    fn generated_with_footer_stripped() {
        let out = scrub(
            "Fix bug\n\n\u{1F916} Generated with [Claude Code](https://claude.com)\n",
            &s(),
        );
        assert!(violations(&out, &s()).is_empty(), "{out}");
        assert!(out.contains("Fix bug"));
    }

    #[test]
    fn inline_attribution_stripped() {
        let out = scrub("This patch was written by Claude to fix the leak.", &s());
        assert!(violations(&out, &s()).is_empty(), "{out}");
    }

    #[test]
    fn scrub_is_idempotent() {
        let once = scrub("A \u{2014} B\n\nCo-Authored-By: Codex <x@y.z>", &s());
        assert_eq!(once, scrub(&once, &s()));
    }

    #[test]
    fn violations_detected_before_scrub() {
        assert!(!violations("a \u{2014} b", &s()).is_empty());
        assert!(!violations("Co-Authored-By: Claude <a@b.c>", &s()).is_empty());
    }

    #[test]
    fn legitimate_prose_survives() {
        let out = scrub("Refactor the AI-facing endpoint handler for clarity.", &s());
        assert!(out.contains("endpoint handler"), "{out}");
    }

    #[test]
    fn disabled_rules_are_respected() {
        let off = Style {
            ban_em_dash: false,
            ban_ai_attribution: false,
            ..s()
        };
        let text = "a \u{2014} b\nCo-Authored-By: Claude <x@y.z>";
        assert!(scrub(text, &off).contains('\u{2014}'));
        assert!(violations(text, &off).is_empty());
    }

    #[test]
    fn dash_at_end_of_line_does_not_swallow_the_paragraph_break() {
        let out = scrub("first line \u{2014}\n\nsecond paragraph", &s());
        assert!(out.contains("\n\n"), "{out:?}");
    }

    #[test]
    fn empty_input_is_empty_output() {
        assert_eq!("", scrub("", &s()));
    }

    // -- concision gate --------------------------------------------------

    #[test]
    fn one_line_flattens() {
        assert_eq!("a b c", one_line("  a\n\n b\t c  "));
    }

    #[test]
    fn clip_leaves_short_text_alone() {
        assert_eq!("short", clip("short", 40));
    }

    #[test]
    fn clip_prefers_a_sentence_boundary() {
        let text = "The loop never terminates. It also leaks a file descriptor on every pass.";
        assert_eq!("The loop never terminates.", clip(text, 40));
    }

    #[test]
    fn clip_falls_back_to_a_word_boundary() {
        let out = clip("supercalifragilistic wording that runs on and on", 25);
        assert!(out.ends_with("..."), "{out}");
        assert!(out.chars().count() <= 25, "{out}");
        assert!(!out.contains("wording that runs"), "{out}");
    }

    #[test]
    /// The budget is a target that rounds up to the end of a sentence, so it
    /// can be exceeded on purpose. What must hold is that the overshoot is
    /// bounded: a budget cannot be run away with.
    fn clip_overshoots_only_within_bounds() {
        for max in 1..60 {
            let out = clip("one two three four five six seven eight nine ten.", max);
            assert!(out.chars().count() <= max * 2 + 3, "max={max} out={out:?}");
        }
    }

    #[test]
    fn clip_handles_multibyte_text() {
        let out = clip(&"\u{1f600}".repeat(50), 10);
        assert!(out.chars().count() <= 10, "{out}");
    }

    /// The sentence-end scan used to look at the last character of the *budget*
    /// rather than of the *text*, so a period landing exactly on the boundary
    /// read as the end of a sentence. The result came back with no ellipsis, so
    /// a truncated file path looked like finished prose.
    #[test]
    fn a_period_on_the_budget_boundary_is_not_a_sentence_end() {
        assert_ne!(
            "Version 1.",
            clip("Version 1.4 of the parser mishandles input", 10)
        );
        assert_ne!(
            "Panic in src/style.",
            clip("Panic in src/style.rs when the budget lands mid word", 19)
        );
    }

    #[test]
    fn an_unmarked_clip_really_did_end_a_sentence() {
        // The only way to come back without an ellipsis is to stop where the
        // author stopped.
        for max in 4..80 {
            let text = "First sentence here. Second one follows it. Third trails off";
            let out = clip(text, max);
            if out.len() < text.len() && !out.ends_with("...") {
                assert!(
                    out.ends_with('.') || out.ends_with('!') || out.ends_with('?'),
                    "max={max} out={out:?}"
                );
                let next = text[out.len()..].chars().next();
                assert!(
                    next.is_none_or(|c| c.is_whitespace()),
                    "max={max} cut mid-token before {next:?}: {out:?}"
                );
            }
        }
    }

    #[test]
    fn clip_ignores_a_decimal_point_as_a_sentence_end() {
        let text = "Version 1.4 of the parser mishandles empty input badly and loops.";
        assert_ne!("Version 1.", clip(text, 30));
    }

    #[test]
    fn empty_sections_are_dropped() {
        let out = strip_empty_sections("## Context\n\n## Proposal\n\nDo the thing.\n");
        assert!(!out.contains("Context"), "{out}");
        assert!(out.contains("Do the thing."), "{out}");
    }

    #[test]
    fn a_lone_label_heading_is_dropped() {
        assert_eq!(
            "The retry never fires.",
            strip_empty_sections("## Summary\n\nThe retry never fires.")
        );
    }

    #[test]
    fn real_headings_survive_when_there_are_several() {
        let text = "## Summary\n\nA thing.\n\n## Repro\n\nRun it.";
        let out = strip_empty_sections(text);
        assert!(
            out.contains("## Summary") && out.contains("## Repro"),
            "{out}"
        );
    }

    #[test]
    fn terse_off_leaves_length_alone() {
        let loose = Style {
            terse: false,
            ..s()
        };
        let long = "word ".repeat(400);
        assert_eq!(long.trim(), detail(&long, &loose));
    }

    #[test]
    fn detail_is_capped_and_single_line() {
        let out = detail(
            &format!("first line\nsecond line\n{}", "filler ".repeat(200)),
            &s(),
        );
        assert!(!out.contains('\n'));
        assert!(out.chars().count() <= s().max_detail_chars);
    }

    #[test]
    fn title_is_capped_and_single_line() {
        let out = title(
            "a very\nlong\ttitle that keeps going ".repeat(20).as_str(),
            &s(),
        );
        assert!(!out.contains('\n'));
        assert!(out.chars().count() <= s().max_title_chars);
    }

    #[test]
    fn body_keeps_structure_but_bounds_length() {
        let text = format!(
            "## Summary\n\nreal content here.\n\n{}",
            "more prose. ".repeat(300)
        );
        let out = body(&text, &s());
        assert!(
            out.chars().count() <= s().max_body_chars,
            "{}",
            out.chars().count()
        );
        assert!(out.contains("real content here"), "{out}");
    }
}

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

    #[test]
    fn a_fragment_reads_as_a_sentence() {
        assert_eq!(
            "The caller already validates it.",
            sentence("the caller already validates it.", &Style::default())
        );
    }

    #[test]
    fn an_already_capitalised_one_is_untouched() {
        assert_eq!(
            "Already fine.",
            sentence("Already fine.", &Style::default())
        );
    }

    #[test]
    fn empty_stays_empty_rather_than_panicking() {
        assert_eq!("", sentence("   ", &Style::default()));
    }

    #[test]
    fn a_multibyte_first_character_does_not_panic() {
        assert_eq!("Ärger", sentence("ärger", &Style::default()));
    }
}

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

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

    fn fences(text: &str) -> usize {
        text.lines()
            .filter(|l| l.trim_start().starts_with("```"))
            .count()
    }

    /// The whole point. A snippet cut in half is broken markdown and a
    /// misleading fragment of the code somebody is being asked to fix.
    #[test]
    fn a_code_block_is_never_truncated() {
        let code = (0..400)
            .map(|n| format!("    line_{n}();"))
            .collect::<Vec<_>>()
            .join("\n");
        let text = format!("It spins forever.\n\n```rust\n{code}\n```\n\nThat is the loop.");
        let out = issue_body(&text, &s());

        assert!(
            out.contains("line_0();") && out.contains("line_399();"),
            "the block was cut"
        );
        assert_eq!(0, fences(&out) % 2, "left an unclosed fence:\n{out}");
    }

    /// Why there are two functions rather than one budget. The comment path
    /// cuts wherever the character count runs out, which on a snippet means an
    /// unclosed fence and a misleading half of the code.
    #[test]
    /// However long the snippet, an issue keeps the fence closed. A comment
    /// budget is character counted and knows nothing about fences, which is why
    /// issues do not go through it.
    fn an_issue_keeps_the_fence_closed_however_long_the_snippet() {
        for lines in [50, 400, 4000] {
            let code = (0..lines)
                .map(|n| format!("    line_{n}();"))
                .collect::<Vec<_>>()
                .join("\n");
            let text = format!("It spins forever.\n\n```rust\n{code}\n```");
            let out = issue_body(&text, &s());
            assert_eq!(0, fences(&out) % 2, "unclosed fence at {lines} lines");
            if lines <= 400 {
                assert!(
                    out.contains(&format!("line_{}();", lines - 1)),
                    "cut at {lines} lines"
                );
            } else {
                // Past what GitHub would accept at all. Shortened rather than
                // dropped, on a line boundary, and it says so.
                assert!(out.contains("line_0();"), "the snippet went entirely");
                assert!(
                    out.contains("snippet shortened"),
                    "the reader is not told: {}",
                    &out[out.len().saturating_sub(80)..]
                );
            }
        }
    }

    /// Code is exempt from the budget, so a long snippet cannot squeeze out the
    /// prose that explains it.
    #[test]
    fn a_long_snippet_does_not_evict_the_explanation() {
        let code = "x();\n".repeat(1500);
        let text = format!(
            "Reproduction:\n\n1. Call connect twice.\n2. Watch the retry count.\n\n```\n{code}```\n\nSuggested fix: bound the loop."
        );
        let out = issue_body(&text, &s());
        assert!(out.contains("Call connect twice"), "{out}");
        assert!(out.contains("Suggested fix"), "the tail survived");
    }

    #[test]
    fn steps_to_reproduce_survive_intact() {
        let text = "The retry never fires.\n\n1. Start the daemon.\n2. Kill the peer.\n3. Observe connectedToElectrum stays true.\n\nsrc/electrum/index.ts:289 is where the guard is.";
        assert_eq!(text, issue_body(text, &s()));
    }

    #[test]
    fn a_body_within_budget_is_untouched() {
        let text = "One paragraph.\n\nAnd another.";
        assert_eq!(text, issue_body(text, &s()));
    }

    /// When prose does have to go, whole blocks go from the end. Nothing is cut
    /// mid-sentence and nothing gains an ellipsis.
    #[test]
    fn overlong_prose_drops_whole_blocks_from_the_end() {
        let para = |n: usize| format!("Paragraph {n}. {}", "filler words here. ".repeat(30));
        let text = (0..20).map(para).collect::<Vec<_>>().join("\n\n");
        let out = issue_body(&text, &s());

        assert!(out.starts_with("Paragraph 0."), "{out}");
        assert!(!out.contains("..."), "no mid-sentence cut: {out}");
        assert!(
            out.trim_end().ends_with('.'),
            "ends on a complete block: {out}"
        );
        assert!(
            out.chars().count() <= s().max_issue_body_chars + 400,
            "{}",
            out.chars().count()
        );
    }

    /// An issue gets far more room than a pull request comment, because it is
    /// read cold by somebody with none of the context.
    #[test]
    fn an_issue_gets_much_more_room_than_a_comment() {
        let text = "word ".repeat(4000);
        assert!(
            issue_body(&text, &s()).len() > body(&text, &s()).len() * 2,
            "issue {} vs comment {}",
            issue_body(&text, &s()).len(),
            body(&text, &s()).len()
        );
    }

    #[test]
    fn a_single_block_over_budget_is_kept_rather_than_mangled() {
        let text = format!("```\n{}\n```", "y();\n".repeat(3000));
        let out = issue_body(&text, &s());
        assert!(!out.is_empty());
        assert_eq!(0, fences(&out) % 2, "{}", &out[..80.min(out.len())]);
    }

    #[test]
    fn an_unterminated_fence_is_still_kept_whole() {
        let text = "Here is the code:\n\n```rust\nfn broken() {\n    loop {}";
        let out = issue_body(text, &s());
        assert!(out.contains("fn broken()"), "{out}");
    }

    #[test]
    fn terse_off_leaves_an_issue_body_completely_alone() {
        let loose = Style {
            terse: false,
            ..s()
        };
        let text = "a".repeat(50_000);
        assert_eq!(text, issue_body(&text, &loose));
    }

    #[test]
    fn issue_body_is_idempotent() {
        let text = format!(
            "Explanation.\n\n```\n{}\n```\n\n{}",
            "z();\n".repeat(50),
            "more prose. ".repeat(600)
        );
        let once = issue_body(&text, &s());
        assert_eq!(once, issue_body(&once, &s()));
    }
}

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

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

    /// The real close comment from beignet#493, which stopped mid-clause and
    /// told the reader nothing.
    const REAL: &str = "Disconnect() deliberately drops the instance's restore debt and stops \
        its poll, so re-arming _restoreOwed there would leave a field nothing consumes, and \
        surviving instances already reconnect and restore every remaining hash on their own.";

    #[test]
    fn the_real_comment_now_finishes_its_sentence() {
        let out = summary(REAL, &s());
        assert!(!out.ends_with("..."), "{out}");
        assert!(out.ends_with('.'), "{out}");
        assert!(out.contains("on their own"), "the thought completes: {out}");
    }

    /// The point of the overshoot: a budget is a target, not a guillotine.
    #[test]
    fn a_sentence_running_just_past_the_budget_is_finished_not_cut() {
        let text = format!("{} and then it ends here.", "word ".repeat(78));
        let out = clip(&text, 400);
        assert!(out.ends_with("and then it ends here."), "{out}");
        assert!(out.chars().count() > 400, "it overshot on purpose");
    }

    /// But not forever. Prose with no sentence end in sight still gets cut.
    #[test]
    fn a_sentence_that_never_ends_is_still_cut() {
        let text = "word ".repeat(400);
        let out = clip(&text, 200);
        assert!(out.ends_with("..."), "{out}");
        assert!(out.chars().count() <= 200, "{}", out.chars().count());
    }

    /// Overshoot is for a sentence straddling the budget, not a licence to
    /// ignore it. Where sentences end regularly, it stops within budget.
    #[test]
    fn it_stops_within_budget_when_a_sentence_ends_there() {
        let text = "This sentence is complete. ".repeat(30);
        let out = clip(&text, 400);
        assert!(out.ends_with("complete."), "{out}");
        assert!(out.chars().count() <= 400, "{}", out.chars().count());
    }

    /// And a small budget cannot be run away with by one long sentence.
    #[test]
    fn overshoot_never_more_than_doubles_the_budget() {
        let text = format!("Short. {}", "word ".repeat(400));
        let out = clip(&text, 60);
        assert!(out.chars().count() <= 120, "{}", out.chars().count());
    }

    /// Two issues were filed on a real repository with titles ending in a
    /// literal ellipsis. A title is not a place for one.
    #[test]
    fn a_title_never_wears_an_ellipsis() {
        let long = "disconnect() stops electrum for clients.network rather than \
                    this.electrumNetwork and records the stop against a key nothing reads back"
            .to_string();
        let out = title(&long, &s());
        assert!(!out.ends_with("..."), "{out}");
        assert!(!out.contains("..."), "{out}");
    }

    /// The two real titles that were truncated were 85 and 89 characters after
    /// spar cut them. The raised budget keeps titles of that length whole.
    #[test]
    fn the_titles_that_were_cut_would_now_survive() {
        for real in [
            "Public subscribeToHeader/subscribeToAddresses re-register an instance disconnect() \
             deliberately dropped",
            "disconnect() stops electrum for clients.network, not this.electrumNetwork, and \
             records the stop against the wrong key",
        ] {
            let out = title(real, &s());
            assert_eq!(one_line(real), out, "still truncated: {out}");
        }
    }

    #[test]
    fn the_budgets_leave_room_to_finish_a_thought() {
        let d = s();
        assert!(d.max_summary_chars >= 400, "a one line reason needs room");
        assert!(d.max_detail_chars >= 500);
        assert!(d.max_title_chars >= 140);
    }

    #[test]
    fn a_short_text_is_still_left_completely_alone() {
        assert_eq!("Already short.", clip("Already short.", 400));
        assert_eq!("Already short.", clip_bare("Already short.", 400));
    }
}