Skip to main content

xtask/
lib.rs

1//! The pending-increment format validator (increment-allocation track, Slice 0).
2//!
3//! A feature PR adds one `design/pending/<slug>.md` declaring its bump level, a
4//! one-line changelog blurb, and — when it records a decision — one or more ADR
5//! prose blocks. It writes *no* version and *no* ADR number: those are the two
6//! serial counters that the merge-time stamp assigns on `main`, so that parallel
7//! increments stop conflicting on them. See `design/pending/README.md` and
8//! ADR 0206 (`design/decisions/0206-allocation-on-main.md`).
9//!
10//! This module is the *format contract* between that human-authored file and the
11//! future stamp. It is process tooling, not compiler behaviour, which is why it
12//! lives in the unpublished `xtask` crate rather than in `bynk`'s test suite.
13//! [`check_all`] is exercised two ways: an integration test (`tests/pending_files.rs`)
14//! runs it over the real `design/pending/**` as a drift guard, and the
15//! `check-pending` binary subcommand exposes it for local runs.
16
17use std::fs;
18use std::path::{Path, PathBuf};
19
20pub mod bench;
21pub mod delivery_isolation;
22pub mod editor_contract;
23pub mod fn_length;
24pub mod grammar;
25pub mod greenfield_status;
26pub mod manifest_schema;
27pub mod module_lines;
28pub mod release_notes;
29pub mod release_pages;
30pub mod site_page;
31pub mod stamp;
32pub mod tiers;
33
34/// The bump level an increment declares. The stamp turns this into the next
35/// `X.Y.Z` in merge order; the format never carries a concrete number.
36#[derive(Debug, PartialEq, Eq)]
37pub enum Level {
38    Minor,
39    Patch,
40}
41
42/// One ADR block. The stamp writes `design/decisions/NNNN-<slug>.md` — a
43/// `# NNNN — <title>` heading, a status line, then `body` verbatim — and a
44/// `decisions/README.md` index row (`**<title>** … <summary>`), assigning
45/// `NNNN` at merge. `title` is required (the file heading and the index bold
46/// need it); `summary` defaults to `title`, `status` to `Accepted`.
47#[derive(Debug, PartialEq, Eq)]
48pub struct Adr {
49    pub slug: String,
50    pub title: String,
51    pub summary: Option<String>,
52    pub status: Option<String>,
53    pub body: String,
54}
55
56impl Adr {
57    /// The one-line distillation for the index row — the author's `summary`, or
58    /// the title when none was given.
59    pub fn summary(&self) -> &str {
60        self.summary.as_deref().unwrap_or(&self.title)
61    }
62
63    /// The ADR status — the author's `status`, or `Accepted`.
64    pub fn status(&self) -> &str {
65        self.status.as_deref().unwrap_or("Accepted")
66    }
67}
68
69/// One `raises:` entry: a growth probe and the reason its reading may rise.
70#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Raise {
72    pub probe: String,
73    pub reason: String,
74}
75
76/// A parsed, validated pending-increment file.
77#[derive(Debug, PartialEq, Eq)]
78pub struct Pending {
79    pub level: Level,
80    pub changelog: String,
81    pub adrs: Vec<Adr>,
82    /// Greenfield reference rule ids (`R2.3`) this increment closes (#1001).
83    /// Optional and usually empty — most increments don't close a tracked rule.
84    /// Syntax-checked here (each entry matches `R<major>.<minor>`); whether the
85    /// id actually exists in `design/bynk-greenfield-compiler.md` is checked
86    /// separately by [`known_rule_ids`], which needs the repo root this pure
87    /// parse doesn't have.
88    pub closes_rule: Vec<String>,
89    /// Gated greenfield-status probes this increment moves (see
90    /// `design/pending/README.md`). Acknowledging a probe here is what lets the
91    /// increment change its reading *without* editing the shared
92    /// `design/greenfield-status.md` table: the gate accepts an acknowledged
93    /// disagreement, and the stamp rewrites the table's gated rows on `main` in
94    /// merge order. Optional and usually empty. Each entry is checked against
95    /// [`greenfield_status::GATED_PROBES`].
96    pub probes: Vec<String>,
97    /// Growth probes this increment deliberately *raises*, each with its reason
98    /// (#3679). A [`greenfield_status::GROWTH_PROBES`] reading may fall under
99    /// `probes:` alone, but may only rise when a pending file also lists it
100    /// here. Optional and usually empty. A raised probe must still be named in
101    /// `probes:` (or have its table row committed) for the exact-match gate.
102    pub raises: Vec<Raise>,
103    /// The increment's breaking-change note (#3178): one line of Markdown saying
104    /// what breaks, the diagnostic a user will see and the fix. Optional — absent
105    /// for the (vast majority of) increments that break nothing. The stamp
106    /// collects it into the Book's `reference/upgrading.md`, which the release
107    /// body's "Upgrading from vX" section is assembled from.
108    pub breaking: Option<String>,
109}
110
111/// The repo root, resolved from this crate's manifest dir so it's independent
112/// of the working directory (the same trick `decisions_index` uses).
113pub fn repo_root() -> PathBuf {
114    PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..")
115}
116
117/// `design/pending/` under [`repo_root`].
118pub fn pending_dir() -> PathBuf {
119    repo_root().join("design/pending")
120}
121
122/// Validate every `*.md` under [`pending_dir`] except `README.md` (the format
123/// doc, excluded like the decisions index excludes its own README). Returns the
124/// number of pending files validated, or every error found across all files
125/// (each prefixed with its filename) so one run reports the whole picture.
126pub fn check_all() -> Result<usize, Vec<String>> {
127    validated_pending_in(&repo_root()).map(|ps| ps.len())
128}
129
130/// Read and validate the pending files under `root/design/pending` (skipping
131/// `README.md`), sorted by filename. Root-parameterised so the stamp — and its
132/// fixture tests — can target any tree; [`check_all`] is this over the real
133/// [`repo_root`].
134///
135/// Also cross-checks each file's `closes_rule` entries against
136/// [`known_rule_ids`] — a syntactically valid id (`is_rule_id`, checked in
137/// [`validate`]) that names no rule the reference actually has is still an
138/// error, just one that needs `root` to catch, which the pure per-file parse
139/// doesn't have.
140pub fn validated_pending_in(root: &Path) -> Result<Vec<(String, Pending)>, Vec<String>> {
141    let dir = root.join("design/pending");
142    let entries = match fs::read_dir(&dir) {
143        Ok(e) => e,
144        Err(err) => return Err(vec![format!("cannot read {}: {err}", dir.display())]),
145    };
146
147    let mut names: Vec<String> = entries
148        .filter_map(Result::ok)
149        .map(|e| e.file_name().to_string_lossy().into_owned())
150        .filter(|n| n.ends_with(".md") && n != "README.md")
151        .collect();
152    names.sort();
153
154    let mut parsed = Vec::new();
155    let mut errors = Vec::new();
156    for name in names {
157        let content = match fs::read_to_string(dir.join(&name)) {
158            Ok(c) => c,
159            Err(err) => {
160                errors.push(format!("{name}: cannot read: {err}"));
161                continue;
162            }
163        };
164        match validate(&name, &content) {
165            Ok(p) => parsed.push((name, p)),
166            Err(errs) => errors.extend(errs.into_iter().map(|e| format!("{name}: {e}"))),
167        }
168    }
169
170    if !parsed.iter().any(|(_, p)| !p.closes_rule.is_empty()) {
171        // No file cites a rule — skip reading the (large) reference doc at all.
172    } else {
173        match known_rule_ids(root) {
174            Ok(known) => {
175                for (name, pending) in &parsed {
176                    for rule in &pending.closes_rule {
177                        if !known.contains(rule) {
178                            errors.push(format!(
179                                "{name}: closes_rule cites {rule:?}, which is not a rule id in \
180                                 design/bynk-greenfield-compiler.md"
181                            ));
182                        }
183                    }
184                }
185            }
186            Err(e) => errors.push(format!(
187                "cannot validate closes_rule entries against the reference: {e}"
188            )),
189        }
190    }
191
192    if errors.is_empty() {
193        Ok(parsed)
194    } else {
195        Err(errors)
196    }
197}
198
199/// Validate a single pending file's `content`. `filename` is used to check the
200/// stem is a kebab-case slug. Returns every problem found (not just the first),
201/// so a malformed file reports completely.
202pub fn validate(filename: &str, content: &str) -> Result<Pending, Vec<String>> {
203    let mut errors = Vec::new();
204
205    let stem = Path::new(filename)
206        .file_stem()
207        .map(|s| s.to_string_lossy().into_owned())
208        .unwrap_or_default();
209    if !is_kebab(&stem) {
210        errors.push(format!(
211            "filename stem {stem:?} is not a kebab-case slug (a-z, 0-9, single hyphens)"
212        ));
213    }
214
215    let (level, changelog, closes_rule, probes, raises, breaking) =
216        match parse_frontmatter(content, &mut errors) {
217            Some(fm) => fm,
218            None => return Err(errors),
219        };
220    let adrs = parse_adrs(content, &mut errors);
221
222    if errors.is_empty() {
223        Ok(Pending {
224            level: level.expect("no errors implies a level"),
225            changelog: changelog.expect("no errors implies a changelog"),
226            adrs,
227            closes_rule,
228            probes,
229            raises,
230            breaking,
231        })
232    } else {
233        Err(errors)
234    }
235}
236
237/// The header fields [`parse_frontmatter`] recovers: `level`, `changelog`,
238/// `closes_rule`, `probes`, `raises`, `breaking`.
239type Frontmatter = (
240    Option<Level>,
241    Option<String>,
242    Vec<String>,
243    Vec<String>,
244    Vec<Raise>,
245    Option<String>,
246);
247
248/// Parse and validate the `---`-delimited header. Pushes errors; returns the
249/// fields when present and well-formed (`closes_rule` and `probes` default to
250/// empty rather than `Option` — they're genuinely optional, unlike `level`/`changelog`). Returns
251/// `None` only when the frontmatter block itself is missing/unterminated
252/// (nothing to recover).
253fn parse_frontmatter(content: &str, errors: &mut Vec<String>) -> Option<Frontmatter> {
254    let mut lines = content.lines();
255    if lines.next().map(str::trim_end) != Some("---") {
256        errors.push("must open with a `---` frontmatter fence on line 1".into());
257        return None;
258    }
259
260    let mut header = Vec::new();
261    let mut closed = false;
262    for line in lines {
263        if line.trim_end() == "---" {
264            closed = true;
265            break;
266        }
267        header.push(line);
268    }
269    if !closed {
270        errors.push("frontmatter is not closed with a `---` fence".into());
271        return None;
272    }
273
274    let mut level = None;
275    let mut changelog = None;
276    let mut closes_rule = Vec::new();
277    let mut probes = Vec::new();
278    let mut raises: Vec<Raise> = Vec::new();
279    let mut breaking = None;
280    // Track key presence separately from a valid value: a key that is present
281    // but malformed reports its own error and must not also be "missing".
282    let mut saw_level = false;
283    let mut saw_changelog = false;
284    let mut saw_closes_rule = false;
285    let mut saw_probes = false;
286    let mut saw_breaking = false;
287    for raw in header {
288        let line = raw.trim();
289        if line.is_empty() {
290            continue;
291        }
292        let Some((key, value)) = line.split_once(':') else {
293            errors.push(format!("frontmatter line is not `key: value`: {raw:?}"));
294            continue;
295        };
296        let key = key.trim();
297        let value = value.trim();
298        match key {
299            "level" => {
300                if saw_level {
301                    errors.push("duplicate frontmatter key `level`".into());
302                }
303                saw_level = true;
304                level = match value {
305                    "minor" => Some(Level::Minor),
306                    "patch" => Some(Level::Patch),
307                    other => {
308                        errors.push(format!("level must be `minor` or `patch`, got {other:?}"));
309                        None
310                    }
311                };
312            }
313            "changelog" => {
314                if saw_changelog {
315                    errors.push("duplicate frontmatter key `changelog`".into());
316                }
317                saw_changelog = true;
318                if value.is_empty() {
319                    errors.push("changelog must not be empty".into());
320                } else if looks_like_version_prefix(value) {
321                    errors.push(format!(
322                        "changelog must not start with a version number (the stamp adds it): {value:?}"
323                    ));
324                } else if is_wrapped_in_quotes(value) {
325                    errors.push(format!(
326                        "changelog is wrapped in quotes: {value:?}. The value is Markdown, not YAML, \
327                         and lands verbatim in the changelog row, so the quotes would show. Write it \
328                         without them."
329                    ));
330                } else if let Some(dest) = relative_markdown_link_in(value) {
331                    errors.push(format!(
332                        "changelog reads as a Markdown link to the relative destination {dest:?} \
333                         — the blurb is inserted verbatim into the Book's changelog table, so a \
334                         bare `x[T](y)` in prose becomes a link the docs site's link-checker \
335                         rejects (and it only sees the row after the stamp writes it on `main`). \
336                         Wrap the code in backticks, or use an absolute URL."
337                    ));
338                } else {
339                    changelog = Some(value.to_string());
340                }
341            }
342            "closes_rule" => {
343                if saw_closes_rule {
344                    errors.push("duplicate frontmatter key `closes_rule`".into());
345                }
346                saw_closes_rule = true;
347                if value.is_empty() {
348                    errors.push(
349                        "closes_rule must not be empty (omit the key entirely if there's \
350                         nothing to cite)"
351                            .into(),
352                    );
353                } else {
354                    for entry in value.split(',') {
355                        let entry = entry.trim();
356                        if is_rule_id(entry) {
357                            closes_rule.push(entry.to_string());
358                        } else {
359                            errors.push(format!(
360                                "closes_rule entry {entry:?} is not a rule id \
361                                 (expected `R<major>.<minor>`, e.g. `R2.3`)"
362                            ));
363                        }
364                    }
365                }
366            }
367            "probes" => {
368                if saw_probes {
369                    errors.push("duplicate frontmatter key `probes`".into());
370                }
371                saw_probes = true;
372                if value.is_empty() {
373                    errors.push(
374                        "probes must not be empty (omit the key entirely if no gated probe \
375                         moves)"
376                            .into(),
377                    );
378                } else {
379                    for entry in value.split(',') {
380                        let entry = entry.trim().trim_matches('`');
381                        if greenfield_status::GATED_PROBES.contains(&entry) {
382                            if !probes.iter().any(|p| p == entry) {
383                                probes.push(entry.to_string());
384                            }
385                        } else {
386                            errors.push(format!(
387                                "probes entry {entry:?} is not a gated greenfield-status probe \
388                                 (one of: {})",
389                                greenfield_status::GATED_PROBES.join(", ")
390                            ));
391                        }
392                    }
393                }
394            }
395            "raises" => {
396                // Repeatable: one line per raised probe, so each reason stays a
397                // single line of Markdown (a comma/semicolon list would collide
398                // with punctuation in the reasons).
399                match parse_raise(value) {
400                    Ok(raise) => {
401                        if raises.iter().any(|r| r.probe == raise.probe) {
402                            errors.push(format!(
403                                "duplicate `raises` entry for probe {:?}",
404                                raise.probe
405                            ));
406                        } else {
407                            raises.push(raise);
408                        }
409                    }
410                    Err(e) => errors.push(e),
411                }
412            }
413            "breaking" => {
414                if saw_breaking {
415                    errors.push("duplicate frontmatter key `breaking`".into());
416                }
417                saw_breaking = true;
418                if value.is_empty() {
419                    errors.push(
420                        "breaking must not be empty (omit the key entirely if nothing breaks)"
421                            .into(),
422                    );
423                } else if looks_like_version_prefix(value) {
424                    errors.push(format!(
425                        "breaking must not start with a version number (the stamp adds it): \
426                         {value:?}"
427                    ));
428                } else if let Some(dest) = relative_markdown_link_in(value) {
429                    errors.push(format!(
430                        "breaking reads as a Markdown link to the relative destination {dest:?} \
431                         — the note is inserted verbatim into the Book's upgrading page, so a \
432                         bare `x[T](y)` in prose becomes a link the docs site's link-checker \
433                         rejects. Wrap the code in backticks, or use an absolute URL."
434                    ));
435                } else {
436                    breaking = Some(value.to_string());
437                }
438            }
439            other => errors.push(format!("unknown frontmatter key {other:?}")),
440        }
441    }
442
443    if !saw_level {
444        errors.push("frontmatter is missing `level`".into());
445    }
446    if !saw_changelog {
447        errors.push("frontmatter is missing `changelog`".into());
448    }
449
450    Some((level, changelog, closes_rule, probes, raises, breaking))
451}
452
453/// Parse one `raises:` value, `<probe> — <reason>` (an em dash; ` - ` is accepted
454/// too). The probe must be a [`greenfield_status::GROWTH_PROBES`] member and the
455/// reason is mandatory. The reason lands verbatim in a Markdown table cell of
456/// `design/greenfield-status-raises.md`, so like `changelog` it must be one line
457/// with no relative link, and it must not contain `|`.
458fn parse_raise(value: &str) -> Result<Raise, String> {
459    let growth = greenfield_status::GROWTH_PROBES.join(", ");
460    // Split at whichever separator comes first, so a dash inside the reason
461    // (`ts_any - a — b`) stays in the reason.
462    let em = value.find(" — ").map(|i| (i, " — ".len()));
463    let hy = value.find(" - ").map(|i| (i, " - ".len()));
464    let sep = match (em, hy) {
465        (Some(a), Some(b)) => Some(if a.0 <= b.0 { a } else { b }),
466        (a, b) => a.or(b),
467    };
468    let (probe, reason) = sep
469        .map(|(i, n)| (value[..i].trim().trim_matches('`'), value[i + n..].trim()))
470        .ok_or_else(|| {
471            format!(
472                "raises must read `<probe> — <reason>` (the reason is mandatory), got {value:?}"
473            )
474        })?;
475    if !greenfield_status::GROWTH_PROBES.contains(&probe) {
476        return Err(format!(
477            "raises entry {probe:?} is not a growth probe (one of: {growth}); only growth \
478             probes can rise, and any other probe needs no raise"
479        ));
480    }
481    if reason.is_empty() {
482        return Err(format!("raises entry for {probe:?} has an empty reason"));
483    }
484    if reason.contains('|') {
485        return Err(format!(
486            "raises reason for {probe:?} contains `|`, which would break the ledger's table row"
487        ));
488    }
489    if let Some(dest) = relative_markdown_link_in(reason) {
490        return Err(format!(
491            "raises reason for {probe:?} reads as a Markdown link to the relative destination \
492             {dest:?} — it is inserted verbatim into `design/greenfield-status-raises.md`. Wrap \
493             the code in backticks, or use an absolute URL."
494        ));
495    }
496    Ok(Raise {
497        probe: probe.to_string(),
498        reason: reason.to_string(),
499    })
500}
501
502/// The growth probes raised by every pending file under `root` — the union of
503/// their `raises` keys. Same reasoning as [`acknowledged_probes`] for why the
504/// pending files present in a tree are the right set.
505pub fn raised_probes(root: &Path) -> std::collections::BTreeSet<String> {
506    validated_pending_in(root)
507        .map(|ps| {
508            ps.into_iter()
509                .flat_map(|(_, p)| p.raises.into_iter().map(|r| r.probe))
510                .collect()
511        })
512        .unwrap_or_default()
513}
514
515/// Like [`raised_probes`], but an invalid pending directory is an error (with
516/// each problem) rather than an empty set, so a caller can say the pending files
517/// are invalid instead of reporting a misleading "unraised" rise.
518pub fn raised_probes_checked(
519    root: &Path,
520) -> Result<std::collections::BTreeSet<String>, Vec<String>> {
521    validated_pending_in(root).map(|ps| {
522        ps.into_iter()
523            .flat_map(|(_, p)| p.raises.into_iter().map(|r| r.probe))
524            .collect()
525    })
526}
527
528/// The gated probes acknowledged by every pending file under `root` — the union
529/// of their `probes` keys. The pending files present in a tree are exactly the
530/// increments not yet stamped (the stamp deletes each one as it rewrites the
531/// table), so on a PR's merge ref this covers both the PR's own acknowledgement
532/// and any just-merged increment whose stamp hasn't landed yet. An unreadable or
533/// invalid pending directory acknowledges nothing; `pending_files` reports why.
534pub fn acknowledged_probes(root: &Path) -> std::collections::BTreeSet<String> {
535    validated_pending_in(root)
536        .map(|ps| ps.into_iter().flat_map(|(_, p)| p.probes).collect())
537        .unwrap_or_default()
538}
539
540/// Is `s` shaped like a greenfield-reference rule id — `R` followed by
541/// `<digits>.<digits>` (e.g. `R2.3`, `R0.1`)? Syntax only; whether the id
542/// actually exists in the reference is [`known_rule_ids`]'s job.
543pub fn is_rule_id(s: &str) -> bool {
544    let Some(rest) = s.strip_prefix('R') else {
545        return false;
546    };
547    let Some((major, minor)) = rest.split_once('.') else {
548        return false;
549    };
550    !major.is_empty()
551        && major.chars().all(|c| c.is_ascii_digit())
552        && !minor.is_empty()
553        && minor.chars().all(|c| c.is_ascii_digit())
554}
555
556/// Every rule id (`R2.3`, …) enumerated in the greenfield reference
557/// (`design/bynk-greenfield-compiler.md`) — the existence check for a pending
558/// file's `closes_rule` entries, separate from [`is_rule_id`]'s pure syntax
559/// check because it needs the repo root. Root-parameterised like
560/// `stamp::next_adr_number`, so a fixture tree can supply its own reference doc.
561///
562/// Rules are written inline as `**R2.3 — <title>.**`; this scans every `**R`
563/// occurrence for the dotted id immediately following, rather than requiring a
564/// line-start anchor — the doc's own precedent (`grep -oE '\*\*R[0-9]+\.[0-9]+
565/// —'`) confirmed this finds exactly the 130 rules the reference claims.
566pub fn known_rule_ids(root: &Path) -> Result<std::collections::HashSet<String>, String> {
567    let path = root.join("design/bynk-greenfield-compiler.md");
568    let text =
569        fs::read_to_string(&path).map_err(|e| format!("cannot read {}: {e}", path.display()))?;
570    let mut ids = std::collections::HashSet::new();
571    let bytes = text.as_bytes();
572    let mut i = 0;
573    while let Some(rel) = text[i..].find("**R") {
574        let start = i + rel + 2; // skip `**`, keep the leading `R`
575        let mut end = start;
576        while end < bytes.len() && (bytes[end].is_ascii_alphanumeric() || bytes[end] == b'.') {
577            end += 1;
578        }
579        let candidate = &text[start..end];
580        if is_rule_id(candidate) {
581            ids.insert(candidate.to_string());
582        }
583        i = end.max(start + 1);
584    }
585    Ok(ids)
586}
587
588/// The PR number a commit `subject` (the first line of its message) names, if
589/// it ends in the `(#NNNN)` GitHub's squash-merge appends to the PR title —
590/// pure and root-independent, so `xtask/src/main.rs`'s `pr_number_from_head`
591/// (the only caller, which runs `git log -1 --format=%s` to get `subject`)
592/// stays a thin wrapper over this, and this half — the part with the
593/// interesting edge cases — is unit-testable without a git tree (#1001,
594/// caught by review as the one piece of new logic with no test coverage).
595///
596/// **Known limitation, stated rather than guarded against:** this matches on
597/// shape alone. Any subject ending `(#NNNN)` is read as the merging PR,
598/// including a hand-written commit that happens to end in an *issue*
599/// reference (`"fix: handle empty spans (#1001)"`, where 1001 names an issue,
600/// not the PR that closes it) — correct on the squash-merge path this exists
601/// for, a silent false positive off it (a hand-run `stamp --apply` on an
602/// unmerged local commit, say). Not guarded against because the fix — only
603/// trust the parse when the run is known to be CI/merge-triggered — would
604/// also suppress the *legitimate* case of manually re-running `stamp --apply`
605/// against an already-merged commit to recover from a failed push (`stamp.yml`
606/// names this as the documented recovery path), which is a worse trade.
607pub fn pr_number_from_subject(subject: &str) -> Option<u32> {
608    let inner = subject.strip_suffix(')')?.rsplit_once("(#")?.1;
609    inner.parse().ok()
610}
611
612/// Parse `## ADR: <slug>` blocks from the body (everything after the closing
613/// frontmatter fence). Zero blocks is valid — an increment may record no
614/// decision. Pushes errors for a non-kebab or duplicate slug, or an empty body.
615fn parse_adrs(content: &str, errors: &mut Vec<String>) -> Vec<Adr> {
616    // Body starts after the second `---` fence.
617    let mut fences = 0;
618    let mut body_lines = Vec::new();
619    for line in content.lines() {
620        if fences < 2 {
621            if line.trim_end() == "---" {
622                fences += 1;
623            }
624            continue;
625        }
626        body_lines.push(line);
627    }
628
629    // A `## ADR:` line inside a ``` code fence is prose (e.g. a pending file
630    // documenting the format inline), not a block header. Mark each line's
631    // header-ness up front, toggling on backtick-fence delimiters, so both the
632    // outer scan and the body-collecting loop below agree on where blocks start.
633    let mut in_fence = false;
634    let is_header: Vec<bool> = body_lines
635        .iter()
636        .map(|line| {
637            if line.trim_start().starts_with("```") {
638                in_fence = !in_fence;
639                false
640            } else {
641                !in_fence && adr_header_slug(line).is_some()
642            }
643        })
644        .collect();
645
646    let mut adrs: Vec<Adr> = Vec::new();
647    let mut i = 0;
648    while i < body_lines.len() {
649        if is_header[i] {
650            let slug = adr_header_slug(body_lines[i])
651                .expect("is_header implies an ADR header")
652                .trim()
653                .to_string();
654            i += 1;
655            let mut block = Vec::new();
656            while i < body_lines.len() && !is_header[i] {
657                block.push(body_lines[i]);
658                i += 1;
659            }
660
661            // The block opens with `title:`/`summary:`/`status:` key lines (any
662            // order, `title` required), then a blank line, then the verbatim
663            // body. Consume leading blanks and known keys; the first other line
664            // starts the body.
665            let mut title = None;
666            let mut summary = None;
667            let mut status = None;
668            let mut body_start = block.len();
669            for (idx, raw) in block.iter().enumerate() {
670                let line = raw.trim();
671                if line.is_empty() && title.is_none() && summary.is_none() && status.is_none() {
672                    continue;
673                }
674                if let Some(v) = line.strip_prefix("title:") {
675                    title = Some(v.trim().to_string());
676                } else if let Some(v) = line.strip_prefix("summary:") {
677                    summary = Some(v.trim().to_string());
678                } else if let Some(v) = line.strip_prefix("status:") {
679                    status = Some(v.trim().to_string());
680                } else {
681                    body_start = idx;
682                    break;
683                }
684            }
685            let body = block[body_start..].join("\n").trim().to_string();
686
687            if !is_kebab(&slug) {
688                errors.push(format!(
689                    "ADR slug {slug:?} is not a kebab-case slug (a-z, 0-9, single hyphens)"
690                ));
691            } else if adrs.iter().any(|a| a.slug == slug) {
692                errors.push(format!("duplicate ADR slug {slug:?}"));
693            }
694            match &title {
695                Some(t) if t.is_empty() => {
696                    errors.push(format!("ADR {slug:?} has an empty `title:`"))
697                }
698                None => errors.push(format!("ADR {slug:?} is missing a `title:` line")),
699                _ => {}
700            }
701            if body.is_empty() {
702                errors.push(format!("ADR {slug:?} has an empty body"));
703            }
704            adrs.push(Adr {
705                slug,
706                title: title.unwrap_or_default(),
707                summary: summary.filter(|s| !s.is_empty()),
708                status: status.filter(|s| !s.is_empty()),
709                body,
710            });
711        } else {
712            i += 1;
713        }
714    }
715    adrs
716}
717
718/// The slug text of a `## ADR: <slug>` header line, if this line is one.
719fn adr_header_slug(line: &str) -> Option<&str> {
720    line.trim().strip_prefix("## ADR:")
721}
722
723/// A kebab-case slug: non-empty, `a-z0-9` and single interior hyphens only.
724fn is_kebab(s: &str) -> bool {
725    !s.is_empty()
726        && !s.starts_with('-')
727        && !s.ends_with('-')
728        && !s.contains("--")
729        && s.chars()
730            .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
731}
732
733/// Whether `value` is wrapped in one matching pair of quotes, `'…'` or `"…"`.
734/// A pending file's `changelog` is Markdown that the stamp copies into the row
735/// verbatim, not a YAML scalar, so such quotes would appear in the changelog
736/// (#3236, #3247 both landed that way).
737fn is_wrapped_in_quotes(value: &str) -> bool {
738    let b = value.as_bytes();
739    b.len() >= 2 && matches!(b[0], b'\'' | b'"') && b[b.len() - 1] == b[0]
740}
741
742/// Whether the changelog's first token reads as a repo version the author has
743/// accidentally prefixed — the stamp prepends the number, so the blurb must not
744/// carry one. Matched to the repo's actual spellings: a `v` prefix (`v0.186`,
745/// the banner form) or three-plus numeric groups (`0.186.0`, the Cargo form).
746/// A bare two-group token like `3.0` is *not* a version here, so a blurb such as
747/// "3.0 rendering pipeline added" is allowed.
748fn looks_like_version_prefix(changelog: &str) -> bool {
749    let raw = changelog.split_whitespace().next().unwrap_or("");
750    let had_v = raw.starts_with('v') || raw.starts_with('V');
751    let groups: Vec<&str> = raw.trim_start_matches(['v', 'V']).split('.').collect();
752    let all_numeric = groups.len() >= 2
753        && groups
754            .iter()
755            .all(|p| !p.is_empty() && p.chars().all(|c| c.is_ascii_digit()));
756    all_numeric && (had_v || groups.len() >= 3)
757}
758
759/// The destination of the first Markdown inline link in `blurb` that resolves
760/// *relatively*, if there is one.
761///
762/// The blurb is inserted verbatim into a table row on the Book's
763/// `reference/releases/unreleased.md`, so `[…](…)` in prose is a real link once it lands —
764/// and an unbackticked generic call like `Events.emit[E](event)` is exactly that
765/// shape, a link to a relative `event`. The docs site's own link-checker
766/// (starlight-links-validator, the `Docs site (astro build)` gate) rejects those,
767/// but it only ever sees the row *after* the stamp writes it on `main`, so that
768/// gate fires post-merge with nothing left to review. This is the pre-merge
769/// stand-in, run against the pending file the PR actually carries.
770///
771/// Deliberate links stay allowed — absolute (`https://…`, the `[#548](…)` issue
772/// citations the corpus is full of), site-root (`/book/…`), and anchors. Code
773/// spans are skipped, which is also the fix the error message asks for: write
774/// ``` `Events.emit[E](event)` ```.
775fn relative_markdown_link_in(blurb: &str) -> Option<String> {
776    let bytes = blurb.as_bytes();
777    let mut i = 0;
778    let mut saw_open_bracket = false;
779    while i < bytes.len() {
780        match bytes[i] {
781            // A backslash escape covers the next byte, whatever it is.
782            b'\\' => i += 1,
783            // Skip a code span: a run of N backticks closes on the next run of
784            // exactly N. An *unmatched* run is literal text in CommonMark and
785            // the rest of the blurb still parses as Markdown, so resume just
786            // after it rather than swallowing the remainder — otherwise a
787            // half-applied fix (`` `Events.emit[E](event) ``, opening backtick
788            // only) would sail through this check and break `main` anyway.
789            b'`' => {
790                let fence = bytes[i..].iter().take_while(|&&b| b == b'`').count();
791                let mut j = i + fence;
792                let mut closed = false;
793                while j < bytes.len() {
794                    if bytes[j] == b'`' {
795                        let run = bytes[j..].iter().take_while(|&&b| b == b'`').count();
796                        j += run;
797                        if run == fence {
798                            closed = true;
799                            break;
800                        }
801                    } else {
802                        j += 1;
803                    }
804                }
805                i = if closed { j } else { i + fence };
806                continue;
807            }
808            b'[' => saw_open_bracket = true,
809            // `](` is only a link if some `[` opened it.
810            b']' if saw_open_bracket && bytes.get(i + 1) == Some(&b'(') => {
811                saw_open_bracket = false;
812                let start = i + 2;
813                let Some(len) = bytes[start..].iter().position(|&b| b == b')') else {
814                    break;
815                };
816                if let Some(dest) = link_destination(&blurb[start..start + len])
817                    && !is_absolute_link_destination(dest)
818                {
819                    return Some(dest.to_string());
820                }
821                i = start + len;
822            }
823            b']' => saw_open_bracket = false,
824            _ => {}
825        }
826        i += 1;
827    }
828    None
829}
830
831/// The destination inside a `](…)` link tail, or `None` when the tail is not one.
832///
833/// CommonMark accepts `(dest)` and `(dest "title")` (also `'…'` and `(…)` titles),
834/// and a bare destination may not contain spaces unless it is `<…>`-wrapped. So a
835/// multi-parameter generic call in prose — `map[K, V](key, value)` — is genuinely
836/// not a link, and reporting one would assert something the site's own checker
837/// would never do. Backticking it is still the house convention; this check just
838/// does not claim it is a broken link.
839fn link_destination(tail: &str) -> Option<&str> {
840    let tail = tail.trim();
841    if let Some(rest) = tail.strip_prefix('<') {
842        return rest.split_once('>').map(|(dest, _)| dest);
843    }
844    let (dest, rest) = match tail.split_once(char::is_whitespace) {
845        Some((dest, rest)) => (dest, rest.trim_start()),
846        None => (tail, ""),
847    };
848    // Whatever follows the destination has to be a title, or this is just prose.
849    if rest.is_empty() || rest.starts_with(['"', '\'', '(']) {
850        Some(dest)
851    } else {
852        None
853    }
854}
855
856/// Whether a Markdown link destination resolves without depending on the page it
857/// is written on — the only kind a changelog blurb may carry.
858///
859/// Note this is about *shape*, not existence: the site's link-checker also
860/// resolves site-root paths and anchors, which nothing here can do without the
861/// built site. A hand-written `/book/typo/` still passes this and fails the docs
862/// build. `design/pending/README.md` says so rather than implying a guarantee.
863fn is_absolute_link_destination(dest: &str) -> bool {
864    dest.starts_with("https://")
865        || dest.starts_with("http://")
866        || dest.starts_with("mailto:")
867        || dest.starts_with('/')
868        || dest.starts_with('#')
869}
870
871#[cfg(test)]
872mod tests {
873    use super::*;
874
875    fn ok(name: &str, content: &str) -> Pending {
876        validate(name, content).unwrap_or_else(|e| panic!("expected valid, got {e:?}"))
877    }
878    fn err(name: &str, content: &str) -> Vec<String> {
879        validate(name, content).expect_err("expected invalid")
880    }
881
882    #[test]
883    fn minimal_no_adr_is_valid() {
884        let p = ok(
885            "add-a-thing.md",
886            "---\nlevel: minor\nchangelog: Add a thing to the language\n---\n",
887        );
888        assert_eq!(p.level, Level::Minor);
889        assert_eq!(p.changelog, "Add a thing to the language");
890        assert!(p.adrs.is_empty());
891    }
892
893    #[test]
894    fn patch_level_is_valid() {
895        assert_eq!(
896            ok(
897                "fix-a-thing.md",
898                "---\nlevel: patch\nchangelog: Fix a non-language thing\n---\n"
899            )
900            .level,
901            Level::Patch
902        );
903    }
904
905    #[test]
906    fn one_adr_parses_slug_title_and_body() {
907        let p = ok(
908            "unit-tier.md",
909            "---\nlevel: minor\nchangelog: Drive a handler at the unit tier\n---\n\n## ADR: unit-tier-service-address\ntitle: A case addresses a handler by surface\n\n**Decision.** A case addresses by surface.\n",
910        );
911        assert_eq!(p.adrs.len(), 1);
912        let adr = &p.adrs[0];
913        assert_eq!(adr.slug, "unit-tier-service-address");
914        assert_eq!(adr.title, "A case addresses a handler by surface");
915        // summary/status default to title/"Accepted" when absent.
916        assert_eq!(adr.summary(), adr.title);
917        assert_eq!(adr.status(), "Accepted");
918        assert!(adr.body.contains("addresses by surface"));
919        assert!(!adr.body.contains("title:"), "the title line is not body");
920    }
921
922    #[test]
923    fn adr_summary_and_status_are_parsed() {
924        let p = ok(
925            "x.md",
926            "---\nlevel: minor\nchangelog: x\n---\n\n## ADR: a-slug\ntitle: The title\nsummary: The one-line index distillation\nstatus: Proposed\n\nBody.\n",
927        );
928        let adr = &p.adrs[0];
929        assert_eq!(adr.summary(), "The one-line index distillation");
930        assert_eq!(adr.status(), "Proposed");
931    }
932
933    #[test]
934    fn adr_missing_title_rejected() {
935        assert!(
936            err(
937                "x.md",
938                "---\nlevel: minor\nchangelog: x\n---\n\n## ADR: a-slug\n\nBody with no title line.\n"
939            )
940            .iter()
941            .any(|e| e.contains("missing a `title:`"))
942        );
943    }
944
945    #[test]
946    fn two_adrs_parse() {
947        let p = ok(
948            "two.md",
949            "---\nlevel: minor\nchangelog: Two decisions\n---\n\n## ADR: first-one\ntitle: First\n\nBody one.\n\n## ADR: second-one\ntitle: Second\n\nBody two.\n",
950        );
951        assert_eq!(p.adrs.len(), 2);
952        assert_eq!(p.adrs[0].slug, "first-one");
953        assert_eq!(p.adrs[1].slug, "second-one");
954    }
955
956    #[test]
957    fn bad_level_rejected() {
958        assert!(
959            err("x.md", "---\nlevel: major\nchangelog: x\n---\n")
960                .iter()
961                .any(|e| e.contains("level must be"))
962        );
963    }
964
965    #[test]
966    fn missing_level_rejected() {
967        assert!(
968            err("x.md", "---\nchangelog: x\n---\n")
969                .iter()
970                .any(|e| e.contains("missing `level`"))
971        );
972    }
973
974    #[test]
975    fn missing_changelog_rejected() {
976        assert!(
977            err("x.md", "---\nlevel: minor\n---\n")
978                .iter()
979                .any(|e| e.contains("missing `changelog`"))
980        );
981    }
982
983    #[test]
984    fn empty_changelog_rejected() {
985        assert!(
986            err("x.md", "---\nlevel: minor\nchangelog:   \n---\n")
987                .iter()
988                .any(|e| e.contains("changelog"))
989        );
990    }
991
992    #[test]
993    fn version_prefixed_changelog_rejected() {
994        for cl in ["v0.186 Add a thing", "0.186.0 Add a thing"] {
995            let content = format!("---\nlevel: minor\nchangelog: {cl}\n---\n");
996            assert!(
997                err("x.md", &content)
998                    .iter()
999                    .any(|e| e.contains("version number")),
1000                "expected rejection for {cl:?}"
1001            );
1002        }
1003    }
1004
1005    #[test]
1006    fn plain_changelog_with_a_dot_is_allowed() {
1007        // A blurb ending in a version-like word must not false-positive; only the
1008        // *first* token is checked.
1009        ok(
1010            "x.md",
1011            "---\nlevel: minor\nchangelog: Support semver ranges like 1.2.3\n---\n",
1012        );
1013    }
1014
1015    #[test]
1016    fn bare_two_group_leading_number_is_allowed() {
1017        // `3.0` is not a repo version (no `v`, only two groups) — a blurb may
1018        // legitimately open with it.
1019        ok(
1020            "x.md",
1021            "---\nlevel: minor\nchangelog: 3.0 rendering pipeline added\n---\n",
1022        );
1023    }
1024
1025    #[test]
1026    fn accidental_relative_markdown_link_in_changelog_rejected() {
1027        // The real regression (v0.249.1): an unbackticked generic call in prose
1028        // parses as `[E](event)`, a link to a relative `event`, and failed the
1029        // docs site's link-checker on `main` — post-merge, after the stamp had
1030        // already written the row.
1031        let content = "---\nlevel: patch\nchangelog: Read Callee to detect an \
1032                       Events.emit[E](event) call\n---\n";
1033        assert!(
1034            err("x.md", content)
1035                .iter()
1036                .any(|e| e.contains("relative destination \"event\"")),
1037            "expected rejection, got {:?}",
1038            err("x.md", content)
1039        );
1040    }
1041
1042    #[test]
1043    fn a_changelog_wrapped_in_quotes_is_rejected() {
1044        // The stamp copies the value verbatim, so the quotes would land in the
1045        // changelog row (#3236, #3247).
1046        for value in ["'Add a thing'", "\"Add a thing\""] {
1047            let content = format!("---\nlevel: patch\nchangelog: {value}\n---\n");
1048            assert!(
1049                err("x.md", &content)
1050                    .iter()
1051                    .any(|e| e.contains("wrapped in quotes")),
1052                "expected rejection of {value}, got {:?}",
1053                err("x.md", &content)
1054            );
1055        }
1056        // A quote that does not wrap the whole value is prose, not a wrapper.
1057        for value in [
1058            "Add a 'thing'",
1059            "'Add' a thing",
1060            "Add a thing's tail",
1061            "\"Add\" and 'a thing'",
1062        ] {
1063            let content = format!("---\nlevel: patch\nchangelog: {value}\n---\n");
1064            assert_eq!(ok("x.md", &content).changelog, value, "{value}");
1065        }
1066    }
1067
1068    #[test]
1069    fn backticked_generic_call_in_changelog_is_allowed() {
1070        // The documented fix, and the corpus's own convention for code in prose.
1071        ok(
1072            "x.md",
1073            "---\nlevel: patch\nchangelog: Detect an `Events.emit[E](event)` call\n---\n",
1074        );
1075    }
1076
1077    #[test]
1078    fn absolute_links_in_changelog_are_allowed() {
1079        // Issue citations are the single most common blurb decoration; site-root
1080        // links and anchors resolve independently of the page too.
1081        for cl in [
1082            "Close [#548](https://github.com/accuser/bynk/issues/548)",
1083            "See [the roadmap](/project/versioning-and-roadmap/)",
1084            "See [below](#notes)",
1085        ] {
1086            let content = format!("---\nlevel: minor\nchangelog: {cl}\n---\n");
1087            ok("x.md", &content);
1088        }
1089    }
1090
1091    #[test]
1092    fn bracket_without_a_link_in_changelog_is_allowed() {
1093        // `]` with no `(` after it, and `(` with no `[` before it, are ordinary
1094        // punctuation — neither forms a link.
1095        ok(
1096            "x.md",
1097            "---\nlevel: minor\nchangelog: Widen ts_any [see the probe] (P7.0) for writes\n---\n",
1098        );
1099    }
1100
1101    #[test]
1102    fn a_half_backticked_changelog_is_still_rejected() {
1103        // The likeliest mistake after reading the error message: the author adds
1104        // the opening backtick and forgets the closing one. CommonMark treats the
1105        // unmatched run as literal text and still links `[E](event)` (confirmed
1106        // against the site's own parser), so the guard must not stop scanning.
1107        let content = "---\nlevel: patch\nchangelog: Detect an `Events.emit[E](event) call\n---\n";
1108        assert!(
1109            err("x.md", content)
1110                .iter()
1111                .any(|e| e.contains("relative destination \"event\"")),
1112            "expected rejection, got {:?}",
1113            err("x.md", content)
1114        );
1115    }
1116
1117    #[test]
1118    fn a_stray_backtick_does_not_blind_the_rest_of_the_blurb() {
1119        // Same failure mode from an unrelated typo earlier in the sentence.
1120        let content = "---\nlevel: patch\nchangelog: A stray `Callee typo, then \
1121                       Events.emit[E](event) later\n---\n";
1122        assert!(
1123            err("x.md", content)
1124                .iter()
1125                .any(|e| e.contains("relative destination \"event\"")),
1126            "expected rejection, got {:?}",
1127            err("x.md", content)
1128        );
1129    }
1130
1131    #[test]
1132    fn a_multi_parameter_generic_call_is_not_reported_as_a_link() {
1133        // `(key, value)` holds a space, so CommonMark does not link it — claiming
1134        // otherwise would assert a failure the site checker would never produce.
1135        ok(
1136            "x.md",
1137            "---\nlevel: minor\nchangelog: Lift a fn map[K, V](key, value) call\n---\n",
1138        );
1139    }
1140
1141    #[test]
1142    fn a_titled_link_is_still_read_as_a_link() {
1143        // `(dest "title")` is a real link, so the destination is still checked
1144        // even though a space follows it.
1145        let content = "---\nlevel: minor\nchangelog: See [it](there \"a title\")\n---\n";
1146        assert!(
1147            err("x.md", content)
1148                .iter()
1149                .any(|e| e.contains("relative destination \"there\"")),
1150            "expected rejection, got {:?}",
1151            err("x.md", content)
1152        );
1153    }
1154
1155    #[test]
1156    fn duplicate_frontmatter_key_rejected() {
1157        assert!(
1158            err(
1159                "x.md",
1160                "---\nlevel: minor\nlevel: patch\nchangelog: x\n---\n"
1161            )
1162            .iter()
1163            .any(|e| e.contains("duplicate frontmatter key `level`"))
1164        );
1165    }
1166
1167    #[test]
1168    fn adr_header_inside_a_code_fence_is_not_a_block() {
1169        // A pending file documenting the format inline must not have its fenced
1170        // `## ADR:` example split off into a spurious block.
1171        let p = ok(
1172            "x.md",
1173            "---\nlevel: minor\nchangelog: Document the format\n---\n\n\
1174             Example:\n\n```markdown\n## ADR: not-a-real-block\nfenced prose\n```\n\n\
1175             ## ADR: the-real-one\ntitle: The real one\n\nReal body.\n",
1176        );
1177        assert_eq!(p.adrs.len(), 1);
1178        assert_eq!(p.adrs[0].slug, "the-real-one");
1179    }
1180
1181    #[test]
1182    fn no_frontmatter_rejected() {
1183        assert!(
1184            err("x.md", "just some text\n")
1185                .iter()
1186                .any(|e| e.contains("open with a `---`"))
1187        );
1188    }
1189
1190    #[test]
1191    fn unclosed_frontmatter_rejected() {
1192        assert!(
1193            err("x.md", "---\nlevel: minor\nchangelog: x\n")
1194                .iter()
1195                .any(|e| e.contains("not closed"))
1196        );
1197    }
1198
1199    #[test]
1200    fn unknown_key_rejected() {
1201        assert!(
1202            err("x.md", "---\nlevel: minor\nchangelog: x\nversion: 9\n---\n")
1203                .iter()
1204                .any(|e| e.contains("unknown frontmatter key"))
1205        );
1206    }
1207
1208    // --- breaking -------------------------------------------------------------
1209
1210    #[test]
1211    fn breaking_is_optional_and_defaults_absent() {
1212        // Backward-compatible: every pending file written before the key existed.
1213        assert_eq!(
1214            ok("x.md", "---\nlevel: patch\nchangelog: x\n---\n").breaking,
1215            None
1216        );
1217    }
1218
1219    #[test]
1220    fn breaking_parses_a_one_line_note() {
1221        let p = ok(
1222            "x.md",
1223            "---\nlevel: minor\nchangelog: x\nbreaking: `old` is now `new`; `bynk check --fix` rewrites it\n---\n",
1224        );
1225        assert_eq!(
1226            p.breaking.as_deref(),
1227            Some("`old` is now `new`; `bynk check --fix` rewrites it")
1228        );
1229    }
1230
1231    #[test]
1232    fn breaking_rejects_empty_duplicate_versioned_and_relative_link_notes() {
1233        let e = err("x.md", "---\nlevel: patch\nchangelog: x\nbreaking:\n---\n");
1234        assert!(
1235            e.iter().any(|m| m.contains("breaking must not be empty")),
1236            "{e:?}"
1237        );
1238        let e = err(
1239            "x.md",
1240            "---\nlevel: patch\nchangelog: x\nbreaking: a\nbreaking: b\n---\n",
1241        );
1242        assert!(
1243            e.iter()
1244                .any(|m| m.contains("duplicate frontmatter key `breaking`")),
1245            "{e:?}"
1246        );
1247        let e = err(
1248            "x.md",
1249            "---\nlevel: patch\nchangelog: x\nbreaking: v0.9.0 removes it\n---\n",
1250        );
1251        assert!(
1252            e.iter()
1253                .any(|m| m.contains("must not start with a version")),
1254            "{e:?}"
1255        );
1256        let e = err(
1257            "x.md",
1258            "---\nlevel: patch\nchangelog: x\nbreaking: use Events.emit[E](event)\n---\n",
1259        );
1260        assert!(
1261            e.iter().any(|m| m.contains("relative destination")),
1262            "{e:?}"
1263        );
1264    }
1265
1266    // --- probes --------------------------------------------------------------
1267
1268    #[test]
1269    fn probes_is_optional_and_defaults_empty() {
1270        let p = ok("x.md", "---\nlevel: patch\nchangelog: x\n---\n");
1271        assert!(p.probes.is_empty());
1272    }
1273
1274    #[test]
1275    fn probes_parses_a_list_trims_backticks_and_dedupes() {
1276        let p = ok(
1277            "x.md",
1278            "---\nlevel: patch\nchangelog: x\nprobes: `ts_writes`, diagnostic_coverage ,ts_writes\n---\n",
1279        );
1280        assert_eq!(
1281            p.probes,
1282            vec!["ts_writes".to_string(), "diagnostic_coverage".to_string()]
1283        );
1284    }
1285
1286    #[test]
1287    fn probes_rejects_a_trend_or_unknown_probe() {
1288        let errs = err(
1289            "x.md",
1290            "---\nlevel: patch\nchangelog: x\nprobes: wildcard_arms, nope\n---\n",
1291        );
1292        assert_eq!(
1293            errs.iter()
1294                .filter(|e| e.contains("is not a gated greenfield-status probe"))
1295                .count(),
1296            2
1297        );
1298    }
1299
1300    #[test]
1301    fn probes_rejects_empty_and_duplicate_keys() {
1302        assert!(
1303            err("x.md", "---\nlevel: patch\nchangelog: x\nprobes:\n---\n")
1304                .iter()
1305                .any(|e| e.contains("probes must not be empty"))
1306        );
1307        assert!(
1308            err(
1309                "x.md",
1310                "---\nlevel: patch\nchangelog: x\nprobes: ts_any\nprobes: ts_any\n---\n"
1311            )
1312            .iter()
1313            .any(|e| e.contains("duplicate frontmatter key `probes`"))
1314        );
1315    }
1316
1317    // --- raises (#3679) ------------------------------------------------------
1318
1319    #[test]
1320    fn raises_is_optional_and_defaults_empty() {
1321        assert!(
1322            ok("x.md", "---\nlevel: patch\nchangelog: x\n---\n")
1323                .raises
1324                .is_empty()
1325        );
1326    }
1327
1328    #[test]
1329    fn raises_parses_one_line_per_probe_with_a_reason() {
1330        let p = ok(
1331            "x.md",
1332            "---\nlevel: patch\nchangelog: x\nraises: `ts_writes` — no typed node for Y yet (#1)\nraises: ts_any - a bare `any` (#2): kept\n---\n",
1333        );
1334        assert_eq!(
1335            p.raises,
1336            vec![
1337                Raise {
1338                    probe: "ts_writes".into(),
1339                    reason: "no typed node for Y yet (#1)".into()
1340                },
1341                Raise {
1342                    probe: "ts_any".into(),
1343                    reason: "a bare `any` (#2): kept".into()
1344                },
1345            ]
1346        );
1347    }
1348
1349    #[test]
1350    fn raises_splits_at_the_first_separator() {
1351        let p = ok(
1352            "x.md",
1353            "---\nlevel: patch\nchangelog: x\nraises: ts_any - reason — more detail\nraises: ts_writes — a - b\n---\n",
1354        );
1355        assert_eq!(p.raises[0].probe, "ts_any");
1356        assert_eq!(p.raises[0].reason, "reason — more detail");
1357        assert_eq!(p.raises[1].probe, "ts_writes");
1358        assert_eq!(p.raises[1].reason, "a - b");
1359    }
1360
1361    #[test]
1362    fn raises_rejects_a_non_growth_probe() {
1363        let errs = err(
1364            "x.md",
1365            "---\nlevel: patch\nchangelog: x\nraises: hoist_sinks — because\n---\n",
1366        );
1367        assert!(errs.iter().any(|e| e.contains("not a growth probe")));
1368    }
1369
1370    #[test]
1371    fn raises_rejects_a_missing_or_empty_reason() {
1372        for bad in ["ts_writes", "ts_writes —"] {
1373            let errs = err(
1374                "x.md",
1375                &format!("---\nlevel: patch\nchangelog: x\nraises: {bad}\n---\n"),
1376            );
1377            assert!(
1378                errs.iter().any(|e| e.contains("raises")),
1379                "{bad:?} should be rejected: {errs:?}"
1380            );
1381        }
1382    }
1383
1384    #[test]
1385    fn raises_rejects_a_duplicate_probe_a_pipe_and_a_relative_link() {
1386        let dup = err(
1387            "x.md",
1388            "---\nlevel: patch\nchangelog: x\nraises: ts_any — a\nraises: ts_any — b\n---\n",
1389        );
1390        assert!(dup.iter().any(|e| e.contains("duplicate `raises`")));
1391        let pipe = err(
1392            "x.md",
1393            "---\nlevel: patch\nchangelog: x\nraises: ts_any — a | b\n---\n",
1394        );
1395        assert!(pipe.iter().any(|e| e.contains("`|`")));
1396        let link = err(
1397            "x.md",
1398            "---\nlevel: patch\nchangelog: x\nraises: ts_any — see [y](z)\n---\n",
1399        );
1400        assert!(link.iter().any(|e| e.contains("relative destination")));
1401    }
1402
1403    // --- closes_rule (#1001) --------------------------------------------------
1404
1405    #[test]
1406    fn closes_rule_is_optional_and_defaults_empty() {
1407        let p = ok("x.md", "---\nlevel: patch\nchangelog: x\n---\n");
1408        assert!(p.closes_rule.is_empty());
1409    }
1410
1411    #[test]
1412    fn closes_rule_parses_a_single_id() {
1413        let p = ok(
1414            "x.md",
1415            "---\nlevel: patch\nchangelog: x\ncloses_rule: R2.3\n---\n",
1416        );
1417        assert_eq!(p.closes_rule, vec!["R2.3".to_string()]);
1418    }
1419
1420    #[test]
1421    fn closes_rule_parses_a_comma_separated_list_and_trims_whitespace() {
1422        let p = ok(
1423            "x.md",
1424            "---\nlevel: patch\nchangelog: x\ncloses_rule: R2.3,  R2.12 ,R0.1\n---\n",
1425        );
1426        assert_eq!(
1427            p.closes_rule,
1428            vec!["R2.3".to_string(), "R2.12".to_string(), "R0.1".to_string()]
1429        );
1430    }
1431
1432    #[test]
1433    fn closes_rule_rejects_a_malformed_entry() {
1434        assert!(
1435            err(
1436                "x.md",
1437                "---\nlevel: patch\nchangelog: x\ncloses_rule: not-a-rule\n---\n"
1438            )
1439            .iter()
1440            .any(|e| e.contains("closes_rule entry") && e.contains("not a rule id"))
1441        );
1442    }
1443
1444    #[test]
1445    fn closes_rule_rejects_empty_value() {
1446        assert!(
1447            err(
1448                "x.md",
1449                "---\nlevel: patch\nchangelog: x\ncloses_rule: \n---\n"
1450            )
1451            .iter()
1452            .any(|e| e.contains("closes_rule must not be empty"))
1453        );
1454    }
1455
1456    #[test]
1457    fn closes_rule_rejects_duplicate_key() {
1458        assert!(
1459            err(
1460                "x.md",
1461                "---\nlevel: patch\nchangelog: x\ncloses_rule: R2.3\ncloses_rule: R2.4\n---\n"
1462            )
1463            .iter()
1464            .any(|e| e.contains("duplicate frontmatter key `closes_rule`"))
1465        );
1466    }
1467
1468    #[test]
1469    fn is_rule_id_accepts_and_rejects() {
1470        assert!(is_rule_id("R2.3"));
1471        assert!(is_rule_id("R0.1"));
1472        assert!(is_rule_id("R12.34"));
1473        assert!(!is_rule_id("2.3"));
1474        assert!(!is_rule_id("R2"));
1475        assert!(!is_rule_id("R2.3.4"));
1476        assert!(!is_rule_id("R.3"));
1477        assert!(!is_rule_id("R2."));
1478        assert!(!is_rule_id("Rx.y"));
1479    }
1480
1481    // --- pr_number_from_subject (#1001) --------------------------------------
1482
1483    #[test]
1484    fn pr_number_from_subject_finds_a_trailing_squash_merge_suffix() {
1485        assert_eq!(
1486            pr_number_from_subject("feat(xtask): thing (#1234)"),
1487            Some(1234)
1488        );
1489    }
1490
1491    #[test]
1492    fn pr_number_from_subject_requires_the_suffix_at_the_very_end() {
1493        // Trailing prose after the `)` means this isn't a squash-merge title.
1494        assert_eq!(pr_number_from_subject("feat: thing (#12) then more"), None);
1495    }
1496
1497    #[test]
1498    fn pr_number_from_subject_is_not_confused_by_earlier_nested_parens() {
1499        assert_eq!(pr_number_from_subject("chore: bump (deps) (#12)"), Some(12));
1500    }
1501
1502    #[test]
1503    fn pr_number_from_subject_rejects_a_non_numeric_hash() {
1504        assert_eq!(pr_number_from_subject("feat: thing (#abc)"), None);
1505    }
1506
1507    #[test]
1508    fn pr_number_from_subject_rejects_a_number_too_large_for_u32() {
1509        assert_eq!(pr_number_from_subject("(#99999999999999)"), None);
1510    }
1511
1512    #[test]
1513    fn pr_number_from_subject_none_without_any_suffix() {
1514        assert_eq!(pr_number_from_subject("Merge branch 'x'"), None);
1515    }
1516
1517    /// The documented limitation, pinned so it can't silently change meaning:
1518    /// a hand-written commit ending in an *issue* reference is indistinguishable
1519    /// from a squash-merge PR title by shape alone.
1520    #[test]
1521    fn pr_number_from_subject_cannot_distinguish_an_issue_reference() {
1522        assert_eq!(
1523            pr_number_from_subject("fix: handle empty spans (#1001)"),
1524            Some(1001)
1525        );
1526    }
1527
1528    /// A throwaway fixture tree, named per calling test so parallel runs don't
1529    /// collide — the same convention `xtask/tests/stamp_apply.rs`'s `fixture`
1530    /// uses. Removed and recreated on construction, not cleaned up after (the OS
1531    /// temp dir is not this test's to manage beyond that).
1532    fn rule_fixture(tag: &str, reference_body: &str) -> PathBuf {
1533        let root = std::env::temp_dir().join(format!("xtask-closes-rule-{tag}"));
1534        let _ = fs::remove_dir_all(&root);
1535        fs::create_dir_all(root.join("design/pending")).unwrap();
1536        fs::write(
1537            root.join("design/bynk-greenfield-compiler.md"),
1538            reference_body,
1539        )
1540        .unwrap();
1541        root
1542    }
1543
1544    #[test]
1545    fn acknowledged_probes_is_the_union_across_pending_files() {
1546        let dir = rule_fixture("ack-union", "");
1547        let pending = dir.join("design/pending");
1548        fs::write(
1549            pending.join("a.md"),
1550            "---\nlevel: patch\nchangelog: a\nprobes: ts_writes, ts_any\n---\n",
1551        )
1552        .unwrap();
1553        fs::write(
1554            pending.join("b.md"),
1555            "---\nlevel: patch\nchangelog: b\nprobes: ts_any, diagnostic_coverage\n---\n",
1556        )
1557        .unwrap();
1558        fs::write(
1559            pending.join("c.md"),
1560            "---\nlevel: patch\nchangelog: c\n---\n",
1561        )
1562        .unwrap();
1563        fs::write(pending.join("README.md"), "not a pending file").unwrap();
1564        let ack: Vec<String> = acknowledged_probes(&dir).into_iter().collect();
1565        assert_eq!(ack, ["diagnostic_coverage", "ts_any", "ts_writes"]);
1566    }
1567
1568    #[test]
1569    fn acknowledged_probes_is_empty_when_any_pending_file_is_invalid() {
1570        let dir = rule_fixture("ack-invalid", "");
1571        let pending = dir.join("design/pending");
1572        fs::write(
1573            pending.join("a.md"),
1574            "---\nlevel: patch\nchangelog: a\nprobes: ts_writes\n---\n",
1575        )
1576        .unwrap();
1577        fs::write(
1578            pending.join("b.md"),
1579            "---\nlevel: nope\nchangelog: b\n---\n",
1580        )
1581        .unwrap();
1582        assert!(acknowledged_probes(&dir).is_empty());
1583    }
1584
1585    #[test]
1586    fn acknowledged_probes_is_empty_without_a_pending_dir() {
1587        let dir = std::env::temp_dir().join("xtask-ack-no-pending-dir");
1588        let _ = fs::remove_dir_all(&dir);
1589        fs::create_dir_all(&dir).unwrap();
1590        assert!(acknowledged_probes(&dir).is_empty());
1591    }
1592
1593    #[test]
1594    fn known_rule_ids_finds_bold_rule_headers() {
1595        let dir = rule_fixture(
1596            "finds-bold-headers",
1597            "Some prose.\n\n**R2.3 — A rule about spans.**\n\nMore prose citing **R2.3** again \
1598             in passing, and introducing **R10.11 — a second rule.**\n",
1599        );
1600        let ids = known_rule_ids(&dir).unwrap();
1601        assert_eq!(ids.len(), 2, "expected exactly 2 distinct ids: {ids:?}");
1602        assert!(ids.contains("R2.3"));
1603        assert!(ids.contains("R10.11"));
1604    }
1605
1606    #[test]
1607    fn validated_pending_in_rejects_a_closes_rule_citing_an_unknown_id() {
1608        let dir = rule_fixture("rejects-unknown", "**R2.3 — real.**\n");
1609        fs::write(
1610            dir.join("design/pending/x.md"),
1611            "---\nlevel: patch\nchangelog: x\ncloses_rule: R99.99\n---\n",
1612        )
1613        .unwrap();
1614        let errors = validated_pending_in(&dir).expect_err("R99.99 does not exist");
1615        assert!(
1616            errors
1617                .iter()
1618                .any(|e| e.contains("R99.99") && e.contains("not a rule id in")),
1619            "{errors:?}"
1620        );
1621    }
1622
1623    #[test]
1624    fn validated_pending_in_accepts_a_closes_rule_citing_a_known_id() {
1625        let dir = rule_fixture("accepts-known", "**R2.3 — real.**\n");
1626        fs::write(
1627            dir.join("design/pending/x.md"),
1628            "---\nlevel: patch\nchangelog: x\ncloses_rule: R2.3\n---\n",
1629        )
1630        .unwrap();
1631        let parsed = validated_pending_in(&dir).unwrap();
1632        assert_eq!(parsed.len(), 1);
1633        assert_eq!(parsed[0].1.closes_rule, vec!["R2.3".to_string()]);
1634    }
1635
1636    #[test]
1637    fn non_kebab_adr_slug_rejected() {
1638        assert!(
1639            err(
1640                "x.md",
1641                "---\nlevel: minor\nchangelog: x\n---\n\n## ADR: Not_Kebab\ntitle: T\n\nBody.\n"
1642            )
1643            .iter()
1644            .any(|e| e.contains("not a kebab-case slug"))
1645        );
1646    }
1647
1648    #[test]
1649    fn duplicate_adr_slug_rejected() {
1650        assert!(err(
1651            "x.md",
1652            "---\nlevel: minor\nchangelog: x\n---\n\n## ADR: dup\ntitle: A\n\nBody a.\n\n## ADR: dup\ntitle: B\n\nBody b.\n"
1653        )
1654        .iter()
1655        .any(|e| e.contains("duplicate ADR slug")));
1656    }
1657
1658    #[test]
1659    fn empty_adr_body_rejected() {
1660        assert!(
1661            err(
1662                "x.md",
1663                "---\nlevel: minor\nchangelog: x\n---\n\n## ADR: empty\ntitle: T\n\n## ADR: next\ntitle: N\n\nBody.\n"
1664            )
1665            .iter()
1666            .any(|e| e.contains("empty body"))
1667        );
1668    }
1669
1670    #[test]
1671    fn non_kebab_filename_rejected() {
1672        assert!(
1673            err("Not_A_Slug.md", "---\nlevel: minor\nchangelog: x\n---\n")
1674                .iter()
1675                .any(|e| e.contains("filename stem"))
1676        );
1677    }
1678}