soothfast-report 0.4.3

Soothfast report engine: perf tables, trend charts, changelog drafts, badges, llms.txt
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
//! Changelog drafting: API-surface diff + perf deltas rendered as a draft
//! section, assembled from recorded facts instead of backfilled from memory.

use std::collections::BTreeMap;

use serde_json::Value;

use crate::llms::SurfaceEntry;

/// What the API section has to report.
///
/// The two cases are separate types rather than an empty-string convention:
/// "nothing changed" and "there was nothing to compare against" read the
/// same in prose but mean opposite things, and a changelog that confuses
/// them reports calm where it had no input at all.
pub enum ApiSection<'a> {
    /// Diff against an earlier release.
    Diff { against: &'a str, text: &'a str },
    /// No earlier release exists, so the surface itself is the news.
    Initial(&'a [SurfaceEntry]),
}

/// Per-metric movement a delta table is willing to report, as percentages.
///
/// These mirror the gate's own thresholds and are passed in rather than
/// defined here, so the changelog reports exactly what the gate would have
/// flagged instead of drifting from it.
///
/// Only deterministic metrics have thresholds, because a changelog is a
/// permanent record: walltime moves 15-20% between two runs of identical
/// code on a shared CI runner, so recording it means rewriting the section
/// on every merge to say nothing. Walltime regressions are `gate`'s job,
/// where a human reads the verdict against a live noise floor.
pub struct PerfThresholds {
    pub instructions_pct: f64,
    pub allocs_pct: f64,
}

/// One merged change, read off a conventional-commit subject.
pub struct Change {
    /// Commit type: `feat`, `fix`, `perf`, `docs`, and the rest.
    pub kind: String,
    /// Conventional-commit scope, the parenthesised part after the type.
    pub scope: Option<String>,
    /// The subject carried the `!` breaking-change marker.
    pub breaking: bool,
    /// Subject line with the type prefix and pull request number removed.
    pub subject: String,
    /// Pull request the subject ended with, when it named one.
    pub pr: Option<u32>,
}

/// Subjects the repo's own bots commit, matched whole. A prefix would be
/// tidier and would also swallow a real `regenerate ...` feature, which is
/// the worse failure: a stray bot line is visible, a missing feature is not.
const BOT_SUBJECTS: [&str; 3] = [
    "regenerate CHANGELOG.md",
    "regenerate API specs",
    "regenerate derived docs",
];

/// Reader-facing sections, in the order a release renders them. Anything
/// whose type is missing here lands under the last entry.
const SECTIONS: [(&str, &[&str]); 7] = [
    ("Breaking changes", &[]),
    ("Features", &["feat"]),
    ("Fixes", &["fix"]),
    ("Performance", &["perf"]),
    ("Documentation", &["docs"]),
    ("Dependencies", &["deps"]),
    ("Internal", &["refactor", "chore", "build", "test", "ci"]),
];

const BREAKING: &str = "Breaking changes";

/// Parse `type(scope)!: subject (#N)` subjects. Release commits and the bots
/// that regenerate derived artifacts are dropped, since a release listing
/// its own paperwork is noise.
pub fn changes_from_subjects(subjects: &[String]) -> Vec<Change> {
    subjects
        .iter()
        .filter_map(|line| parse_subject(line))
        .filter(|change| !is_bookkeeping(&change.subject))
        .collect()
}

/// Subjects that are not conventional commits of a known type: the ones a
/// release would otherwise drop in silence.
pub fn unparsed_subjects(subjects: &[String]) -> Vec<&str> {
    subjects
        .iter()
        .filter(|line| parse_subject(line).is_none())
        .map(String::as_str)
        .collect()
}

fn is_bookkeeping(subject: &str) -> bool {
    subject.starts_with("release v") || BOT_SUBJECTS.contains(&subject)
}

fn parse_subject(line: &str) -> Option<Change> {
    let (prefix, rest) = line.split_once(": ")?;
    let (prefix, breaking) = match prefix.strip_suffix('!') {
        Some(bare) => (bare, true),
        None => (prefix, false),
    };
    let (kind, scope) = match prefix.split_once('(') {
        Some((kind, scope)) => (kind, Some(scope.strip_suffix(')')?)),
        None => (prefix, None),
    };
    // A `deps` or `deps-dev` scope names the section itself, whatever type
    // carries it.
    let is_deps = scope.is_some_and(|s| s == "deps" || s.starts_with("deps-"));
    let kind = if is_deps { "deps" } else { kind };
    if !SECTIONS.iter().any(|(_, kinds)| kinds.contains(&kind)) {
        return None;
    }
    let rest = rest.trim();
    let (subject, pr) = match rest.rsplit_once(" (#") {
        Some((head, tail)) => (head, tail.strip_suffix(')').and_then(|n| n.parse().ok())),
        None => (rest, None),
    };
    Some(Change {
        kind: kind.to_string(),
        scope: scope.filter(|_| !is_deps).map(str::to_string),
        breaking,
        subject: subject.trim().to_string(),
        pr,
    })
}

/// Inputs already computed by the CLI (API section, two baselines).
pub struct DraftInputs<'a> {
    pub api: ApiSection<'a>,
    /// Merged changes since the reference, newest first.
    pub changes: &'a [Change],
    /// Section icons; `Icons::default()` for the shipped set.
    pub icons: &'a Icons,
    /// Reference baseline (older) — None renders current-only.
    pub old_baseline: Option<&'a Value>,
    pub new_baseline: &'a Value,
    /// Only consulted when `old_baseline` is Some.
    pub thresholds: PerfThresholds,
}

/// Render the "Unreleased" draft section: API surface + perf table.
pub fn draft(inputs: &DraftInputs) -> String {
    let heading = match &inputs.api {
        ApiSection::Diff { against, .. } => format!("Unreleased (draft vs {against})"),
        ApiSection::Initial(_) => "Unreleased (initial public surface)".to_string(),
    };
    let mut out = format!("## {heading}\n\n");
    out.push_str(&sections(inputs.changes, inputs.icons));

    let api = api_section(&inputs.api);
    let perf = perf_section(inputs);
    if api.is_empty() && perf.is_empty() {
        out.truncate(out.trim_end().len());
        out.push('\n');
        return out;
    }
    out.push_str("---\n\n");
    out.push_str(&api);
    out.push_str(&perf);
    out.truncate(out.trim_end().len());
    out.push('\n');
    out
}

/// One `### <emoji> <name>` block per type that has changes, omitting the
/// rest so an empty section never ships.
fn sections(changes: &[Change], icons: &Icons) -> String {
    let mut out = String::new();
    for (name, kinds) in SECTIONS {
        let mut entries = changes.iter().filter(|c| {
            if name == BREAKING {
                c.breaking
            } else {
                !c.breaking && kinds.contains(&c.kind.as_str())
            }
        });
        let Some(first) = entries.next() else {
            continue;
        };
        out.push_str(&format!("### {} {name}\n\n", icons.get(name)));
        for change in std::iter::once(first).chain(entries) {
            out.push_str(&format!("- {}\n", entry_line(change)));
        }
        out.push('\n');
    }
    out
}

fn entry_line(change: &Change) -> String {
    let subject = sentence_case(&change.subject);
    let scoped = match &change.scope {
        Some(scope) => format!("{scope}: {subject}"),
        None => subject,
    };
    match change.pr {
        Some(pr) => format!("{scoped} (#{pr})"),
        None => scoped,
    }
}

/// Commit subjects are imperative and lowercase; a release note reads as a
/// list of sentences. A subject opening on an identifier is left alone,
/// since `soothfast.lock` is not a word to capitalize. `-` is deliberately
/// not in that set: `cargo-soothfast` and `version-coupled` are the same
/// shape, and the ordinary word is the commoner case.
fn sentence_case(subject: &str) -> String {
    let first_token = subject.split_whitespace().next().unwrap_or_default();
    if first_token.contains(['.', '_', '(', ':']) {
        return subject.to_string();
    }
    let mut chars = subject.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

/// Section icons, keyed by the lowercased section name a release renders
/// (`breaking changes`, `features`, `fixes`, `performance`, `documentation`,
/// `dependencies`, `internal`).
///
/// A repo overrides any subset through `[changelog.icons]` in its
/// `soothfast.toml`; whatever it leaves out keeps the shipped default, so a
/// consumer never has to restate the whole vocabulary to change one glyph.
#[derive(Debug, Default)]
pub struct Icons {
    overrides: BTreeMap<String, String>,
}

impl Icons {
    /// Build from configured pairs, rejecting a name that is not a section.
    /// A typo silently keeping the default is how config drifts from intent.
    pub fn new(overrides: BTreeMap<String, String>) -> Result<Icons, String> {
        for name in overrides.keys() {
            if !SECTIONS
                .iter()
                .any(|(section, _)| section.eq_ignore_ascii_case(name))
            {
                let known: Vec<&str> = SECTIONS.iter().map(|(s, _)| *s).collect();
                return Err(format!(
                    "`{name}` is not a changelog section; expected one of {}",
                    known.join(", ").to_lowercase()
                ));
            }
        }
        Ok(Icons {
            overrides: overrides
                .into_iter()
                .map(|(name, icon)| (name.to_ascii_lowercase(), icon))
                .collect(),
        })
    }

    fn get(&self, section: &str) -> &str {
        self.overrides
            .get(&section.to_ascii_lowercase())
            .map(String::as_str)
            .unwrap_or_else(|| default_icon(section))
    }
}

fn default_icon(name: &str) -> &'static str {
    match name {
        "Breaking changes" => "\u{1F4A5}",
        "Features" => "\u{2728}",
        "Fixes" => "\u{1F41B}",
        "Performance" => "\u{26A1}",
        "Documentation" => "\u{1F4DD}",
        "Dependencies" => "\u{1F4E6}",
        _ => "\u{1F527}",
    }
}

/// The API surface block, empty when there is nothing to report.
fn api_section(api: &ApiSection) -> String {
    let body = match api {
        ApiSection::Diff { text, .. } if is_empty_diff(text) => return String::new(),
        ApiSection::Diff { text, .. } => format!("```\n{}\n```\n", text.trim_end()),
        // An initial surface with nothing in it is a real finding, not an
        // empty section: the extraction produced nothing to describe.
        ApiSection::Initial([]) => {
            "No public items found: nothing was extracted to describe.\n".to_string()
        }
        ApiSection::Initial(entries) => inventory(entries),
    };
    format!("### \u{1F50D} API surface\n\n{body}\n")
}

/// The measured-movement table, empty when nothing moved past a threshold.
fn perf_section(inputs: &DraftInputs) -> String {
    let mut out = String::new();
    match inputs.old_baseline {
        None => {
            out.push_str(&crate::perf_table::markdown(inputs.new_baseline));
        }
        Some(old) => {
            let t = &inputs.thresholds;
            let metrics: [(&str, [&str; 2], f64); 2] = [
                (
                    "instructions",
                    ["perfcnt", "instructions"],
                    t.instructions_pct,
                ),
                ("allocs", ["alloc", "allocs"], t.allocs_pct),
            ];
            let mut rows = String::new();
            let empty = serde_json::Map::new();
            let new_items = inputs.new_baseline["items"].as_object().unwrap_or(&empty);
            for (id, m) in new_items {
                for (label, path, threshold) in &metrics {
                    let new_v = m[path[0]][path[1]].as_f64();
                    let old_v = old["items"][id][path[0]][path[1]].as_f64();
                    if let (Some(o), Some(n)) = (old_v, new_v)
                        && o > 0.0
                    {
                        let delta = (n - o) / o * 100.0;
                        if delta.abs() >= *threshold {
                            rows.push_str(&format!(
                                "| `{id}` | {label} | {o:.1} | {n:.1} | {delta:+.1}% |\n"
                            ));
                        }
                    }
                }
            }
            if rows.is_empty() {
                return String::new();
            }
            out.push_str("| item | metric | was | now | delta |\n|---|---|---:|---:|---:|\n");
            out.push_str(&rows);
        }
    }
    format!("### \u{1F4CA} Gate movement\n\n{out}")
}

/// A diff the surface engine produced no findings for.
fn is_empty_diff(text: &str) -> bool {
    text.trim().is_empty() || text.trim() == "surface: no public API changes"
}

/// Every public item, grouped by crate. Nothing is capped: a first release
/// listing "the 12 most interesting items" would be a claim about taste,
/// not a record of what shipped.
fn inventory(entries: &[SurfaceEntry]) -> String {
    let mut by_pkg: BTreeMap<&str, Vec<&SurfaceEntry>> = BTreeMap::new();
    for e in entries {
        by_pkg.entry(&e.pkg).or_default().push(e);
    }

    let mut out = format!(
        "Initial release: {} public items across {} crates.\n",
        entries.len(),
        by_pkg.len()
    );
    for (pkg, mut items) in by_pkg {
        items.sort_by(|a, b| a.path.cmp(&b.path));
        out.push_str(&format!("\n#### `{pkg}` ({})\n\n", items.len()));
        for e in items {
            out.push_str(&format!("- `{}` ({})", e.path, e.kind));
            if !e.summary.trim().is_empty() {
                out.push_str(&format!(": {}", e.summary.trim()));
            }
            out.push('\n');
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use serde_json::json;

    use super::{
        ApiSection, Change, DraftInputs, Icons, PerfThresholds, changes_from_subjects, draft,
        sections, unparsed_subjects,
    };
    use crate::llms::SurfaceEntry;

    /// The values `cargo-soothfast` passes from its gate constants.
    fn gate_thresholds() -> PerfThresholds {
        PerfThresholds {
            instructions_pct: 5.0,
            allocs_pct: 5.0,
        }
    }

    fn entry(pkg: &str, path: &str, kind: &str, summary: &str) -> SurfaceEntry {
        SurfaceEntry {
            path: path.into(),
            kind: kind.into(),
            signature: String::new(),
            pkg: pkg.into(),
            summary: summary.into(),
            docs: String::new(),
        }
    }

    fn subjects(lines: &[&str]) -> Vec<String> {
        lines.iter().map(|l| l.to_string()).collect()
    }

    #[test]
    fn drafts_diff_and_deltas() {
        let old = json!({ "items": { "demo::f": { "perfcnt": { "instructions": 100 } } } });
        let new = json!({ "items": { "demo::f": { "perfcnt": { "instructions": 90 } } } });
        let text = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Diff {
                against: "v1.0.0",
                text: "ADDED    demo::g\n",
            },
            old_baseline: Some(&old),
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert!(text.contains("draft vs v1.0.0"));
        assert!(text.contains("ADDED    demo::g"));
        assert!(text.contains("-10.0%"));
    }

    #[test]
    fn an_unchanged_crates_sentinel_must_not_hide_findings() {
        let new = json!({ "items": {} });
        let text = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Diff {
                against: "v1.0.0",
                text: "# a\nsurface: no public API changes\n\n# b\nADDED    b::x\n",
            },
            old_baseline: None,
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert!(text.contains("ADDED    b::x"), "{text}");
        assert!(!text.contains("No public API changes"), "{text}");
    }

    /// A changelog is permanent, so it records only metrics that reproduce.
    /// Two CI runs of identical code moved walltime -15.2% and +18.2% on
    /// separate items, which rewrote this section on every merge.
    #[test]
    fn walltime_never_reaches_the_table_however_far_it_moved() {
        let old = json!({ "items": { "demo::f": {
            "walltime": { "median_ns": 275028.3 }, "alloc": { "allocs": 6 } } } });
        let new = json!({ "items": { "demo::f": {
            "walltime": { "median_ns": 324972.0 }, "alloc": { "allocs": 6 } } } });
        let text = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Diff {
                against: "v1.0.0",
                text: "",
            },
            old_baseline: Some(&old),
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert_eq!(text.trim(), "## Unreleased (draft vs v1.0.0)");
    }

    /// The deterministic metrics are the point: they must still land.
    #[test]
    fn an_allocation_regression_is_still_reported() {
        let old = json!({ "items": { "demo::f": {
            "walltime": { "median_ns": 100.0 }, "alloc": { "allocs": 100 } } } });
        let new = json!({ "items": { "demo::f": {
            "walltime": { "median_ns": 200.0 }, "alloc": { "allocs": 120 } } } });
        let text = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Diff {
                against: "v1.0.0",
                text: "",
            },
            old_baseline: Some(&old),
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert!(!text.contains("median_ns"), "{text}");
        assert!(text.contains("allocs"), "{text}");
        assert!(text.contains("+20.0%"), "{text}");
    }

    /// The bug this section's types exist to prevent: an empty diff and a
    /// missing reference are different facts and must not read alike.
    #[test]
    fn nothing_to_compare_against_does_not_claim_nothing_changed() {
        let new = json!({ "items": {} });
        let unchanged = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Diff {
                against: "v1.0.0",
                text: "",
            },
            old_baseline: None,
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert!(!unchanged.contains("API surface"), "{unchanged}");
        assert!(unchanged.contains("draft vs v1.0.0"), "{unchanged}");

        let items = [entry("demo", "demo::f", "fn", "Does a thing.")];
        let initial = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Initial(&items),
            old_baseline: None,
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert!(initial.contains("API surface"), "{initial}");
        assert!(initial.contains("initial public surface"), "{initial}");
        assert!(
            initial.contains("1 public items across 1 crates"),
            "{initial}"
        );
        assert!(
            initial.contains("`demo::f` (fn): Does a thing."),
            "{initial}"
        );
    }

    #[test]
    fn an_empty_initial_surface_says_so_rather_than_looking_calm() {
        let new = json!({ "items": {} });
        let text = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Initial(&[]),
            old_baseline: None,
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert!(text.contains("No public items found"), "{text}");
    }

    #[test]
    fn a_release_with_nothing_to_report_renders_only_its_heading() {
        let new = json!({ "items": {} });
        let old = json!({ "items": {} });
        let text = draft(&DraftInputs {
            changes: &[],
            icons: &Icons::default(),
            api: ApiSection::Diff {
                against: "v1.0.0",
                text: "",
            },
            old_baseline: Some(&old),
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert_eq!(text.trim(), "## Unreleased (draft vs v1.0.0)");
    }

    #[test]
    fn subjects_group_by_type_and_carry_their_pull_request() {
        let changes = changes_from_subjects(&subjects(&[
            "feat: add gate accept for reviewed regressions (#110)",
            "fix: sync untracked config into gate worktrees (#113)",
            "chore: release v0.1.19 (#112)",
            "docs: regenerate CHANGELOG.md (#115)",
            "docs: regenerate derived docs (#126)",
            "not a conventional subject",
        ]));
        assert_eq!(changes.len(), 2);
        assert_eq!(changes[0].kind, "feat");
        assert_eq!(
            changes[0].subject,
            "add gate accept for reviewed regressions"
        );
        assert_eq!(changes[0].pr, Some(110));
        assert_eq!(changes[1].pr, Some(113));
    }

    #[test]
    fn scoped_subjects_keep_their_section_and_show_the_scope() {
        let changes = changes_from_subjects(&subjects(&[
            "feat(api): add grouped daily bars (#1)",
            "fix(server): drop a stale cache (#2)",
            "chore(deps): bump serde (#3)",
            "build(deps): bump tokio (#4)",
            "build: switch to lld (#5)",
            "chore(deps-dev): bump typescript (#6)",
        ]));
        let kinds: Vec<&str> = changes.iter().map(|c| c.kind.as_str()).collect();
        assert_eq!(kinds, ["feat", "fix", "deps", "deps", "build", "deps"]);
        assert_eq!(changes[0].scope.as_deref(), Some("api"));
        assert_eq!(changes[2].scope, None);
        assert_eq!(changes[5].scope, None);
        let text = sections(&changes, &Icons::default());
        assert!(text.contains("- api: Add grouped daily bars (#1)"));
        assert!(text.contains("- server: Drop a stale cache (#2)"));
        assert!(
            text.contains("### \u{1F4E6} Dependencies\n\n- Bump serde (#3)\n- Bump tokio (#4)\n- Bump typescript (#6)")
        );
        assert!(text.contains("### \u{1F527} Internal\n\n- Switch to lld (#5)"));
    }

    #[test]
    fn a_breaking_marker_moves_the_entry_to_its_own_section() {
        let changes = changes_from_subjects(&subjects(&[
            "feat!: drop the v1 endpoints (#7)",
            "fix(api)!: rename the cursor field (#8)",
            "feat: add a thing (#9)",
        ]));
        assert!(changes[0].breaking && changes[1].breaking && !changes[2].breaking);
        let text = sections(&changes, &Icons::default());
        let breaking = text.find("Breaking changes").unwrap();
        let features = text.find("Features").unwrap();
        assert!(breaking < features);
        assert!(
            text.contains("- Drop the v1 endpoints (#7)\n- api: Rename the cursor field (#8)\n")
        );
        assert!(!text[features..].contains("v1 endpoints"));
    }

    #[test]
    fn unparsed_subjects_are_reported_but_paperwork_is_not() {
        let lines = subjects(&[
            "feat: add a thing (#1)",
            "wip: something",
            "Merge branch 'x'",
            "chore: release v0.2.0 (#3)",
            "docs: regenerate CHANGELOG.md (#4)",
        ]);
        assert_eq!(
            unparsed_subjects(&lines),
            ["wip: something", "Merge branch 'x'"]
        );
    }

    #[test]
    fn a_configured_icon_replaces_only_the_section_it_names() {
        let changes = changes_from_subjects(&subjects(&["feat: add a thing", "fix: mend a thing"]));
        let icons =
            Icons::new(BTreeMap::from([("features".to_string(), "A".to_string())])).unwrap();
        let rendered = super::sections(&changes, &icons);
        assert!(rendered.contains("### A Features"), "{rendered}");
        assert!(rendered.contains("### \u{1F41B} Fixes"), "{rendered}");
    }

    #[test]
    fn a_capitalized_section_name_is_honored_rather_than_quietly_ignored() {
        let icons =
            Icons::new(BTreeMap::from([("Features".to_string(), "A".to_string())])).unwrap();
        let changes = changes_from_subjects(&subjects(&["feat: add a thing"]));
        let rendered = super::sections(&changes, &icons);
        assert!(rendered.contains("### A Features"), "{rendered}");
    }

    #[test]
    fn dependency_bumps_get_their_own_section_rather_than_vanishing() {
        let changes = changes_from_subjects(&subjects(&[
            "deps: bump linkme from 0.3.36 to 0.3.37 (#85)",
            "deps: bump actions/download-artifact from 4.3.0 to 8.0.1 (#90)",
            "ci: harden the gate workflow (#91)",
        ]));
        let rendered = super::sections(&changes, &Icons::default());
        assert!(rendered.contains("\u{1F4E6} Dependencies"), "{rendered}");
        assert!(
            rendered.contains("- Bump linkme from 0.3.36 to 0.3.37 (#85)"),
            "{rendered}"
        );
        assert!(
            rendered.contains("- Bump actions/download-artifact from 4.3.0 to 8.0.1 (#90)"),
            "{rendered}"
        );
        let deps = rendered.find("Dependencies").unwrap();
        let internal = rendered.find("Internal").unwrap();
        assert!(deps < internal, "dependencies should precede internal");
        assert!(
            rendered.contains("- Harden the gate workflow (#91)"),
            "{rendered}"
        );
    }

    #[test]
    fn a_real_feature_that_regenerates_something_is_not_mistaken_for_a_bot() {
        let changes = changes_from_subjects(&subjects(&[
            "feat: regenerate SDK clients on a spec change",
            "docs: regenerate derived docs (#126)",
            "chore: regenerate API specs (#99)",
        ]));
        assert_eq!(changes.len(), 1);
        assert_eq!(
            changes[0].subject,
            "regenerate SDK clients on a spec change"
        );
    }

    #[test]
    fn an_icon_for_something_that_is_not_a_section_is_rejected() {
        let bad = Icons::new(BTreeMap::from([("feature".to_string(), "A".to_string())]));
        assert!(bad.unwrap_err().contains("not a changelog section"));
    }

    #[test]
    fn a_subject_opening_on_an_identifier_keeps_its_case() {
        let changes = changes_from_subjects(&subjects(&[
            "fix: soothfast.lock moves to v2",
            "fix: keep_alive is honored",
            "fix: resume changelog regen",
        ]));
        let rendered = super::sections(&changes, &Icons::default());
        assert!(
            rendered.contains("- soothfast.lock moves to v2"),
            "{rendered}"
        );
        assert!(rendered.contains("- keep_alive is honored"), "{rendered}");
        assert!(rendered.contains("- Resume changelog regen"), "{rendered}");
    }

    #[test]
    fn a_subject_without_a_pull_request_still_lists() {
        let changes = changes_from_subjects(&subjects(&["fix: land a direct commit"]));
        assert_eq!(changes.len(), 1);
        assert_eq!(changes[0].pr, None);
    }

    #[test]
    fn only_the_types_with_changes_get_a_section() {
        let new = json!({ "items": {} });
        let changes = vec![Change {
            kind: "fix".into(),
            scope: None,
            breaking: false,
            subject: "stop hashing comments".into(),
            pr: Some(124),
        }];
        let text = draft(&DraftInputs {
            changes: &changes,
            icons: &Icons::default(),
            api: ApiSection::Diff {
                against: "v1.0.0",
                text: "",
            },
            old_baseline: None,
            new_baseline: &new,
            thresholds: gate_thresholds(),
        });
        assert!(text.contains("Fixes"), "{text}");
        assert!(text.contains("- Stop hashing comments (#124)"), "{text}");
        assert!(!text.contains("Features"), "{text}");
        assert!(!text.contains("Internal"), "{text}");
    }
}