1use std::io::Read as _;
34use std::io::Write as _;
35
36use camino::Utf8Path;
37use serde::Serialize;
38
39use crate::cli::message::{MessageArgs, MessageKind};
40use crate::diagnostic::{Diagnostic, Reason};
41use crate::error::RkError;
42use crate::landing;
43use crate::output::Output;
44
45static GUARDS: &str = include_str!("../../blocks/message-guards");
47
48#[derive(Debug, Serialize)]
50pub(crate) struct Finding {
51 pub(crate) class: &'static str,
54 pub(crate) line: usize,
56 pub(crate) detail: String,
58}
59
60#[derive(Debug, Serialize)]
62struct Report {
63 schema: &'static str,
65 kind: &'static str,
67 exempt: bool,
69 findings: Vec<Finding>,
71}
72
73pub fn run(args: &MessageArgs) -> Result<(), RkError> {
81 crate::requirements::require("rk message", &[crate::requirements::Tool::Git])?;
82 let text = read_input(args.file.as_deref().map(camino::Utf8Path::as_str))?;
83 let out = Output::new(args.json);
84
85 let title = match args.kind {
86 MessageKind::Commit | MessageKind::Title => text.lines().next().unwrap_or(""),
87 MessageKind::Body => args.title.as_deref().unwrap_or(""),
88 };
89 let exempt = bot_title(title);
90 let judgment = Judgment {
91 exempt,
92 scope_required: scope_required(&args.target),
93 };
94
95 let (findings, no_repo) = judge(&text, args.kind, &args.target, title, judgment);
96 if no_repo && !args.json {
97 out.warn(format!(
98 "{} is not a git repository; only the fixed .draft/ pattern was tested",
99 args.target
100 ));
101 }
102
103 if exempt {
104 out.result_line("exempt: the release bot's request, by its title");
105 }
106 for finding in &findings {
107 out.result_line(format!(
108 "{}:{} {}",
109 finding.class, finding.line, finding.detail
110 ));
111 }
112 if findings.is_empty() {
113 out.result_line(format!("clean {}", args.kind.as_str()));
114 }
115 let count = findings.len();
116 out.emit(&Report {
117 schema: "rk.message/4",
118 kind: args.kind.as_str(),
119 exempt,
120 findings,
121 })?;
122
123 if args.check && count > 0 {
124 return Err(RkError::check_failed(
125 Diagnostic::new(
126 Reason::StateDrift,
127 format!(
128 "the {} carries {count} finding{}",
129 args.kind.as_str(),
130 if count == 1 { "" } else { "s" }
131 ),
132 )
133 .expected("no agent attribution, no reference to a git-ignored path, and a scope the title check admits")
134 .action("reword the text; the findings above name each line"),
135 ));
136 }
137 Ok(())
138}
139
140#[derive(Debug, Clone, Copy)]
142pub(crate) struct Judgment {
143 pub(crate) exempt: bool,
145 pub(crate) scope_required: bool,
148}
149
150fn scope_required(target: &Utf8Path) -> bool {
157 let mode = crate::landing::manifest::load(target)
158 .ok()
159 .flatten()
160 .map(|record| record.profile.release.mode)
161 .or_else(|| {
162 crate::config::load(target.as_std_path())
163 .ok()
164 .flatten()
165 .and_then(|config| config.profile.release.mode)
166 });
167 mode.is_some_and(|mode| mode != crate::profile::ReleaseMode::None)
168}
169
170pub(crate) fn judge(
178 text: &str,
179 kind: MessageKind,
180 target: &Utf8Path,
181 title: &str,
182 judgment: Judgment,
183) -> (Vec<Finding>, bool) {
184 let exempt = judgment.exempt;
185 let mut findings = Vec::new();
186 let mut no_repo = false;
187 for (index, line) in text.lines().enumerate() {
188 if !exempt {
189 findings.extend(attribution_hits(line).into_iter().map(|detail| Finding {
190 class: "attribution",
191 line: index + 1,
192 detail,
193 }));
194 }
195 }
196 if matches!(kind, MessageKind::Commit | MessageKind::Title)
200 && !exempt
201 && let Some(scope) = misshapen_scope(title)
202 {
203 findings.push(Finding {
204 class: "scope-shape",
205 line: 1,
206 detail: format!(
207 "the scope '{scope}' is outside {}: lowercase letters, digits, and _ . / -",
208 landing::SCOPE_SHAPE
209 ),
210 });
211 }
212 if matches!(kind, MessageKind::Commit | MessageKind::Title)
213 && !exempt
214 && judgment.scope_required
215 && let Some(kind) = unscoped_type(title)
216 {
217 findings.push(Finding {
218 class: "scope-missing",
219 line: 1,
220 detail: format!(
221 "the subject names no scope after '{kind}', and this target names a release, so every subject reads <type>(<scope>): <description>"
222 ),
223 });
224 }
225 if !exempt
227 && judgment.scope_required
228 && let Some((line, id)) = advisory(text, kind, title)
229 {
230 let message = match kind {
232 MessageKind::Body => [title, text].join("\n"),
233 MessageKind::Commit | MessageKind::Title => text.to_owned(),
234 };
235 if !title.is_empty() && crate::integrate::release_intent(&message).is_none() {
236 findings.push(Finding {
237 class: "advisory-type",
238 line,
239 detail: format!(
240 "the message names the security advisory {id}, so its type must release: feat, fix, or perf, or a breaking change; a security update is fix(deps)"
241 ),
242 });
243 }
244 }
245 let mut seen: std::collections::BTreeSet<(usize, String)> = std::collections::BTreeSet::new();
246 match ignored_paths(target, text) {
247 IgnoreJudgment::Repo(hits) => {
248 for (line, token) in hits {
249 findings.push(Finding {
250 class: "internal-path",
251 line,
252 detail: format!("{token} is git-ignored in {target}"),
253 });
254 seen.insert((line, token));
255 }
256 }
257 IgnoreJudgment::NoRepo => no_repo = true,
258 }
259 findings.extend(
263 fixed_draft_hits(text)
264 .into_iter()
265 .filter(|(line, fragment)| {
266 !seen
267 .iter()
268 .any(|(seen_line, token)| seen_line == line && token.contains(fragment))
269 })
270 .map(|(line, fragment)| Finding {
271 class: "internal-path",
272 line,
273 detail: format!("{fragment} references the internal .draft/ tree"),
274 }),
275 );
276 findings.sort_by_key(|finding| finding.line);
277 (findings, no_repo)
278}
279
280pub(crate) fn exempt_title(title: &str) -> bool {
282 bot_title(title)
283}
284
285fn read_input(file: Option<&str>) -> Result<String, RkError> {
287 match file {
288 None | Some("-") => {
289 let mut text = String::new();
290 std::io::stdin().read_to_string(&mut text)?;
291 Ok(text)
292 }
293 Some(path) => Ok(std::fs::read_to_string(path)?),
294 }
295}
296
297fn bot_title(title: &str) -> bool {
301 let Some(rest) = title.strip_prefix("chore") else {
302 return false;
303 };
304 let rest = if rest.starts_with('(') {
305 let Some(rest) = ["(release)", "(master)", "(main)"]
306 .iter()
307 .find_map(|scope| rest.strip_prefix(scope))
308 else {
309 return false;
310 };
311 rest
312 } else {
313 rest
314 };
315 let Some(rest) = rest.strip_prefix(": ") else {
316 return false;
317 };
318 ["release", "v"].iter().any(|stem| {
319 rest.strip_suffix('\n')
320 .unwrap_or(rest)
321 .strip_prefix(stem)
322 .is_some_and(|tail| !tail.is_empty())
323 })
324}
325
326fn misshapen_scope(title: &str) -> Option<String> {
335 let (kind, rest) = title.split_once('(')?;
336 if kind.is_empty() || !kind.chars().all(|c| c.is_ascii_alphabetic()) {
337 return None;
338 }
339 let (scope, rest) = rest.split_once(')')?;
340 if !(rest.starts_with(':') || rest.starts_with("!:")) {
341 return None;
342 }
343 (!landing::scope_is_shaped(scope)).then(|| scope.to_owned())
344}
345
346fn unscoped_type(title: &str) -> Option<&str> {
351 let (head, _) = title.split_once(':')?;
352 let kind = head.strip_suffix('!').unwrap_or(head);
353 (!kind.is_empty() && kind.chars().all(|c| c.is_ascii_alphabetic())).then_some(kind)
354}
355
356fn advisory(text: &str, kind: MessageKind, title: &str) -> Option<(usize, String)> {
362 let titled = matches!(kind, MessageKind::Body)
363 .then(|| advisory_in(title).map(|id| (0, id)))
364 .flatten();
365 titled.or_else(|| {
366 text.lines()
367 .enumerate()
368 .find_map(|(index, line)| advisory_in(line).map(|id| (index + 1, id)))
369 })
370}
371
372fn advisory_in(line: &str) -> Option<String> {
376 line.char_indices()
377 .filter(|(at, _)| {
378 !line[..*at]
379 .chars()
380 .next_back()
381 .is_some_and(|c| c.is_ascii_alphanumeric())
382 })
383 .find_map(|(at, _)| {
384 let rest = &line[at..];
385 numbered(rest, "RUSTSEC-")
386 .or_else(|| numbered(rest, "CVE-"))
387 .or_else(|| ghsa(rest))
388 })
389}
390
391fn numbered(rest: &str, prefix: &str) -> Option<String> {
393 let tail = rest.strip_prefix(prefix)?;
394 let year = tail.get(..4)?;
395 let serial: String = tail
396 .get(4..)?
397 .strip_prefix('-')?
398 .chars()
399 .take_while(char::is_ascii_digit)
400 .collect();
401 (year.bytes().all(|byte| byte.is_ascii_digit()) && serial.len() >= 4)
402 .then(|| format!("{prefix}{year}-{serial}"))
403}
404
405fn ghsa(rest: &str) -> Option<String> {
408 let id = rest.strip_prefix("GHSA-")?.get(..14)?;
409 let groups: Vec<&str> = id.split('-').collect();
410 (groups.len() == 3
411 && groups.iter().all(|group| {
412 group.len() == 4
413 && group
414 .bytes()
415 .all(|byte| byte.is_ascii_digit() || byte.is_ascii_lowercase())
416 }))
417 .then(|| format!("GHSA-{id}"))
418}
419
420fn attribution_hits(line: &str) -> Vec<String> {
427 let mut hits = Vec::new();
428 if [
430 "Generated with Claude",
431 "generated with Claude",
432 "Generated with [Claude",
433 "generated with [Claude",
434 ]
435 .iter()
436 .any(|variant| line.contains(variant))
437 {
438 hits.push("generated-with-claude attribution".to_owned());
439 }
440 if line.contains("🤖 Generated with") {
442 hits.push("robot generated-with attribution".to_owned());
443 }
444 let trailer = [
446 "Co-Authored-By:",
447 "Co-Authored-by:",
448 "Co-authored-By:",
449 "Co-authored-by:",
450 "co-Authored-By:",
451 "co-Authored-by:",
452 "co-authored-By:",
453 "co-authored-by:",
454 ]
455 .iter()
456 .filter_map(|variant| line.find(variant))
457 .min();
458 if let Some(at) = trailer {
459 let tail = &line[at..];
460 if ["Claude", "claude", "Copilot", "copilot", "Codex", "ChatGPT"]
461 .iter()
462 .any(|agent| tail.contains(agent))
463 {
464 hits.push("agent co-authored-by trailer".to_owned());
465 }
466 }
467 if line.contains("noreply@anthropic.com") {
469 hits.push("anthropic noreply address".to_owned());
470 }
471 hits
472}
473
474enum IgnoreJudgment {
476 Repo(Vec<(usize, String)>),
478 NoRepo,
480}
481
482fn ignored_paths(target: &Utf8Path, text: &str) -> IgnoreJudgment {
488 let candidates: Vec<(usize, String)> = text
489 .lines()
490 .enumerate()
491 .flat_map(|(index, line)| {
492 line.split_whitespace()
493 .filter_map(path_token)
494 .map(move |token| (index + 1, token))
495 })
496 .collect();
497 if candidates.is_empty() {
498 return IgnoreJudgment::Repo(Vec::new());
499 }
500 check_ignore(target, &candidates).map_or(IgnoreJudgment::NoRepo, IgnoreJudgment::Repo)
501}
502
503fn fixed_draft_hits(text: &str) -> Vec<(usize, String)> {
510 let mut hits = Vec::new();
511 for (index, line) in text.lines().enumerate() {
512 for (at, _) in line.match_indices(".draft/") {
513 let boundary = line[..at]
514 .chars()
515 .next_back()
516 .is_none_or(|c| !c.is_ascii_alphanumeric());
517 if !boundary {
518 continue;
519 }
520 let tail = &line[at..];
521 let end = tail.find(char::is_whitespace).unwrap_or(tail.len());
522 let fragment = tail[..end].trim_end_matches(|c: char| "()[]<>`'\".,;:".contains(c));
523 hits.push((index + 1, fragment.to_owned()));
524 }
525 }
526 hits
527}
528
529fn path_token(token: &str) -> Option<String> {
535 let token = token
536 .trim_start_matches(|c: char| "()[]<>`'\"".contains(c))
537 .trim_end_matches(|c: char| "()[]<>`'\".,;:".contains(c));
538 if token.contains("://") || token.starts_with('-') || token.contains('$') {
539 return None;
540 }
541 let (head, tail) = token.split_once('/')?;
542 if head.is_empty() || tail.is_empty() {
543 return None;
544 }
545 Some(token.to_owned())
546}
547
548fn check_ignore(target: &Utf8Path, candidates: &[(usize, String)]) -> Option<Vec<(usize, String)>> {
557 let mut command = std::process::Command::new(crate::probes::git_bin());
558 let mut child = command
559 .arg("-C")
560 .arg(target.as_std_path())
561 .args(["check-ignore", "--stdin", "-z"])
562 .stdin(std::process::Stdio::piped())
563 .stdout(std::process::Stdio::piped())
564 .stderr(std::process::Stdio::null())
565 .spawn()
566 .ok()?;
567 let writer = child.stdin.take().map(|mut stdin| {
568 let payload: Vec<u8> = candidates
569 .iter()
570 .flat_map(|(_, token)| token.as_bytes().iter().copied().chain([0]))
571 .collect();
572 std::thread::spawn(move || {
573 let _ = stdin.write_all(&payload);
574 })
575 });
576 let output = child.wait_with_output().ok()?;
577 if let Some(writer) = writer {
578 let _ = writer.join();
579 }
580 if !matches!(output.status.code(), Some(0 | 1)) {
583 return None;
584 }
585 let ignored: std::collections::BTreeSet<&[u8]> = output
586 .stdout
587 .split(|byte| *byte == 0)
588 .filter(|path| !path.is_empty())
589 .collect();
590 Some(
591 candidates
592 .iter()
593 .filter(|(_, token)| ignored.contains(token.as_bytes()))
594 .cloned()
595 .collect(),
596 )
597}
598
599#[must_use]
601pub fn guard_patterns() -> Vec<(&'static str, &'static str)> {
602 let mut class = "";
603 let mut patterns = Vec::new();
604 for line in GUARDS.lines() {
605 if let Some(named) = line.strip_prefix("# class: ") {
606 class = named;
607 } else if !line.starts_with('#') && !line.is_empty() {
608 patterns.push((class, line));
609 }
610 }
611 patterns
612}
613
614#[cfg(test)]
615mod tests {
616 use super::{
617 Finding, Judgment, Report, attribution_hits, bot_title, fixed_draft_hits, guard_patterns,
618 judge, path_token, unscoped_type,
619 };
620
621 #[test]
626 fn the_message_schema_snapshot_holds() {
627 let report = Report {
628 schema: "rk.message/4",
629 kind: "commit",
630 exempt: false,
631 findings: vec![
632 Finding {
633 class: "scope-shape",
634 line: 1,
635 detail: "the scope 'Specs Ugly' is outside [a-z0-9._/-]+: lowercase letters, digits, and _ . / -".into(),
636 },
637 Finding {
638 class: "internal-path",
639 line: 3,
640 detail: ".draft/plan.md is git-ignored in .".into(),
641 },
642 ],
643 };
644 assert_eq!(
645 serde_json::to_string(&report).expect("a report serializes"),
646 r#"{"schema":"rk.message/4","kind":"commit","exempt":false,"findings":[{"class":"scope-shape","line":1,"detail":"the scope 'Specs Ugly' is outside [a-z0-9._/-]+: lowercase letters, digits, and _ . / -"},{"class":"internal-path","line":3,"detail":".draft/plan.md is git-ignored in ."}]}"#
647 );
648 }
649
650 #[test]
654 fn the_guard_file_holds_the_patterns_the_matchers_implement() {
655 assert_eq!(
656 guard_patterns(),
657 [
658 ("attribution", r"[Gg]enerated with \[?Claude"),
659 ("attribution", "🤖 Generated with"),
660 (
661 "attribution",
662 r"[Cc]o-[Aa]uthored-[Bb]y:.*([Cc]laude|[Cc]opilot|Codex|ChatGPT)"
663 ),
664 ("attribution", r"noreply@anthropic\.com"),
665 ("internal-path", r"(^|[^A-Za-z0-9])\.draft/"),
666 ]
667 );
668 }
669
670 #[test]
671 fn the_attribution_matchers_cover_the_patterns() {
672 for line in [
673 "Generated with Claude Code",
674 "generated with [Claude Code](https://claude.com/claude-code)",
675 "🤖 Generated with tooling",
676 "Co-Authored-By: Claude <x@y>",
677 "co-authored-by: github-copilot",
678 "Co-authored-by: Codex",
679 "Co-Authored-By: ChatGPT",
680 "Signed noreply@anthropic.com",
681 ] {
682 assert!(!attribution_hits(line).is_empty(), "{line} must match");
683 }
684 for line in [
685 "Generated with release-plz",
686 "Co-authored-by: A Person <person@example.com>",
687 "the claude skill route",
688 "Co-authored-by: Autopilot Team",
689 "Xenerated with Claude",
690 "CO-AUTHORED-BY: Claude",
691 ] {
692 assert!(attribution_hits(line).is_empty(), "{line} must not match");
693 }
694 }
695
696 #[test]
699 fn a_multibyte_prefix_neither_panics_nor_hides_the_trailer() {
700 let line = format!("{} Co-Authored-By: Claude", "İ".repeat(40));
703 assert!(!attribution_hits(&line).is_empty());
704 assert!(attribution_hits(&format!("{} nothing here", "İ".repeat(40))).is_empty());
705 }
706
707 #[test]
710 fn the_fixed_pattern_matches_decorated_references_only_at_a_boundary() {
711 assert_eq!(
712 fixed_draft_hits(
713 "path=.draft/plan.md
714"
715 ),
716 vec![(1, ".draft/plan.md".to_owned())]
717 );
718 assert_eq!(
719 fixed_draft_hits(
720 "a [plan](.draft/plan.md) link
721"
722 ),
723 vec![(1, ".draft/plan.md".to_owned())]
724 );
725 assert_eq!(
726 fixed_draft_hits(
727 ".draft/x
728"
729 ),
730 vec![(1, ".draft/x".to_owned())]
731 );
732 assert!(
733 fixed_draft_hits(
734 "archived.draft/x
735"
736 )
737 .is_empty()
738 );
739 assert!(
740 fixed_draft_hits(
741 "no reference here
742"
743 )
744 .is_empty()
745 );
746 }
747
748 #[test]
751 fn the_bot_exemption_is_the_title_checks_bot_alternative() {
752 for title in [
753 "chore: release v0.2.6",
754 "chore(release): v0.3.0",
755 "chore(master): release 1.0.0",
756 "chore(main): v2",
757 ] {
758 assert!(bot_title(title), "{title} is the bot's");
759 }
760 for title in [
761 "chore: bump deps",
762 "chore(deps): release v1",
763 "feat(cli): release v1",
764 "chore(release): ",
765 "chore(release): v",
766 "chore:release v1",
767 ] {
768 assert!(!bot_title(title), "{title} is not the bot's");
769 }
770 }
771
772 #[test]
773 fn a_path_token_is_two_segments_without_url_flag_or_variable() {
774 assert_eq!(
775 path_token("(.draft/plan.md)"),
776 Some(".draft/plan.md".into())
777 );
778 assert_eq!(path_token("`src/main.rs`,"), Some("src/main.rs".into()));
779 assert_eq!(path_token("https://a.b/c"), None);
780 assert_eq!(path_token("--flag/value"), None);
781 assert_eq!(path_token("$HOME/x"), None);
782 assert_eq!(path_token("and/or"), Some("and/or".into()));
783 assert_eq!(path_token("word"), None);
784 assert_eq!(path_token("trailing/"), None);
785 }
786
787 #[test]
794 fn workflow_only_a_header_with_no_scope_passes_only_without_a_release() {
795 let dir = tempfile::tempdir().expect("a scratch dir exists");
796 let target = camino::Utf8Path::from_path(dir.path()).expect("utf-8");
797 let judged = |text: &str, scope_required: bool| {
798 let title = text.lines().next().unwrap_or("");
799 judge(
800 text,
801 crate::cli::message::MessageKind::Commit,
802 target,
803 title,
804 Judgment {
805 exempt: bot_title(title),
806 scope_required,
807 },
808 )
809 .0
810 };
811 assert!(judged("fix: drop the stale path\n", false).is_empty());
812 let refused = judged("fix: drop the stale path\n", true);
813 assert_eq!(refused.len(), 1, "{refused:?}");
814 assert_eq!(refused[0].class, "scope-missing");
815 assert!(refused[0].detail.contains("names no scope"), "{refused:?}");
816 assert!(judged("fix(paths): drop the stale path\n", true).is_empty());
817 assert!(judged("chore: release v1.2.0\n", true).is_empty());
818 assert_eq!(unscoped_type("feat!: break it"), Some("feat"));
819 assert_eq!(unscoped_type("feat(x): add it"), None);
820 assert_eq!(unscoped_type("Merge branch 'x' into master"), None);
821 assert_eq!(unscoped_type("fixup! feat(x): add it"), None);
822 assert_eq!(
824 judged("fix(Bad Scope): mend\n", false)[0].class,
825 "scope-shape"
826 );
827 }
828}