Skip to main content

release_kit/commands/
message.rs

1//! `rk message`: the content guards over a commit message, a title, or a
2//! request body.
3//!
4//! Two classes of finding are declared in `blocks/message-guards`:
5//! attribution an agent left in the text, and a reference to a path the
6//! target repository ignores — an internal artifact that would leak into
7//! the permanent record. The release bot's request is exempt from the
8//! attribution class alone, recognized by exactly the title shape the
9//! landed title check admits for the bot; the ignored-path class always
10//! runs. The guard file owns the patterns; the matchers here implement
11//! them by hand — the binary carries no regex engine — and a unit test
12//! pins the file to the set the matchers cover, so a pattern edit and its
13//! matcher move together.
14//!
15//! A third class is a shape rather than a forbidden pattern, so it lives
16//! here and not in the guard file: a subject whose scope falls outside
17//! [`landing::SCOPE_SHAPE`]. The landed `conventional-pre-commit` hook
18//! requires a scope but takes no pattern for it, so without this class a
19//! scope the forge's title check rejects passes at the desk.
20//!
21//! A fourth class is the scope's absence, judged only where the target's
22//! record names a release, because the changelog reads the scope. Under
23//! `release.mode = "none"` a scope is preferred and not required, so a
24//! Conventional Commit header with none passes.
25//!
26//! A fifth class, also judged only where the record names a release, is
27//! a security advisory under a type that releases nothing: a message that
28//! names a `RUSTSEC-`, `GHSA-`, or `CVE-` identifier must carry a
29//! releasing type, `feat`, `fix`, or `perf`, or mark a breaking change,
30//! because a security update always releases. The classifier is
31//! [`crate::integrate::release_intent`], the one the release engine reads.
32
33use 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
45/// The guard patterns, verbatim: `blocks/message-guards`.
46static GUARDS: &str = include_str!("../../blocks/message-guards");
47
48/// One finding.
49#[derive(Debug, Serialize)]
50pub(crate) struct Finding {
51    /// `attribution`, `internal-path`, `scope-shape`, `scope-missing`, or
52    /// `advisory-type`.
53    pub(crate) class: &'static str,
54    /// The 1-based line the finding sits on.
55    pub(crate) line: usize,
56    /// What matched.
57    pub(crate) detail: String,
58}
59
60/// The machine form of a report.
61#[derive(Debug, Serialize)]
62struct Report {
63    /// The shape version of this document.
64    schema: &'static str,
65    /// What the text was judged as.
66    kind: &'static str,
67    /// Whether the bot exemption applied to the attribution class.
68    exempt: bool,
69    /// Every finding, in line order.
70    findings: Vec<Finding>,
71}
72
73/// Judge the text and report; exit 1 under `--check` when a finding stands.
74///
75/// # Errors
76///
77/// Returns [`RkError::CheckFailed`] under `--check` when any finding
78/// stands, [`RkError::Io`] when the input cannot be read, and an error
79/// when the report cannot serialize.
80pub 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/// What decides the judgment beside the text itself.
141#[derive(Debug, Clone, Copy)]
142pub(crate) struct Judgment {
143    /// Whether the release bot's exemption applies, by the title.
144    pub(crate) exempt: bool,
145    /// Whether the subject must name a scope: wherever the target's record
146    /// names a release.
147    pub(crate) scope_required: bool,
148}
149
150/// Whether the target at `target` requires a scope on every subject: its
151/// record, or its configuration where no record stands, names a release.
152/// A target that states neither is judged as before, by the landed
153/// `conventional-pre-commit` hook alone.
154///
155/// SATISFIES project-profile:a-release-less-landing-carries-no-release-text
156fn 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
170/// Every finding one text carries, in line order, beside whether the
171/// ignore judgment had no repository to ask.
172///
173/// The one owner of what `rk message --check` judges, so a second caller
174/// cannot judge a weaker set. `rk integrate` calls it before writing a
175/// trunk commit with `git commit-tree`, which fires no `commit-msg` hook
176/// and would otherwise publish a message the landed hook refuses.
177pub(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    // The subject is line 1 of a commit message and of a title; a body's
197    // title is context passed beside it, and its findings would carry no
198    // line the reader can open.
199    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    // SATISFIES release-engine:an-advisory-takes-a-releasing-type
226    if !exempt
227        && judgment.scope_required
228        && let Some((line, id)) = advisory(text, kind, title)
229    {
230        // A body is judged under its title, which carries its type.
231        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    // A fixed-pattern fragment already inside a reported token on the
260    // same line — `nested/.draft/plan.md` carrying `.draft/plan.md` — is
261    // the same reference, not a second finding.
262    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
280/// Whether the release bot's exemption applies to one title.
281pub(crate) fn exempt_title(title: &str) -> bool {
282    bot_title(title)
283}
284
285/// The text: stdin for `-` or no file, the file otherwise.
286fn 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
297/// Whether the title is the release bot's, by exactly the shape the
298/// landed title check admits for it:
299/// `^chore(\((release|master|main)\))?: (release|v).+$`.
300fn 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
326/// The subject's scope where it falls outside [`landing::SCOPE_SHAPE`],
327/// or `None`.
328///
329/// The scope is what sits between the parentheses of a `type(scope):`
330/// subject, with the breaking `!` outside them. A subject carrying no
331/// scope at all returns `None`: requiring one is the landed
332/// `conventional-pre-commit` hook's job, and this class judges the shape
333/// of a scope that is there.
334fn 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
346/// The type of a Conventional Commit subject that names no scope, or
347/// `None`: `fix: drop it` and `feat!: break it` answer, while a scoped
348/// subject and a subject that is no Conventional Commit at all do not,
349/// because the landed `conventional-pre-commit` hook owns that shape.
350fn 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
356/// The first security advisory identifier the text names, as its 1-based
357/// line and the identifier: `RUSTSEC-<year>-<four digits>`,
358/// `CVE-<year>-<four or more digits>`, or `GHSA-` and three groups of four
359/// lowercase letters or digits, each after no ASCII letter or digit. A
360/// body's title is judged too, as line 0.
361fn 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
372/// The first advisory identifier on one line, as the title checks match
373/// it: `(^|[^A-Za-z0-9])(RUSTSEC-[0-9]{4}-[0-9]{4}|CVE-[0-9]{4}-[0-9]{4,}|GHSA(-[0-9a-z]{4}){3})`,
374/// implemented by hand.
375fn 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
391/// `<prefix><four digits>-<four or more digits>` at the start of `rest`.
392fn 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
405/// `GHSA-` and three groups of four lowercase letters or digits at the
406/// start of `rest`.
407fn 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
420/// Every attribution match on one line, as the matched fragment.
421///
422/// Each matcher implements one pattern of the guard file's attribution
423/// class by hand, exactly — each bracketed case class expands to its
424/// literal variants, never to a broader case-insensitive search — and
425/// [`guard_patterns`] with its test holds the two in step.
426fn attribution_hits(line: &str) -> Vec<String> {
427    let mut hits = Vec::new();
428    // [Gg]enerated with \[?Claude
429    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    // 🤖 Generated with
441    if line.contains("🤖 Generated with") {
442        hits.push("robot generated-with attribution".to_owned());
443    }
444    // [Cc]o-[Aa]uthored-[Bb]y:.*([Cc]laude|[Cc]opilot|Codex|ChatGPT)
445    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    // noreply@anthropic\.com
468    if line.contains("noreply@anthropic.com") {
469        hits.push("anthropic noreply address".to_owned());
470    }
471    hits
472}
473
474/// What the ignored-path check could determine.
475enum IgnoreJudgment {
476    /// The target is a repository; these `(line, token)` pairs are ignored.
477    Repo(Vec<(usize, String)>),
478    /// No repository at the target; only the fixed pattern judged.
479    NoRepo,
480}
481
482/// The path-shaped tokens of the text the target's ignore rules reject,
483/// degraded to no repository judgment where the target is none. The
484/// fixed `.draft/` pattern is not here: it runs unconditionally in
485/// [`fixed_draft_hits`], so a decorated reference no clean token carries
486/// still answers, repository or not.
487fn 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
503/// Every `(line, fragment)` the fixed internal-path pattern matches:
504/// `(^|[^A-Za-z0-9])\.draft/`, implemented exactly — a `.draft/` whose
505/// preceding character, where one exists, is not ASCII-alphanumeric —
506/// with the fragment read forward to the surrounding whitespace and
507/// trimmed of trailing wrappers, so a decorated reference like
508/// `path=.draft/plan.md` or a markdown link still answers.
509fn 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
529/// A whitespace token reduced to its path candidate: wrapping brackets
530/// and quotes trimmed from both edges, sentence punctuation only from the
531/// end — a leading dot is part of a hidden path — URLs, flags, and
532/// variables skipped, and only a token of two or more segments kept,
533/// because a bare word is prose, not a reference.
534fn 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
548/// The candidates the target's git ignores, or `None` where the target is
549/// not a repository the check could consult.
550///
551/// `-z` on both sides: input and output are NUL-delimited, so a non-ASCII
552/// path comes back verbatim rather than `core.quotePath`-escaped and the
553/// byte comparison holds. The writer is its own thread, because git may
554/// fill its stdout pipe while this process is still writing stdin — the
555/// buffering deadlock its documentation assigns the caller.
556fn 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    // 0: some input is ignored; 1: none is. Anything else — 128 for a
581    // missing repository above all — is a target the check cannot judge.
582    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/// The guard file's `(class, pattern)` lines, in order.
600#[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    /// The complete `rk.message/4` shape, held by snapshot: the class
622    /// vocabulary is part of the contract, so the third class moved the
623    /// version rather than arriving unannounced, and the fourth,
624    /// `scope-missing`, moved it again.
625    #[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    /// The guard file and the hand matchers move together: this is the
651    /// exact pattern set the matchers above implement, so an edit to
652    /// `blocks/message-guards` fails here until the matcher follows.
653    #[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    /// Case transformation never feeds an offset back into the original:
697    /// multibyte text before a trailer must match without panicking.
698    #[test]
699    fn a_multibyte_prefix_neither_panics_nor_hides_the_trailer() {
700        // Enough expanding characters that a lowercased offset would
701        // fall past the original string's end, not merely drift.
702        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    /// The fixed pattern is `(^|[^A-Za-z0-9])\.draft/`, exactly: a
708    /// decorated reference answers, an alphanumeric-adjacent one does not.
709    #[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    /// Exactly the landed title check's bot alternative:
749    /// `^chore(\((release|master|main)\))?: (release|v).+$`.
750    #[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    /// A header with no scope passes where the record names no release and
788    /// refuses where it names one, naming the missing scope. The bot's
789    /// request, which names none, stays exempt, and a subject that is no
790    /// Conventional Commit is the landed hook's to judge.
791    ///
792    /// SATISFIES project-profile:a-release-less-landing-carries-no-release-text
793    #[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        // A misshapen scope is still judged where none is required.
823        assert_eq!(
824            judged("fix(Bad Scope): mend\n", false)[0].class,
825            "scope-shape"
826        );
827    }
828}