cargo-soothfast 0.4.4

CLI for soothfast: measure, gate, docs, spec, report
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
//! `cargo soothfast report render|changelog` — doc fragments produced from
//! recorded data: perf tables, trend charts, badges, llms.txt, and a living
//! CHANGELOG.md whose Unreleased section is regenerated in place.

use std::path::PathBuf;

use serde_json::Value;
use soothfast_report::{badges, changelog, llms, perf_table, trend_chart};

use crate::{docs_support, invoke, workspace};

pub fn run(args: &[String]) -> i32 {
    match args.first().map(String::as_str) {
        Some("render") => render(&args[1..]),
        Some("changelog") => changelog_cmd(&args[1..]),
        _ => {
            eprintln!(
                "soothfast: usage: cargo soothfast report render|changelog -p PKG [-p PKG ...] [--out DIR|FILE] [--against-ref REF]"
            );
            2
        }
    }
}

struct ReportArgs {
    // Repeatable: `report render` accepts multiple `-p PKG` to combine
    // several crates' surfaces into one llms.txt (a facade crate's own
    // surface is typically too thin on its own — see llms.rs docs).
    pkg: Vec<String>,
    baseline: String,
    out: Option<PathBuf>,
    against_ref: Option<String>,
    features: Option<String>,
    bot_author: Option<String>,
}

fn parse(args: &[String]) -> Result<ReportArgs, String> {
    let mut a = ReportArgs {
        pkg: Vec::new(),
        baseline: "base".into(),
        out: None,
        against_ref: None,
        features: None,
        bot_author: None,
    };
    let mut it = args.iter();
    while let Some(arg) = it.next() {
        match arg.as_str() {
            "-p" | "--package" => a
                .pkg
                .push(it.next().cloned().ok_or("-p needs a package name")?),
            "--baseline" => a.baseline = it.next().cloned().ok_or("--baseline needs a name")?,
            "--out" => a.out = it.next().map(PathBuf::from),
            "--against-ref" => a.against_ref = it.next().cloned(),
            "--features" => a.features = it.next().cloned(),
            "--bot-author" => a.bot_author = it.next().cloned(),
            other => return Err(format!("unknown report arg {other:?}")),
        }
    }
    Ok(a)
}

fn load_baseline_required(name: &str) -> Result<Value, String> {
    match invoke::load_baseline(name) {
        Ok(Some(b)) => Ok(b),
        Ok(None) => Err(format!(
            "no baseline {name:?} — run `cargo soothfast measure --save-baseline {name}`"
        )),
        Err(e) => Err(e.to_string()),
    }
}

fn render(args: &[String]) -> i32 {
    let a = match parse(args) {
        Ok(a) => a,
        Err(e) => return err(&e),
    };
    let baseline = match load_baseline_required(&a.baseline) {
        Ok(b) => b,
        Err(e) => return err(&e),
    };
    let root = match invoke::workspace_root() {
        Ok(r) => r,
        Err(e) => return err(&e.to_string()),
    };
    let out_dir = a.out.clone().unwrap_or_else(|| root.join("docs/perf"));
    let _ = std::fs::create_dir_all(&out_dir);
    let _ = std::fs::create_dir_all(out_dir.join("badges"));

    let mut summary =
        String::from("# Performance summary\n\n> Generated by `cargo soothfast report`\n\n");
    summary.push_str(&perf_table::markdown(&baseline));

    // Trend charts from the series, when it exists.
    let trend_path = root.join(".soothfast").join("trend.jsonl");
    if let Ok(text) = std::fs::read_to_string(&trend_path) {
        let points: Vec<Value> = text
            .lines()
            .filter_map(|l| serde_json::from_str(l).ok())
            .collect();
        for (key, name, threshold, rel) in trend_chart::METRICS {
            if let Some(svg) = trend_chart::render(&points, key, name, *threshold, *rel) {
                let file = format!("trend-{name}.svg");
                if std::fs::write(out_dir.join(&file), svg).is_ok() {
                    summary.push_str(&format!("\n![{name} trend]({file})\n"));
                    println!("report: wrote {}", out_dir.join(&file).display());
                }
            }
        }
    }

    // Badge reflects the last recorded gate verdict, never a hardcoded pass.
    let gate_passed = std::fs::read_to_string(root.join(".soothfast/gate-status.json"))
        .ok()
        .and_then(|t| serde_json::from_str::<Value>(&t).ok())
        .and_then(|v| v["passed"].as_bool());
    let gate = badges::gate_badge(gate_passed);
    let writes: &[(&str, String)] = &[
        ("summary.md", summary),
        ("summary.html", perf_table::html(&baseline)),
        ("badges/gate.json", gate.to_string()),
        ("badges/gate.svg", badges::svg_from(&gate)),
    ];
    for (file, content) in writes {
        if std::fs::write(out_dir.join(file), content).is_err() {
            return err(&format!("cannot write {file}"));
        }
        println!("report: wrote {}", out_dir.join(file).display());
    }

    // llms.txt needs the public surface (nightly rustdoc); skip with a note
    // when no package is given. Multiple -p flags combine into one digest —
    // a single facade crate's own surface is typically too thin alone.
    if a.pkg.is_empty() {
        println!(
            "report: skipped llms.txt (pass -p PKG to generate; repeat -p for multiple crates)"
        );
    } else {
        let mut entries = Vec::new();
        for pkg in &a.pkg {
            match docs_support::surface_entries(pkg, a.features.as_deref()) {
                Ok(e) => entries.extend(e),
                Err(e) => return err(&format!("llms.txt needs the API surface of {pkg}: {e}")),
            }
        }
        let label = if a.pkg.len() == 1 {
            a.pkg[0].clone()
        } else {
            a.pkg.join(", ")
        };
        let text = llms::render(&label, &entries, &baseline);
        let path = out_dir.join("llms.txt");
        if std::fs::write(&path, text).is_err() {
            return err("cannot write llms.txt");
        }
        println!("report: wrote {}", path.display());
    }
    0
}

/// One diff per package, headed by the crate name when there is more than
/// one — an unattributed `ADDED foo::bar` says nothing about where it landed.
fn surface_diffs(pkgs: &[String], refname: &str, features: Option<&str>) -> Result<String, String> {
    let mut out = String::new();
    for pkg in pkgs {
        let text = docs_support::surface_diff_text(pkg, refname, features)?;
        if text.trim().is_empty() {
            continue;
        }
        if pkgs.len() > 1 {
            out.push_str(&format!("# {pkg}\n"));
        }
        out.push_str(text.trim_end());
        out.push_str("\n\n");
    }
    Ok(out)
}

/// Measure every `-p` package that carries a bench target at the merge-base
/// of `refname`, merged into one baseline-shaped document.
///
/// One worktree for all of them; packages without a bench target there are
/// skipped rather than failing the run, since a newly measured crate simply
/// has no earlier side to compare against. `Ok(None)` when that leaves
/// nothing measured, which renders the current-only table as before.
fn measure_ref(a: &ReportArgs, refname: &str) -> Result<Option<Value>, String> {
    let pkgs = a.pkg.clone();
    let features = a.features.clone();
    println!("report: measuring {refname} in a worktree for the perf delta");
    let runs = invoke::with_merge_base_worktree(refname, |wt| {
        let mut runs = Vec::new();
        for pkg in &pkgs {
            if !workspace::has_bench_target(pkg, "soothfast", Some(wt))
                .map_err(|e| e.to_string())?
            {
                continue;
            }
            let common = invoke::CommonArgs {
                pkg: Some(pkg.clone()),
                features: features.clone(),
                ..Default::default()
            };
            let records =
                invoke::run_bench_in(&common, &[], Some(wt)).map_err(|e| e.to_string())?;
            runs.push(invoke::collect(&records));
        }
        Ok(runs)
    })?;
    if runs.is_empty() {
        return Ok(None);
    }
    let mut items = serde_json::Map::new();
    let mut noise: Option<f64> = None;
    for run in &runs {
        if let Some(obj) = invoke::run_to_items_value(run).as_object() {
            items.extend(obj.clone());
        }
        if let Some(n) = run.noise_pct {
            noise = Some(noise.map_or(n, |m: f64| m.max(n)));
        }
    }
    let mut doc = serde_json::json!({ "version": 1, "items": items });
    if let Some(n) = noise {
        doc["noise_pct"] = serde_json::json!(n);
    }
    Ok(Some(doc))
}

fn changelog_cmd(args: &[String]) -> i32 {
    let mut a = match parse(args) {
        Ok(a) => a,
        Err(e) => return err(&e),
    };

    let root = match invoke::workspace_root() {
        Ok(r) => r,
        Err(e) => return err(&e.to_string()),
    };
    let cfg = match crate::changelog_config::load(&root) {
        Ok(c) => c,
        Err(e) => return err(&e),
    };
    if a.pkg.is_empty() {
        a.pkg = cfg.packages;
    }
    if a.pkg.is_empty() {
        return err("report changelog needs -p PKG");
    }
    let gate_cfg = match crate::gate_config::load(&root) {
        Ok(g) => g,
        Err(e) => return err(&e),
    };
    a.features = resolve_features(
        a.features.take(),
        cfg.features.as_deref(),
        gate_cfg.features.as_deref(),
    );
    let path = a.out.clone().unwrap_or_else(|| root.join("CHANGELOG.md"));
    let existing = std::fs::read_to_string(&path).unwrap_or_default();

    // A release PR renames the top heading away from "Unreleased" before
    // its own CI run gets here — regenerating on top of that would inject
    // a fresh Unreleased section the PR is already in the middle of
    // retiring, which then has to be hand-deleted after every release.
    if changelog_already_cut(&existing, a.against_ref.as_deref()) {
        println!(
            "report: {} already has a released top section — nothing to regenerate",
            path.display()
        );
        return 0;
    }
    if a.against_ref.is_none()
        && let Some(prior) = prior_release_ref(&existing)
    {
        let msg = match prior {
            PriorRelease::Drafted(refname) => format!(
                "{} already has a prior release drafted against {refname}, but no \
                 --against-ref was given; regenerating would replace it with an empty \
                 initial-surface section. Pass --against-ref {refname} (tags may not \
                 have been fetched).",
                path.display()
            ),
            PriorRelease::Released(version) if !version.is_empty() => format!(
                "{} already has a released {version} section, but no --against-ref \
                 was given; regenerating would replace the Unreleased section with an \
                 empty initial-surface one. Pass --against-ref for the tag {version} \
                 shipped under (tags may not have been fetched).",
                path.display()
            ),
            PriorRelease::Released(_) => format!(
                "{} already has a released section, but no --against-ref was given; \
                 regenerating would replace the Unreleased section with an empty \
                 initial-surface one. Pass --against-ref for the tag it shipped under \
                 (tags may not have been fetched).",
                path.display()
            ),
        };
        return err(&msg);
    }

    let baseline = match load_baseline_required(&a.baseline) {
        Ok(b) => b,
        Err(e) => return err(&e),
    };

    // Without a reference there is no earlier surface to diff against, so
    // the release is described by what it contains. A facade crate's own
    // surface is thin; pass every crate whose API ships.
    let (diff_text, entries) = match &a.against_ref {
        Some(refname) => match surface_diffs(&a.pkg, refname, a.features.as_deref()) {
            Ok(t) => (t, Vec::new()),
            Err(e) => return err(&e),
        },
        None => {
            let mut all = Vec::new();
            for pkg in &a.pkg {
                match docs_support::surface_entries(pkg, a.features.as_deref()) {
                    Ok(e) => all.extend(e),
                    Err(e) => return err(&e),
                }
            }
            (String::new(), all)
        }
    };
    // Measuring the ref turns the Performance section from a point-in-time
    // snapshot into "what moved", which is what a changelog reader wants and
    // what keeps a no-op merge from rewriting the whole table.
    let ref_baseline = match &a.against_ref {
        Some(refname) => match measure_ref(&a, refname) {
            Ok(b) => b,
            Err(e) => return err(&e),
        },
        None => None,
    };
    let bot_author = resolve_bot_author(a.bot_author.take(), cfg.bot_author.as_deref());
    let changes = match &a.against_ref {
        Some(refname) => match merged_changes(refname, &bot_author) {
            Ok(c) => c,
            Err(e) => return err(&e),
        },
        None => Vec::new(),
    };
    let text = changelog::draft(&changelog::DraftInputs {
        changes: &changes,
        icons: &cfg.icons,
        api: match &a.against_ref {
            Some(refname) => changelog::ApiSection::Diff {
                against: refname,
                text: &diff_text,
            },
            None => changelog::ApiSection::Initial(&entries),
        },
        old_baseline: ref_baseline.as_ref(),
        new_baseline: &baseline,
        thresholds: changelog::PerfThresholds {
            instructions_pct: crate::gate::INSTRUCTIONS_THRESHOLD_PCT,
            allocs_pct: crate::gate::ALLOC_THRESHOLD_PCT as f64,
        },
    });

    if std::fs::write(&path, merge_changelog(&existing, &text)).is_err() {
        return err(&format!("cannot write {}", path.display()));
    }
    println!("report: regenerated {}", path.display());
    0
}

/// The features `report changelog` reads the API surface under: the command
/// line first, then `[changelog] features`, then `[gate] features`.
fn resolve_features(
    cli: Option<String>,
    changelog: Option<&str>,
    gate: Option<&str>,
) -> Option<String> {
    cli.or_else(|| changelog.or(gate).map(str::to_string))
}

/// The author `report changelog` leaves out: the command line first, then
/// `[changelog] bot-author`, then the slug the action ships with.
fn resolve_bot_author(cli: Option<String>, config: Option<&str>) -> String {
    cli.unwrap_or_else(|| config.unwrap_or(DEFAULT_BOT_AUTHOR).to_string())
}

/// Author of the soothfast bot's own commits, as `action/land.sh` commits
/// them under the default `bot-slug`.
const DEFAULT_BOT_AUTHOR: &str = "soothfast-bot[bot]";

/// Separates author from subject in the log format below. A unit separator
/// occurs in neither field.
const LOG_FIELD_SEP: char = '\u{1f}';

/// Subjects from `%an%x1f%s` log lines, minus the ones `bot_author` wrote.
/// That one author and no other: `dependabot[bot]` writes real changelog
/// entries, and a rule matching every `[bot]` would delete them all.
fn subjects_excluding_author(log: &str, bot_author: &str) -> Vec<String> {
    log.lines()
        .filter_map(|line| line.split_once(LOG_FIELD_SEP))
        .filter(|(author, _)| *author != bot_author)
        .map(|(_, subject)| subject.to_string())
        .collect()
}

/// Conventional-commit subjects merged since `refname`, newest first, with
/// the soothfast bot's own regeneration commits left out. Read from the log
/// rather than a forge API: every merge lands as a squash whose subject
/// already carries its pull request number, and whose author survives it.
fn merged_changes(refname: &str, bot_author: &str) -> Result<Vec<changelog::Change>, String> {
    let range = format!("{refname}..HEAD");
    let log = invoke::git(&["log", "--format=%an%x1f%s", &range]).map_err(|e| e.to_string())?;
    let subjects = subjects_excluding_author(&log, bot_author);
    let unparsed = changelog::unparsed_subjects(&subjects);
    if !unparsed.is_empty() {
        println!(
            "report: {} subject(s) since {refname} are not conventional commits and are left out:",
            unparsed.len()
        );
        for subject in unparsed {
            println!("  {subject}");
        }
    }
    Ok(changelog::changes_from_subjects(&subjects))
}

/// True only for the specific race the guard exists to catch: a release PR
/// that has renamed the top heading away from "Unreleased" in its own
/// branch, running before the matching tag exists. That PR's own CI still
/// diffs against the *previous* release's tag, so regenerating would inject
/// a fresh Unreleased section duplicating the one it's mid-flight retiring.
///
/// A normal PR sometime after that release has the same top heading, but by
/// then `against_ref` (the latest tag reachable from HEAD) has caught up to
/// match it — that's the signal a new Unreleased section is legitimately
/// due, not a race, so this returns false and regeneration proceeds.
///
/// A file with no `## ` heading yet, or one still under "Unreleased", is
/// never "already cut".
fn changelog_already_cut(existing: &str, against_ref: Option<&str>) -> bool {
    let Some(heading) = existing.lines().find_map(|l| l.strip_prefix("## ")) else {
        return false;
    };
    let heading = heading.trim_start();
    if heading.starts_with("Unreleased") || heading.starts_with("[Unreleased]") {
        return false;
    }
    let heading_version = heading
        .split_whitespace()
        .next()
        .unwrap_or("")
        .trim_start_matches('[')
        .split(']')
        .next()
        .unwrap_or("");
    match against_ref {
        Some(r) => heading_version != r.trim_start_matches('v'),
        // No tag at all reachable from HEAD only happens for a repo's very
        // first release, still mid-flight in its own PR — the same race,
        // just without a previous tag to compare against. Stay conservative.
        None => true,
    }
}

/// What a populated Unreleased section says about a prior release, when
/// `existing` shows one and `--against-ref` was left out. `Drafted` is the
/// ref an `Unreleased (draft vs X)` heading already names; `Released` is
/// the version on a released `## ` heading below it, not necessarily a
/// git ref (this repo's own headings are bare versions like `0.3.3`, not
/// tags like `v0.3.3`), so a caller shouldn't hand it to `--against-ref`
/// as-is. `None` means there is nothing to lose: an empty or missing file,
/// or an Unreleased heading that never named a ref.
#[derive(Debug, PartialEq)]
enum PriorRelease {
    Drafted(String),
    Released(String),
}

fn prior_release_ref(existing: &str) -> Option<PriorRelease> {
    let mut headings = existing.lines().filter_map(|l| l.strip_prefix("## "));
    let top = headings.next()?.trim_start();
    if let Some(rest) = top.strip_prefix("Unreleased (draft vs ") {
        return rest
            .split(')')
            .next()
            .map(|r| PriorRelease::Drafted(r.to_string()));
    }
    let is_unreleased = |h: &str| h.starts_with("Unreleased") || h.starts_with("[Unreleased]");
    let released = if is_unreleased(top) {
        headings.find(|h| !is_unreleased(h.trim_start()))?
    } else {
        top
    };
    let version = released
        .split_whitespace()
        .next()
        .unwrap_or("")
        .trim_start_matches('[')
        .split(']')
        .next()
        .unwrap_or("");
    Some(PriorRelease::Released(version.to_string()))
}

const NOTES_START: &str = "<!-- soothfast:notes -->";
const NOTES_END: &str = "<!-- /soothfast:notes -->";

/// Prompts for the sections a reader wants and no measurement can supply.
/// Commented out so an unfilled block renders as nothing.
const NOTES_SCAFFOLD: &str = "\
<!-- ### Overview -->
<!-- What this release means for someone using it. One paragraph. -->

<!-- ### Upgrade notes -->
<!-- What a consumer has to do. \"Nothing\" is a useful answer. -->
";

/// A maintainer's hand-written prose survives regeneration by living inside
/// a `soothfast:notes` marker pair in the Unreleased section; everything
/// else there is bot-owned and gets replaced. Malformed markers (missing or
/// out-of-order) are treated as no notes, rather than guessing.
fn extract_notes(unreleased: &str) -> Option<&str> {
    let start = unreleased.find(NOTES_START)? + NOTES_START.len();
    let end = unreleased[start..].find(NOTES_END)? + start;
    Some(unreleased[start..end].trim())
}

/// Replace the previous Unreleased section with the fresh draft, keeping
/// released sections — regeneration is idempotent, one Unreleased at a time.
/// Keep-a-Changelog files are respected: the preamble prose before the first
/// section survives, and a bracketed `## [Unreleased]` heading counts as the
/// Unreleased section to replace. A `soothfast:notes` block inside the old
/// Unreleased section rides along into the new one (see `extract_notes`).
fn merge_changelog(existing: &str, draft: &str) -> String {
    let mut preamble = String::new();
    let mut released = String::new();
    let mut unreleased = String::new();
    let mut seen_section = false;
    let mut keep = false;
    for line in existing.lines() {
        if let Some(h) = line.strip_prefix("## ") {
            seen_section = true;
            let h = h.trim_start();
            keep = !(h.starts_with("Unreleased") || h.starts_with("[Unreleased]"));
        }
        if !seen_section {
            // The title is re-emitted below; keep any other preamble prose.
            if line.trim() != "# Changelog" {
                preamble.push_str(line);
                preamble.push('\n');
            }
        } else if keep {
            released.push_str(line);
            released.push('\n');
        } else {
            unreleased.push_str(line);
            unreleased.push('\n');
        }
    }
    let mut doc = String::from("# Changelog\n");
    let pre = preamble.trim();
    if !pre.is_empty() {
        doc.push('\n');
        doc.push_str(pre);
        doc.push('\n');
    }
    doc.push('\n');
    match extract_notes(&unreleased).filter(|n| !n.is_empty()) {
        Some(notes) => {
            // Splice right after the heading line, ahead of the bot's own
            // API-surface/Performance sections.
            let (heading, rest) = draft.split_once('\n').unwrap_or((draft, ""));
            doc.push_str(heading);
            doc.push('\n');
            doc.push('\n');
            doc.push_str(NOTES_START);
            doc.push('\n');
            doc.push_str(notes);
            doc.push('\n');
            doc.push_str(NOTES_END);
            doc.push('\n');
            doc.push('\n');
            doc.push_str(rest.trim_start_matches('\n'));
        }
        None => {
            let (heading, rest) = draft.split_once('\n').unwrap_or((draft, ""));
            doc.push_str(heading);
            doc.push_str("\n\n");
            doc.push_str(NOTES_START);
            doc.push('\n');
            doc.push_str(NOTES_SCAFFOLD);
            doc.push_str(NOTES_END);
            doc.push_str("\n\n");
            doc.push_str(rest.trim_start_matches('\n'));
        }
    }
    doc.push('\n');
    if !released.is_empty() {
        doc.push('\n');
        doc.push_str(released.trim_end());
        doc.push('\n');
    }
    doc
}

fn err(msg: &str) -> i32 {
    eprintln!("soothfast: {msg}");
    2
}

#[cfg(test)]
mod tests {
    use super::{
        DEFAULT_BOT_AUTHOR, PriorRelease, changelog_already_cut, merge_changelog,
        prior_release_ref, resolve_bot_author, resolve_features, subjects_excluding_author,
    };

    #[test]
    fn a_release_pr_still_diffing_against_the_previous_tag_is_already_cut() {
        // The race the guard exists for: top heading says 0.1.3, but the
        // ref this run would diff against (v0.1.2, since v0.1.3 isn't
        // tagged yet) is one release behind it.
        assert!(changelog_already_cut(
            "# Changelog\n\n## 0.1.3 - 2026-08-09\n\n- shipped\n",
            Some("v0.1.2")
        ));
        assert!(changelog_already_cut(
            "# Changelog\n\n## [2.8.0] - 2026-07-10\n\n- shipped\n",
            Some("v2.7.0")
        ));
    }

    #[test]
    fn a_release_pr_with_no_prior_tag_at_all_is_already_cut() {
        // A repo's very first release has no earlier tag to compare
        // against; stay conservative rather than guess.
        assert!(changelog_already_cut(
            "# Changelog\n\n## 0.1.0 - 2026-08-01\n\n- shipped\n",
            None
        ));
    }

    #[test]
    fn a_normal_pr_after_the_tag_catches_up_is_not_already_cut() {
        // Once v0.1.3 is tagged, a later PR's `against_ref` matches the top
        // heading exactly — that's not a race, it's a new cycle legitimately
        // starting, so regeneration should proceed and prepend a fresh
        // Unreleased section.
        assert!(!changelog_already_cut(
            "# Changelog\n\n## 0.1.3 - 2026-08-09\n\n- shipped\n",
            Some("v0.1.3")
        ));
        // Keep-a-Changelog repos bracket the version in the heading.
        assert!(!changelog_already_cut(
            "# Changelog\n\n## [3.0.0] - 2026-08-30\n\n- shipped\n",
            Some("v3.0.0")
        ));
        // Generators that link the version to a compare view close the
        // bracket mid-token, so the version has to be cut at the `]`.
        assert!(!changelog_already_cut(
            "# Changelog\n\n## [3.0.0](https://github.com/o/r/compare/v2.9.0...v3.0.0) - 2026-08-30\n\n- shipped\n",
            Some("v3.0.0")
        ));
    }

    #[test]
    fn a_normal_pr_with_an_unreleased_section_is_not_already_cut() {
        assert!(!changelog_already_cut(
            "# Changelog\n\n## Unreleased (draft vs v0.1.1)\n\nold\n",
            Some("v0.1.1")
        ));
        assert!(!changelog_already_cut(
            "# Changelog\n\n## [Unreleased]\n\nold\n",
            None
        ));
    }

    #[test]
    fn a_file_with_no_sections_yet_is_not_already_cut() {
        assert!(!changelog_already_cut("", None));
        assert!(!changelog_already_cut("# Changelog\n", Some("v0.1.0")));
    }

    #[test]
    fn a_released_section_names_its_own_version() {
        assert_eq!(
            prior_release_ref("# Changelog\n\n## 0.1.0 - 2026-08-01\n\n- shipped\n"),
            Some(PriorRelease::Released("0.1.0".to_string()))
        );
    }

    #[test]
    fn a_draft_vs_heading_names_the_ref_it_was_drafted_against() {
        assert_eq!(
            prior_release_ref("# Changelog\n\n## Unreleased (draft vs v0.1.1)\n\nold\n"),
            Some(PriorRelease::Drafted("v0.1.1".to_string()))
        );
    }

    #[test]
    fn a_first_release_has_no_prior_ref() {
        assert_eq!(prior_release_ref(""), None);
        assert_eq!(
            prior_release_ref("# Changelog\n\n## Unreleased (initial public surface)\n\nnew\n"),
            None
        );
        assert_eq!(
            prior_release_ref("# Changelog\n\n## Unreleased\n\nnew\n"),
            None
        );
    }

    #[test]
    fn a_keep_a_changelog_release_under_a_bare_unreleased_heading_is_found() {
        assert_eq!(
            prior_release_ref(
                "# Changelog\n\n## [Unreleased]\n\nstale\n\n## [0.1.0] - 2026-08-01\n\n- shipped\n"
            ),
            Some(PriorRelease::Released("0.1.0".to_string()))
        );
    }

    #[test]
    fn a_released_heading_with_no_version_token_still_refuses() {
        assert_eq!(
            prior_release_ref("# Changelog\n\n##  \n\n- shipped\n"),
            Some(PriorRelease::Released(String::new()))
        );
    }

    #[test]
    fn merge_replaces_unreleased_and_keeps_released() {
        let existing =
            "# Changelog\n\n## Unreleased (draft vs abc)\n\nold\n\n## 0.1.0\n\n- shipped\n";
        let merged = merge_changelog(existing, "## Unreleased (draft vs def)\n\nnew");
        assert!(merged.contains("draft vs def"));
        assert!(!merged.contains("old"));
        assert!(merged.contains("## 0.1.0"));
        assert!(merged.contains("- shipped"));
        // Idempotent: merging the same draft again changes nothing.
        assert_eq!(
            merged,
            merge_changelog(&merged, "## Unreleased (draft vs def)\n\nnew")
        );
    }

    #[test]
    fn merge_into_empty_file() {
        let merged = merge_changelog("", "## Unreleased (draft vs abc)\n\nnew");
        assert!(merged.starts_with("# Changelog\n\n## Unreleased"));
    }

    #[test]
    fn merge_respects_keep_a_changelog_files() {
        let existing = "# Changelog\n\nAll notable changes are documented here.\n\n\
            ## [Unreleased]\n\nstale\n\n## [2.8.0] - 2026-07-10\n\n- shipped\n";
        let merged = merge_changelog(existing, "## Unreleased (draft vs v2.8.0)\n\nnew");
        // Preamble prose survives; the bracketed Unreleased section is replaced.
        assert!(merged.contains("All notable changes are documented here."));
        assert!(!merged.contains("stale"));
        assert!(!merged.contains("## [Unreleased]"));
        assert!(merged.contains("## [2.8.0] - 2026-07-10"));
        assert_eq!(
            merged,
            merge_changelog(&merged, "## Unreleased (draft vs v2.8.0)\n\nnew")
        );
    }

    #[test]
    fn hand_written_notes_survive_regeneration() {
        let existing = "# Changelog\n\n## Unreleased (draft vs abc)\n\n\
            <!-- soothfast:notes -->\nDomain handles gain chart/history.\n\
            <!-- /soothfast:notes -->\n\n### API surface\n\nold\n";
        let draft = "## Unreleased (draft vs def)\n\n### API surface\n\nnew";
        let merged = merge_changelog(existing, draft);
        assert!(merged.contains("Domain handles gain chart/history."));
        assert!(merged.contains("### API surface\n\nnew"));
        // A blank line separates the closing marker from the next section.
        assert!(merged.contains("<!-- /soothfast:notes -->\n\n### API surface"));
        // Notes land ahead of the bot's own sections, right after the heading.
        let notes_pos = merged.find("Domain handles").unwrap();
        let surface_pos = merged.find("### API surface").unwrap();
        assert!(notes_pos < surface_pos);
        // Idempotent: re-merging with the same draft carries the notes forward again.
        assert_eq!(merged, merge_changelog(&merged, draft));
    }

    #[test]
    fn a_section_with_no_notes_yet_gets_the_scaffold() {
        let existing = "# Changelog\n\n## Unreleased (draft vs abc)\n\nold\n";
        let merged = merge_changelog(existing, "## Unreleased (draft vs def)\n\nnew");
        assert!(!merged.contains("old"), "{merged}");
        assert!(merged.contains("new"), "{merged}");
        assert!(merged.contains("<!-- ### Overview -->"), "{merged}");
        assert!(merged.contains("<!-- ### Upgrade notes -->"), "{merged}");
        let notes = merged.find("<!-- soothfast:notes -->").unwrap();
        assert!(notes < merged.find("new").unwrap(), "{merged}");
    }

    #[test]
    fn the_scaffold_is_not_written_over_prose_that_exists() {
        let existing = "# Changelog\n\n## Unreleased (draft vs abc)\n\n\
            <!-- soothfast:notes -->\n### Overview\n\nwhat shipped\n\
            <!-- /soothfast:notes -->\n\nold\n";
        let merged = merge_changelog(existing, "## Unreleased (draft vs def)\n\nnew");
        assert!(merged.contains("what shipped"), "{merged}");
        assert!(!merged.contains("<!-- ### Overview -->"), "{merged}");
    }

    #[test]
    fn unclosed_notes_marker_is_treated_as_absent() {
        let existing = "# Changelog\n\n## Unreleased (draft vs abc)\n\n\
            <!-- soothfast:notes -->\nnever closed\n";
        let merged = merge_changelog(existing, "## Unreleased (draft vs def)\n\nnew");
        assert!(!merged.contains("never closed"));
        assert!(merged.contains("new"));
    }
    #[test]
    fn an_explicit_features_flag_beats_both_tables() {
        let got = resolve_features(Some("cli".into()), Some("changelog"), Some("gate"));
        assert_eq!(got.as_deref(), Some("cli"));
    }

    #[test]
    fn changelog_features_beat_gate_features() {
        let got = resolve_features(None, Some("changelog"), Some("gate"));
        assert_eq!(got.as_deref(), Some("changelog"));
    }

    #[test]
    fn gate_features_fill_in_when_nothing_else_does() {
        assert_eq!(
            resolve_features(None, None, Some("gate")).as_deref(),
            Some("gate")
        );
        assert_eq!(resolve_features(None, None, None), None);
    }

    #[test]
    fn the_bot_s_own_regeneration_commits_are_left_out() {
        let log = "soothfast-bot[bot]\u{1f}chore: regenerate soothfast outputs (#474)\n\
                   Harvey Tseng\u{1f}feat: read gate features from soothfast.toml (#475)\n";
        assert_eq!(
            subjects_excluding_author(log, DEFAULT_BOT_AUTHOR),
            ["feat: read gate features from soothfast.toml (#475)"]
        );
    }

    #[test]
    fn dependabot_commits_survive_the_filter() {
        let log = "dependabot[bot]\u{1f}chore(deps): bump serde from 1.0.2 to 1.0.3 (#476)\n\
                   soothfast-bot[bot]\u{1f}docs: regenerate CHANGELOG.md (#477)\n";
        assert_eq!(
            subjects_excluding_author(log, DEFAULT_BOT_AUTHOR),
            ["chore(deps): bump serde from 1.0.2 to 1.0.3 (#476)"]
        );
    }

    #[test]
    fn a_renamed_bot_author_filters_in_place_of_the_default() {
        let log = "acme-bot[bot]\u{1f}chore: regenerate soothfast outputs (#12)\n\
                   soothfast-bot[bot]\u{1f}feat: ship a thing (#13)\n";
        assert_eq!(
            subjects_excluding_author(log, "acme-bot[bot]"),
            ["feat: ship a thing (#13)"]
        );
    }

    #[test]
    fn an_explicit_bot_author_flag_beats_the_table() {
        assert_eq!(
            resolve_bot_author(Some("cli[bot]".into()), Some("toml[bot]")),
            "cli[bot]"
        );
    }

    #[test]
    fn the_table_fills_in_for_a_repo_that_renamed_the_slug() {
        assert_eq!(resolve_bot_author(None, Some("toml[bot]")), "toml[bot]");
    }

    #[test]
    fn the_shipped_slug_is_the_last_resort() {
        assert_eq!(resolve_bot_author(None, None), DEFAULT_BOT_AUTHOR);
    }

    #[test]
    fn a_subject_the_bot_did_not_write_is_kept_verbatim() {
        let log = "Harvey Tseng\u{1f}fix(server): drop a cache (#478)\n";
        assert_eq!(
            subjects_excluding_author(log, DEFAULT_BOT_AUTHOR),
            ["fix(server): drop a cache (#478)"]
        );
    }
}