cargo-soothfast 0.1.6

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
//! `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>,
}

fn parse(args: &[String]) -> Result<ReportArgs, String> {
    let mut a = ReportArgs {
        pkg: Vec::new(),
        baseline: "base".into(),
        out: None,
        against_ref: None,
        features: 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(),
            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) in trend_chart::METRICS {
            if let Some(svg) = trend_chart::render(&points, key, name) {
                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 a = match parse(args) {
        Ok(a) => a,
        Err(e) => return err(&e),
    };
    if a.pkg.is_empty() {
        return err("report changelog needs -p PKG");
    }

    let root = match invoke::workspace_root() {
        Ok(r) => r,
        Err(e) => return err(&e.to_string()),
    };
    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;
    }

    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 text = changelog::draft(&changelog::DraftInputs {
        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
}

/// 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("");
    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,
    }
}

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

/// 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) {
        Some(notes) if !notes.is_empty() => {
            // 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'));
        }
        _ => doc.push_str(draft),
    }
    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::{changelog_already_cut, merge_changelog};

    #[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")
        ));
    }

    #[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 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 no_notes_marker_behaves_exactly_as_before() {
        let existing = "# Changelog\n\n## Unreleased (draft vs abc)\n\nold\n";
        let draft = "## Unreleased (draft vs def)\n\nnew";
        assert_eq!(
            merge_changelog(existing, draft),
            format!("# Changelog\n\n{draft}\n")
        );
    }

    #[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"));
    }
}