Skip to main content

lean_ctx_cloud/capture/
rules.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Text rules of the capture gate (SPEC-ENGINE §3.1.4, G2–G9): one
3//! complete, single-line claim of 24–300 characters that is not log output,
4//! not truncated and not a list. Rules reject; they never rewrite.
5
6use std::sync::LazyLock;
7
8use regex::Regex;
9
10use super::ReasonCode;
11
12pub const MIN_STATEMENT_CHARS: usize = 24;
13pub const MAX_STATEMENT_CHARS: usize = 300;
14
15/// Abbreviations whose dot never ends a sentence (G4).
16const ABBREVIATIONS: [&str; 6] = ["e.g.", "i.e.", "vs.", "etc.", "approx.", "no."];
17
18static LOG_PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
19    [
20        r"\d{4}-\d{2}-\d{2}[T ]\d{2}:\d{2}",
21        r"\[exit:",
22        r"\x1b\[",
23        r"(?m)^\s*at \S+\(",
24        r#"File ".*", line \d+"#,
25        r"^\s*[{\[]",
26        r"```",
27    ]
28    .iter()
29    .map(|p| Regex::new(p).expect("static log pattern"))
30    .collect()
31});
32
33static LIST_MARKER: LazyLock<Regex> =
34    LazyLock::new(|| Regex::new(r"^\s*([-*•]|\d+[.)])\s").expect("static list pattern"));
35
36/// G2–G9 on a claim statement (already trimmed).
37pub fn check_statement(statement: &str) -> Result<(), ReasonCode> {
38    check_length(statement, MIN_STATEMENT_CHARS, MAX_STATEMENT_CHARS)?;
39    check_single_line(statement)?;
40    check_list(statement)?;
41    check_log(statement)?;
42    if sentence_count(statement) > 2 {
43        return Err(ReasonCode::MultiClaim);
44    }
45    check_sentence(statement, true)?;
46    check_truncated(statement)?;
47    check_path_share(statement)
48}
49
50/// G2 with the given bounds (Unicode scalar values).
51pub fn check_length(text: &str, min: usize, max: usize) -> Result<(), ReasonCode> {
52    let n = text.chars().count();
53    if n < min {
54        Err(ReasonCode::TooShort)
55    } else if n > max {
56        Err(ReasonCode::TooLong)
57    } else {
58        Ok(())
59    }
60}
61
62/// G3.
63pub fn check_single_line(text: &str) -> Result<(), ReasonCode> {
64    if text.contains(['\n', '\r']) {
65        Err(ReasonCode::MultiLine)
66    } else {
67        Ok(())
68    }
69}
70
71/// G8.
72pub fn check_list(text: &str) -> Result<(), ReasonCode> {
73    if LIST_MARKER.is_match(text) {
74        Err(ReasonCode::MultiClaim)
75    } else {
76        Ok(())
77    }
78}
79
80/// G6: timestamps, exit markers, ANSI, stack frames, JSON, tables, fences.
81pub fn check_log(text: &str) -> Result<(), ReasonCode> {
82    if LOG_PATTERNS.iter().any(|re| re.is_match(text)) || text.matches('|').count() >= 3 {
83        Err(ReasonCode::LogText)
84    } else {
85        Ok(())
86    }
87}
88
89/// G4: sentences end at `. ! ?` followed by a space and an uppercase letter,
90/// except after a listed abbreviation.
91pub fn sentence_count(text: &str) -> usize {
92    let chars: Vec<char> = text.chars().collect();
93    let mut count = 1;
94    for (i, c) in chars.iter().enumerate() {
95        if !matches!(c, '.' | '!' | '?') {
96            continue;
97        }
98        let next_upper =
99            chars.get(i + 1) == Some(&' ') && chars.get(i + 2).is_some_and(|c| c.is_uppercase());
100        if !next_upper {
101            continue;
102        }
103        let head: String = chars[..=i].iter().collect();
104        let word = head.rsplit(' ').next().unwrap_or_default().to_lowercase();
105        if !ABBREVIATIONS.contains(&word.as_str()) {
106            count += 1;
107        }
108    }
109    count
110}
111
112/// First words that open a fragment, not a claim (owner 02.11.).
113const FRAGMENT_STARTS: &[&str] = &["Not", "Listed", "See", "Also", "e.g.", "i.e."];
114
115/// G5: starts with an uppercase letter, digit or backtick; is no fragment
116/// when `punctuated` (a claim, `is_fragment`); ends with `. ! ?`
117/// (optionally followed by a closing backtick) when `punctuated`; has a
118/// word of three or more letters that is not part of a path.
119pub fn check_sentence(text: &str, punctuated: bool) -> Result<(), ReasonCode> {
120    let first = text.chars().next().ok_or(ReasonCode::NotSentence)?;
121    if !(first.is_uppercase() || first.is_ascii_digit() || first == '`') {
122        return Err(ReasonCode::NotSentence);
123    }
124    if punctuated && is_fragment(text) {
125        return Err(ReasonCode::NotSentence);
126    }
127    if punctuated {
128        let body = text.strip_suffix('`').unwrap_or(text);
129        if !body.ends_with(['.', '!', '?']) {
130            return Err(ReasonCode::NotSentence);
131        }
132    }
133    let has_word = text
134        .split_whitespace()
135        .filter(|t| !is_path_like(t))
136        .any(|t| t.chars().filter(|c| c.is_alphabetic()).count() >= 3);
137    if has_word {
138        Ok(())
139    } else {
140        Err(ReasonCode::NotSentence)
141    }
142}
143
144/// A claim that is a fragment (C0 2.2 G5): its first word (trailing `, ; :`
145/// trimmed) is a [`FRAGMENT_STARTS`] word; or, with balanced backticks (an
146/// odd count is G7's truncated), more than half of its characters are code
147/// spans (backticks included), or fewer than four letter runs stand
148/// outside them.
149fn is_fragment(text: &str) -> bool {
150    let first_word = text
151        .split_whitespace()
152        .next()
153        .unwrap_or_default()
154        .trim_end_matches([',', ';', ':']);
155    if FRAGMENT_STARTS.contains(&first_word) {
156        return true;
157    }
158    if !text.matches('`').count().is_multiple_of(2) {
159        return false;
160    }
161    let (mut in_code, mut code_chars, mut total) = (false, 0usize, 0usize);
162    let mut prose = String::new();
163    for c in text.chars() {
164        total += 1;
165        if c == '`' {
166            in_code = !in_code;
167            code_chars += 1;
168            prose.push(' ');
169        } else if in_code {
170            code_chars += 1;
171        } else {
172            prose.push(c);
173        }
174    }
175    let words = prose
176        .split(|c: char| !c.is_alphabetic())
177        .filter(|w| !w.is_empty())
178        .count();
179    code_chars * 2 > total || words < 4
180}
181
182/// G7: no trailing ellipsis, dash, comma or open parenthesis; balanced
183/// backticks and brackets.
184pub fn check_truncated(text: &str) -> Result<(), ReasonCode> {
185    if text.ends_with(['…', '-', ',', '(']) || text.ends_with("...") {
186        return Err(ReasonCode::Truncated);
187    }
188    if !text.matches('`').count().is_multiple_of(2) {
189        return Err(ReasonCode::Truncated);
190    }
191    let mut depth: Vec<char> = Vec::new();
192    for c in text.chars() {
193        match c {
194            '(' | '[' | '{' => depth.push(c),
195            ')' | ']' | '}' => {
196                let open = match c {
197                    ')' => '(',
198                    ']' => '[',
199                    _ => '{',
200                };
201                if depth.pop() != Some(open) {
202                    return Err(ReasonCode::Truncated);
203                }
204            }
205            _ => {}
206        }
207    }
208    if depth.is_empty() {
209        Ok(())
210    } else {
211        Err(ReasonCode::Truncated)
212    }
213}
214
215/// A token that reads as a path: contains `/` or `\`, or `::`.
216fn is_path_like(token: &str) -> bool {
217    let t = token.trim_matches(|c: char| matches!(c, '`' | '"' | '\'' | ',' | '.' | '(' | ')'));
218    t.contains('/') || t.contains('\\') || t.contains("::")
219}
220
221/// G9: characters inside path-like tokens are at most 40 % of the text.
222pub fn check_path_share(text: &str) -> Result<(), ReasonCode> {
223    let total = text.chars().filter(|c| !c.is_whitespace()).count();
224    let paths: usize = text
225        .split_whitespace()
226        .filter(|t| is_path_like(t))
227        .map(|t| t.chars().count())
228        .sum();
229    if total > 0 && paths * 100 > total * 40 {
230        Err(ReasonCode::LogText)
231    } else {
232        Ok(())
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239
240    #[test]
241    fn a_clean_claim_passes() {
242        for ok in [
243            "The outbox retries a refused push after the lease is renewed.",
244            "Builds use the shared target, e.g. for worktrees. They never clean it.",
245            "`cargo fast` builds a development binary without LTO.",
246            "3 retries are enough for the relay handshake on slow links.",
247        ] {
248            assert_eq!(check_statement(ok), Ok(()), "{ok}");
249        }
250    }
251
252    #[test]
253    fn each_rule_names_its_reason() {
254        let cases = [
255            ("Too short.", ReasonCode::TooShort),
256            (
257                &*format!("{}.", "A very long claim ".repeat(20)),
258                ReasonCode::TooLong,
259            ),
260            (
261                "The relay drops frames.\nIt also logs them twice.",
262                ReasonCode::MultiLine,
263            ),
264            (
265                "The relay drops frames. It logs twice. It never retries.",
266                ReasonCode::MultiClaim,
267            ),
268            (
269                "- The relay drops frames on slow links.",
270                ReasonCode::MultiClaim,
271            ),
272            (
273                "the relay drops frames on slow links.",
274                ReasonCode::NotSentence,
275            ),
276            (
277                "The relay drops frames on slow links",
278                ReasonCode::NotSentence,
279            ),
280            (
281                "Build failed at 2026-10-24T14:02 with code 101.",
282                ReasonCode::LogText,
283            ),
284            (
285                "Command ended with [exit:1] after the build.",
286                ReasonCode::LogText,
287            ),
288            (
289                "Columns are | a | b | c in the report table.",
290                ReasonCode::LogText,
291            ),
292            (
293                "The relay drops frames when the (link is slow.",
294                ReasonCode::Truncated,
295            ),
296            (
297                "Run `cargo test and then check the output now.",
298                ReasonCode::Truncated,
299            ),
300            (
301                "The fix touched rust/src/core/cloud/outbox.rs and rust/src/core/cloud/capture/mod.rs.",
302                ReasonCode::LogText,
303            ),
304        ];
305        for (text, reason) in cases {
306            assert_eq!(check_statement(text), Err(reason), "{text}");
307        }
308    }
309
310    #[test]
311    fn truncated_endings_are_refused() {
312        for t in [
313            "Then the relay…",
314            "Then the relay...",
315            "Then the relay -",
316            "Then the relay,",
317        ] {
318            assert_eq!(check_truncated(t), Err(ReasonCode::Truncated), "{t}");
319        }
320    }
321
322    #[test]
323    fn abbreviations_do_not_split_sentences() {
324        assert_eq!(
325            sentence_count("Use a lease, e.g. LeanCTX gives one. Then renew."),
326            2
327        );
328        assert_eq!(sentence_count("Compare A vs. B before merging."), 1);
329    }
330}