1use 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#[derive(Debug, PartialEq, Eq)]
37pub enum Level {
38 Minor,
39 Patch,
40}
41
42#[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 pub fn summary(&self) -> &str {
60 self.summary.as_deref().unwrap_or(&self.title)
61 }
62
63 pub fn status(&self) -> &str {
65 self.status.as_deref().unwrap_or("Accepted")
66 }
67}
68
69#[derive(Debug, Clone, PartialEq, Eq)]
71pub struct Raise {
72 pub probe: String,
73 pub reason: String,
74}
75
76#[derive(Debug, PartialEq, Eq)]
78pub struct Pending {
79 pub level: Level,
80 pub changelog: String,
81 pub adrs: Vec<Adr>,
82 pub closes_rule: Vec<String>,
89 pub probes: Vec<String>,
97 pub raises: Vec<Raise>,
103 pub breaking: Option<String>,
109}
110
111pub fn repo_root() -> PathBuf {
114 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("..")
115}
116
117pub fn pending_dir() -> PathBuf {
119 repo_root().join("design/pending")
120}
121
122pub fn check_all() -> Result<usize, Vec<String>> {
127 validated_pending_in(&repo_root()).map(|ps| ps.len())
128}
129
130pub 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 } 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
199pub 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
237type Frontmatter = (
240 Option<Level>,
241 Option<String>,
242 Vec<String>,
243 Vec<String>,
244 Vec<Raise>,
245 Option<String>,
246);
247
248fn 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 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 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
453fn parse_raise(value: &str) -> Result<Raise, String> {
459 let growth = greenfield_status::GROWTH_PROBES.join(", ");
460 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
502pub 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
515pub 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
528pub 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
540pub 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
556pub 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; 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
588pub fn pr_number_from_subject(subject: &str) -> Option<u32> {
608 let inner = subject.strip_suffix(')')?.rsplit_once("(#")?.1;
609 inner.parse().ok()
610}
611
612fn parse_adrs(content: &str, errors: &mut Vec<String>) -> Vec<Adr> {
616 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 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 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
718fn adr_header_slug(line: &str) -> Option<&str> {
720 line.trim().strip_prefix("## ADR:")
721}
722
723fn 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
733fn 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
742fn 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
759fn 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 b'\\' => i += 1,
783 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 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
831fn 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 if rest.is_empty() || rest.starts_with(['"', '\'', '(']) {
850 Some(dest)
851 } else {
852 None
853 }
854}
855
856fn 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 #[test]
1211 fn breaking_is_optional_and_defaults_absent() {
1212 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 #[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 #[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 #[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 #[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 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 #[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 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}