interplane.Get Omega
Read in your language

aien-sovereign-core-mv

AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.

Brought by drakestapleton

branch main Branches Tags History

aien-sovereign-core-mv / crates / aien-runtime / src / requirements.rs

965 lines · 40673 bytes Raw Blame History
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Drake Stapleton (AIEN / aien-dev)
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8// http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Requirement validation for composed documents.
17//!
18//! A task goal can state a measurable requirement ("in at least 20 lines",
19//! "sections titled A, B and C", "covers preparing and testing"). This module
20//! defines a small typed set of requirements, extracts them deterministically
21//! from the goal text ([`analyze`], in `requirements_extract`), and checks the
22//! COMPLETE parsed document (the content that would be saved).
23//!
24//! ## Two outcomes of reading a goal
25//!
26//! [`analyze`] returns an [`Extraction`]: the RECOGNIZED requirements, and the
27//! UNCERTAIN spans. An uncertain span is goal text that looks like an explicit
28//! measurable requirement (a bound word and a number next to a document
29//! noun, "titled", "covers", "include the word", ...) that extraction could
30//! not interpret reliably. Uncertainty is never treated as satisfied: the
31//! task is refused before any model call, the report lists the spans
32//! (`ComposeTaskReport::requirements_uncertain`) and nothing is approved,
33//! committed or written.
34//!
35//! ## Supported requirements
36//!
37//! The exact wordings are in the table of `requirements_extract`; in short:
38//! counts (`at least|at most|no fewer than|no more than|a minimum of|up to|
39//! more than|fewer than|N or more|N or fewer` with digits or number words
40//! one..twenty) of lines, words, list items, steps, sections/headings and
41//! questions, and `under|below|within N` before lines or words only (sc#383,
42//! `under 200 words` = at most 199); section titles (`sections titled A, B and C`), topics
43//! (`covers A, B and C`), required words and phrases, and a minimum number
44//! of sentences in every section; and a markdown heading as the first line
45//! (`start with a Markdown heading line that begins with "# "`).
46//!
47//! ## What a requirement is judged on
48//!
49//! The COMPLETE document that would be saved (in edit mode the merged file,
50//! not the model's reply). An edit only adds lines, so a prior file that
51//! already exceeds a `MaxLines` is refused before any attempt.
52//!
53//! `AddedLines` (a request such as "add 2 lines to README.md") is the one requirement
54//! measured against the PRIOR file: the number of non-empty lines of the complete
55//! proposed bytes that are not in the longest common subsequence with the
56//! prior file's non-empty lines (trailing whitespace ignored). A new file is
57//! compared with an empty prior. Callers bind the prior with
58//! `Extraction::resolved`; an unresolved `AddedLines` is unmet (fails closed).
59//! An edit may only ADD: every non-empty line of the prior file must survive in
60//! order (trailing whitespace may differ), otherwise the requirement is unmet
61//! whatever the number of added lines. Replacing or deleting lines is a change the
62//! goal did not ask for, so "add 2 lines" can never wipe or rewrite the file.
63//! The approved path binds the file found in the workspace.
64//!
65//! Counting: `MinLines`/`MaxLines` count every non-empty line of the file,
66//! INCLUDING code lines and code-fence marker lines; `MinWords`/`MaxWords`
67//! count every whitespace-separated word of the file. Sections, questions,
68//! items, steps, headings, topics and sentences skip fenced code blocks
69//! (``` or ~~~, CommonMark close rule: same marker, at least as long, no
70//! info string; an unclosed fence runs to the end) and the fence lines
71//! themselves, so a `# comment` or a `- x` inside a code block is not a
72//! heading or an item.
73//!
74//! Definitions used by the checks:
75//! - heading text: the heading line without its `#` run, leading numbering
76//! (`1.`, `2)`), emphasis marks and trailing `:.!?#`, trimmed, whitespace
77//! collapsed, compared case-insensitively.
78//! - word form (topics): lowercase, strip ONE suffix of `ment ing ion es ed
79//! s` (only when 3 or more letters remain; not the `s` of a final `ss`), then one trailing `e` (when 4
80//! or more letters remain). `preparing`, `prepare` and `prepared` agree;
81//! `publishing` and `public` do not. A word whose suffix was stripped also
82//! matches with a final `i` as `y` and with a doubled final consonant
83//! undoubled, so `dry`, `dried` and `drying`, `label`, `labelled` and
84//! `labelling`, `run` and `running` agree (`fill` and `file`, `ski` and
85//! `sky` do not). A topic word ending in `age` or `ages` also matches
86//! without it when 4 letters remain, by a verb form only: the topic
87//! `storage` is covered by `store` or `stored`, `postage` not by `post`
88//! (sc#332). A document word that is a topic word (or its word form) plus
89//! `n`, `al` or `als`, with 4 or more letters before the ending (for `n`
90//! only after `w` or `e`), also covers it: `withdrawn`, `withdrawal` and
91//! `withdrawals` cover `withdraw`, `arrival` covers `arrive`, `grown` and
92//! `taken` cover `grow` and `take`. This is an explicit list of endings, not
93//! a prefix match: `drawer`, `withdrawer` and `withdrawable` do not cover
94//! `withdraw`. The rule also lets close neighbours count: `signal` covers
95//! `sign`, `personal` covers `person`, `linen` covers `line` (sc#353 G2).
96//! Irregular forms (`withdrew` / `withdraw`) do not agree: the check errs
97//! on the side of refusing, unless the goal names the form for that topic,
98//! written into the topic as `withdraw (or withdrew)`.
99//! - sentence: a run of at least two words ended by `.`, `!` or `?` (not
100//! inside a number such as `3.10`); an unfinished last fragment of at
101//! least three words counts as one. List markers are ignored.
102//! - section (for sentence counts): a heading and the prose directly under
103//! it up to the next heading of any level. A heading with no prose of its
104//! own whose next heading is deeper is a container, not a section.
105
106use std::collections::HashSet;
107
108pub use crate::requirements_extract::{analyze, extract, Extraction};
109
110/// What a `MinItems` requirement counts.
111#[derive(Debug, Clone, Copy, PartialEq, Eq)]
112pub enum ItemKind {
113 Items,
114 Steps,
115 Sections,
116 Questions,
117 /// Fenced code blocks (each opening fence line counts one).
118 CodeBlocks,
119}
120
121impl ItemKind {
122 fn noun(self) -> &'static str {
123 match self {
124 ItemKind::Items => "list items",
125 ItemKind::Steps => "numbered steps",
126 ItemKind::Sections => "headings",
127 ItemKind::Questions => "questions",
128 ItemKind::CodeBlocks => "fenced code blocks",
129 }
130 }
131}
132
133/// One measurable requirement on a document.
134#[derive(Debug, Clone, PartialEq, Eq)]
135pub enum Requirement {
136 MinLines(usize),
137 MaxLines(usize),
138 MinWords(usize),
139 MaxWords(usize),
140 MinItems(ItemKind, usize),
141 /// At least this many paragraphs (see [`count_paragraphs`]).
142 MinParagraphs(usize),
143 /// At least `n` lines (outside fenced code, leading whitespace ignored) that
144 /// start with exactly `prefix`, e.g. the `- [ ]` of a checklist.
145 MinPrefixedLines {
146 prefix: String,
147 n: usize,
148 },
149 /// Case-insensitive substrings of the document.
150 RequiredPhrases(Vec<String>),
151 /// Whole words, case-insensitive. A word holding a mark other than an
152 /// apostrophe ("first-aid") must occur whole: no letter or digit right
153 /// before or after it.
154 RequiredWords(Vec<String>),
155 /// Section titles that must each appear as a heading.
156 RequiredHeadings(Vec<String>),
157 /// Topics (each a list of content words) that must each be covered: every
158 /// content word must appear in the prose as a word form. A topic written
159 /// `withdraw (or withdrew, withdrawn)` is also covered by any one of the
160 /// forms the goal named for it.
161 RequiredTopics(Vec<String>),
162 /// Every section holds at least this many sentences.
163 MinSentencesPerSection(usize),
164 /// The whole file is exactly one sentence: its prose (outside fenced code)
165 /// holds one sentence by the sentence rule in the module docs (sc#336).
166 SingleSentence,
167 /// Lines ADDED to the file, measured against the prior file (see the module
168 /// docs). `exact`: exactly `n`, else at least `n`. `prior` is None until
169 /// the caller resolves it ([`Extraction::resolved`]); an unresolved one is unmet.
170 AddedLines {
171 n: usize,
172 exact: bool,
173 prior: Option<String>,
174 },
175 /// The section with this title (None: the last section of the document)
176 /// holds at least `n` words of plain text (prose lines, no code, no headings).
177 SectionMinWords {
178 title: Option<String>,
179 n: usize,
180 },
181 /// Each title is present as a heading of exactly this level (1 to 6).
182 LevelHeadings {
183 level: usize,
184 titles: Vec<String>,
185 },
186 /// The first line of the file is a markdown ATX heading: 1 to 6 `#` at the very start of
187 /// the line, then a space or tab, then title text. `level`: exactly that many `#`;
188 /// None: any of 1 to 6.
189 FirstLineHeading {
190 level: Option<usize>,
191 },
192}
193
194fn quoted(items: &[String]) -> String {
195 items
196 .iter()
197 .map(|x| format!("\"{x}\""))
198 .collect::<Vec<_>>()
199 .join(", ")
200}
201
202impl Requirement {
203 /// Short stable label, as recorded in the receipt.
204 pub fn label(&self) -> String {
205 match self {
206 Requirement::MinLines(n) => format!("at least {n} non-empty lines"),
207 Requirement::MaxLines(n) => format!("at most {n} non-empty lines"),
208 Requirement::MinWords(n) => format!("at least {n} words"),
209 Requirement::MaxWords(n) => format!("at most {n} words"),
210 Requirement::MinItems(k, n) => format!("at least {n} {}", k.noun()),
211 Requirement::MinParagraphs(n) => format!("at least {n} paragraphs"),
212 Requirement::MinPrefixedLines { prefix, n } => {
213 format!("at least {n} lines starting with \"{prefix}\"")
214 }
215 Requirement::RequiredPhrases(p) => format!("the phrase {}", quoted(p)),
216 Requirement::RequiredWords(p) => format!("the words {}", quoted(p)),
217 Requirement::RequiredHeadings(p) => format!("the headings {}", quoted(p)),
218 Requirement::RequiredTopics(p) => format!("the topics {}", quoted(p)),
219 Requirement::MinSentencesPerSection(n) => {
220 format!("at least {n} sentences in every section")
221 }
222 Requirement::SingleSentence => "exactly one sentence".to_string(),
223 Requirement::AddedLines { n, exact, .. } => {
224 if *exact {
225 format!("exactly {n} added non-empty lines")
226 } else {
227 format!("at least {n} added non-empty lines")
228 }
229 }
230 Requirement::SectionMinWords { title, n } => match title {
231 Some(t) => format!("at least {n} words of plain text in the section \"{t}\""),
232 None => format!("at least {n} words of plain text in the last section"),
233 },
234 Requirement::LevelHeadings { level, titles } => {
235 format!("the level-{level} headings {}", quoted(titles))
236 }
237 Requirement::FirstLineHeading { level } => match level {
238 Some(l) => format!(
239 "a level-{l} markdown heading (\"{} \") as the first line",
240 "#".repeat(*l)
241 ),
242 None => "a markdown heading as the first line".to_string(),
243 },
244 }
245 }
246
247 /// None when met, else the unmet requirement with what was found.
248 pub fn check(&self, content: &str) -> Option<String> {
249 let label = self.label();
250 match self {
251 Requirement::MinLines(n) => {
252 let c = non_empty_lines(content);
253 (c < *n).then(|| format!("{label}, found {c}"))
254 }
255 Requirement::MaxLines(n) => {
256 let c = non_empty_lines(content);
257 (c > *n).then(|| format!("{label}, found {c}"))
258 }
259 Requirement::MinWords(n) => {
260 let c = content.split_whitespace().count();
261 (c < *n).then(|| format!("{label}, found {c}"))
262 }
263 Requirement::MaxWords(n) => {
264 let c = content.split_whitespace().count();
265 (c > *n).then(|| format!("{label}, found {c}"))
266 }
267 Requirement::MinItems(k, n) => {
268 let c = count_items(*k, content);
269 (c < *n).then(|| format!("{label}, found {c}"))
270 }
271 Requirement::MinParagraphs(n) => {
272 let c = count_paragraphs(content);
273 (c < *n).then(|| {
274 format!("{label}, found {c} (a paragraph is a block of prose lines; separate paragraphs with a blank line)")
275 })
276 }
277 Requirement::MinPrefixedLines { prefix, n } => {
278 let c = prose_lines(content)
279 .into_iter()
280 .filter(|l| l.trim_start().starts_with(prefix.as_str()))
281 .count();
282 (c < *n).then(|| format!("{label}, found {c}"))
283 }
284 Requirement::RequiredPhrases(p) => {
285 let low = content.to_lowercase();
286 let missing: Vec<String> = p
287 .iter()
288 .filter(|x| !low.contains(&x.to_lowercase()))
289 .cloned()
290 .collect();
291 (!missing.is_empty()).then(|| format!("{label}, missing {}", quoted(&missing)))
292 }
293 Requirement::RequiredWords(p) => {
294 let have: HashSet<String> = words_of(content).into_iter().collect();
295 let low = content.to_lowercase();
296 let missing: Vec<String> = p
297 .iter()
298 .filter(|x| {
299 let x = x.to_lowercase();
300 // A word with a hyphen or other mark ("first-aid") is
301 // matched whole in the text, not as split word parts.
302 if x.chars().all(|c| c.is_alphanumeric() || c == '\'') {
303 !have.contains(&x)
304 } else {
305 !has_whole(&low, &x)
306 }
307 })
308 .cloned()
309 .collect();
310 (!missing.is_empty()).then(|| format!("{label}, missing {}", quoted(&missing)))
311 }
312 Requirement::RequiredHeadings(p) => {
313 let have: HashSet<String> = parse_sections(content)
314 .into_iter()
315 .map(|s| s.title)
316 .collect();
317 let missing: Vec<String> = p
318 .iter()
319 .filter(|x| !have.contains(&normalize_title(x)))
320 .cloned()
321 .collect();
322 (!missing.is_empty()).then(|| {
323 format!(
324 "{label}, missing {} (each must be a markdown heading line)",
325 quoted(&missing)
326 )
327 })
328 }
329 Requirement::RequiredTopics(p) => {
330 let have: HashSet<String> = words_of(&prose_lines(content).join("\n"))
331 .iter()
332 .flat_map(|w| word_keys(w, false))
333 .collect();
334 let has = |w: &String| word_keys(w, true).iter().any(|k| have.contains(k));
335 let covered = |t: &str| {
336 let (topic, forms) = topic_forms(t);
337 content_words(topic).iter().all(has)
338 || forms.iter().any(|f| {
339 let f = words_of(f);
340 !f.is_empty() && f.iter().all(|w| have.contains(&stem(w)))
341 })
342 };
343 let missing: Vec<String> = p.iter().filter(|t| !covered(t)).cloned().collect();
344 (!missing.is_empty()).then(|| {
345 format!(
346 "{label}, not covered: {} (use those words, or their word forms, in the text)",
347 missing.join(", ")
348 )
349 })
350 }
351 Requirement::AddedLines { n, exact, prior } => {
352 let Some(prior) = prior else {
353 return Some(format!(
354 "{label} cannot be measured: the existing file was not provided"
355 ));
356 };
357 let (c, lost) = match added_non_empty_lines(prior, content) {
358 Ok(c) => c,
359 Err(e) => return Some(format!("{label} cannot be measured: {e}")),
360 };
361 if lost > 0 {
362 return Some(format!(
363 "{label}, but {lost} existing non-empty line(s) were changed or removed (every existing line must stay, in order; only trailing whitespace may differ)"
364 ));
365 }
366 let bad = if *exact { c != *n } else { c < *n };
367 bad.then(|| format!("{label}, found {c}"))
368 }
369 Requirement::SectionMinWords { title, n } => {
370 let secs = parse_sections(content);
371 let sec = match title {
372 Some(t) => secs.iter().find(|s| s.title == normalize_title(t)),
373 None => secs.last(),
374 };
375 let Some(sec) = sec else {
376 return Some(format!("{label}, the section was not found"));
377 };
378 let c = sec
379 .body
380 .split_whitespace()
381 .filter(|w| w.chars().any(char::is_alphanumeric))
382 .count();
383 (c < *n).then(|| format!("{label}, found {c}"))
384 }
385 Requirement::LevelHeadings { level, titles } => {
386 let secs = parse_sections(content);
387 let missing: Vec<String> = titles
388 .iter()
389 .filter(|t| {
390 !secs
391 .iter()
392 .any(|s| s.level == *level && s.title == normalize_title(t))
393 })
394 .cloned()
395 .collect();
396 (!missing.is_empty()).then(|| {
397 format!(
398 "{label}, missing {} (each must be a level-{level} markdown heading line)",
399 quoted(&missing)
400 )
401 })
402 }
403 Requirement::FirstLineHeading { level } => {
404 let first = content.split('\n').next().unwrap_or("");
405 let first = first.strip_suffix('\r').unwrap_or(first);
406 let hashes = first.bytes().take_while(|&b| b == b'#').count();
407 let has_title = first[hashes..]
408 .strip_prefix([' ', '\t'])
409 .is_some_and(|t| !t.trim().trim_end_matches('#').trim().is_empty());
410 let ok =
411 (1..=6).contains(&hashes) && level.is_none_or(|l| l == hashes) && has_title;
412 (!ok).then(|| {
413 let shown: String = first.chars().take(60).collect();
414 if shown.is_empty() {
415 format!("{label}, found an empty first line")
416 } else {
417 format!("{label}, found \"{shown}\"")
418 }
419 })
420 }
421 Requirement::MinSentencesPerSection(n) => {
422 let secs = parse_sections(content);
423 if secs.is_empty() {
424 return Some(format!("{label}, found no headings"));
425 }
426 let short: Vec<String> = secs
427 .iter()
428 .filter(|s| !s.container)
429 .filter_map(|s| {
430 let c = count_sentences(&s.body);
431 (c < *n).then(|| format!("{} ({c})", s.raw_title))
432 })
433 .collect();
434 (!short.is_empty()).then(|| {
435 let shown: Vec<String> = short.iter().take(8).cloned().collect();
436 format!("{label}, too few in: {}", shown.join(", "))
437 })
438 }
439 Requirement::SingleSentence => {
440 let c = count_every_sentence(content);
441 (c != 1).then(|| format!("{label}, found {c}"))
442 }
443 }
444 }
445}
446
447fn non_empty_lines(s: &str) -> usize {
448 s.lines().filter(|l| !l.trim().is_empty()).count()
449}
450
451/// Lowercase alphanumeric words (apostrophes kept inside a word).
452/// `needle` occurs in `hay` with no letter or digit right before or after it.
453/// Punctuation is a boundary: "first-aid" is found in "first-aid-kit" and
454/// "(first-aid)", not in "first-aider"; "x-ray" is not found in "box-ray".
455fn has_whole(hay: &str, needle: &str) -> bool {
456 !needle.is_empty()
457 && hay.match_indices(needle).any(|(i, _)| {
458 let before = hay[..i].chars().next_back();
459 let after = hay[i + needle.len()..].chars().next();
460 !before.is_some_and(char::is_alphanumeric) && !after.is_some_and(char::is_alphanumeric)
461 })
462}
463
464fn words_of(s: &str) -> Vec<String> {
465 s.split(|c: char| !(c.is_alphanumeric() || c == '\''))
466 .map(|w| w.trim_matches('\'').to_lowercase())
467 .filter(|w| !w.is_empty())
468 .collect()
469}
470
471const STOPWORDS: [&str; 30] = [
472 "a", "an", "the", "of", "to", "for", "and", "or", "in", "on", "with", "your", "you", "our",
473 "their", "its", "it", "is", "are", "be", "as", "at", "by", "from", "into", "about", "this",
474 "that", "new", "all",
475];
476
477/// The content words of a topic: its words minus the small stop list.
478pub(crate) fn content_words(topic: &str) -> Vec<String> {
479 words_of(topic)
480 .into_iter()
481 .filter(|w| !STOPWORDS.contains(&w.as_str()))
482 .collect()
483}
484
485/// Conservative word form (see the module docs).
486pub(crate) fn stem(w: &str) -> String {
487 stem_parts(w).0
488}
489
490/// The word form and whether a suffix was stripped.
491fn stem_parts(w: &str) -> (String, bool) {
492 let mut s = w.to_lowercase();
493 let mut stripped = false;
494 for suf in ["ment", "ing", "ion", "es", "ed", "s"] {
495 // A final `ss` is not a plural: `dress`, `class`, `mess` (sc#332).
496 if s.len() >= suf.len() + 3 && s.ends_with(suf) && !(suf == "s" && s.ends_with("ss")) {
497 s.truncate(s.len() - suf.len());
498 stripped = true;
499 break;
500 }
501 }
502 if s.len() >= 4 && s.ends_with('e') {
503 s.pop();
504 }
505 (s, stripped)
506}
507
508/// The forms a word may match as (see the module docs): its word form and,
509/// only when a suffix was stripped, that form with a final `i` as `y`
510/// (`dried`: `dry`) or a doubled final consonant undoubled (`labelled`:
511/// `label`). A topic word ending in `age` or `ages` (4 letters left) also
512/// matches a document word that is a verb form of the rest, one that ended
513/// in `e` or lost a suffix (`storage`: `store`, `stored`; not `post` for
514/// `postage`); those keys carry an `age:` mark so nothing else meets them
515/// (sc#332). A document word ending in `als`, `al` or `n` (4 letters left;
516/// for `n` only after `w` or `e`) also gives a `der:` key for the rest, which
517/// meets the topic word or its word form (`withdrawal`, `withdrawn`:
518/// `withdraw`; `arrival`: `arrive`; sc#353 G2). `topic` is true for the
519/// topic's words, false for the document's.
520pub(crate) fn word_keys(w: &str, topic: bool) -> Vec<String> {
521 let (s, stripped) = stem_parts(w);
522 let mut keys = vec![s.clone()];
523 if !topic && (stripped || w.to_lowercase().ends_with('e')) {
524 keys.push(format!("age:{s}"));
525 }
526 if stripped {
527 if let Some(r) = s.strip_suffix('i') {
528 keys.push(format!("{r}y"));
529 }
530 let b = s.as_bytes();
531 if b.len() >= 4 {
532 let (x, y) = (b[b.len() - 1], b[b.len() - 2]);
533 if x == y && x.is_ascii_alphabetic() && !b"aeiou".contains(&x) {
534 keys.push(s[..s.len() - 1].to_string());
535 }
536 }
537 }
538 let low = w.to_lowercase();
539 if !topic {
540 for suf in ["als", "al", "n"] {
541 let base = low
542 .strip_suffix(suf)
543 .filter(|r| r.len() >= 4 && (suf != "n" || r.ends_with('w') || r.ends_with('e')));
544 if let Some(r) = base {
545 keys.push(format!("der:{r}"));
546 break;
547 }
548 }
549 }
550 if topic {
551 keys.push(format!("der:{low}"));
552 keys.push(format!("der:{s}"));
553 for suf in ["ages", "age"] {
554 if let Some(r) = low.strip_suffix(suf).filter(|r| r.len() >= 4) {
555 keys.push(format!("age:{}", stem(r)));
556 break;
557 }
558 }
559 }
560 keys
561}
562
563/// A topic and the extra forms the goal named for it: `withdraw (or withdrew,
564/// withdrawn)` is `("withdraw", ["withdrew", "withdrawn"])`.
565pub(crate) fn topic_forms(t: &str) -> (&str, Vec<&str>) {
566 match t.strip_suffix(')').and_then(|x| x.split_once(" (or ")) {
567 Some((topic, forms)) => (topic, forms.split(',').map(str::trim).collect()),
568 None => (t, Vec::new()),
569 }
570}
571
572/// Heading text as compared: see the module docs.
573pub(crate) fn normalize_title(t: &str) -> String {
574 let t: String = t
575 .chars()
576 .filter(|c| !matches!(c, '*' | '_' | '`'))
577 .collect();
578 let t = t.trim().trim_end_matches('#').trim();
579 let d = t.chars().take_while(|c| c.is_ascii_digit()).count();
580 let t = if d > 0 && matches!(t[d..].chars().next(), Some('.') | Some(')')) {
581 t[d + 1..].trim_start()
582 } else {
583 t
584 };
585 let t = t.trim_end_matches([':', '.', '!', '?']);
586 t.split_whitespace()
587 .collect::<Vec<_>>()
588 .join(" ")
589 .to_lowercase()
590}
591
592struct Section {
593 /// Normalized title (compared) and the title as written (reported).
594 title: String,
595 raw_title: String,
596 /// Prose directly under the heading, headings excluded.
597 body: String,
598 /// No prose of its own and the next heading is deeper.
599 container: bool,
600 /// Heading level, 1 to 6.
601 level: usize,
602}
603
604fn heading_of(t: &str) -> Option<(usize, &str)> {
605 let t = t.trim();
606 let h = t.chars().take_while(|&c| c == '#').count();
607 ((1..=6).contains(&h) && t[h..].starts_with(' ') && !t[h..].trim().is_empty())
608 .then(|| (h, t[h..].trim()))
609}
610
611fn parse_sections(content: &str) -> Vec<Section> {
612 let lines = prose_lines(content);
613 let heads: Vec<(usize, usize, &str)> = lines
614 .iter()
615 .enumerate()
616 .filter_map(|(i, l)| heading_of(l).map(|(lv, t)| (i, lv, t)))
617 .collect();
618 heads
619 .iter()
620 .enumerate()
621 .map(|(k, &(i, lv, t))| {
622 let end = heads.get(k + 1).map_or(lines.len(), |h| h.0);
623 let body = lines[i + 1..end].join("\n");
624 let next_deeper = heads.get(k + 1).is_some_and(|n| n.1 > heads[k].1);
625 Section {
626 title: normalize_title(t),
627 raw_title: t.trim_end_matches('#').trim().to_string(),
628 container: body.trim().is_empty() && next_deeper,
629 level: lv,
630 body,
631 }
632 })
633 .collect()
634}
635
636fn count_sentences(body: &str) -> usize {
637 let mut text = String::new();
638 for l in body.lines() {
639 let mut t = l.trim();
640 if let Some(r) = ["- ", "* ", "+ "].iter().find_map(|m| t.strip_prefix(m)) {
641 t = r;
642 } else {
643 let d = t.chars().take_while(|c| c.is_ascii_digit()).count();
644 if d > 0
645 && matches!(t[d..].chars().next(), Some('.') | Some(')'))
646 && t[d + 1..].starts_with(' ')
647 {
648 t = &t[d + 2..];
649 }
650 }
651 text.push_str(t);
652 text.push(' ');
653 }
654 let chars: Vec<char> = text.chars().collect();
655 let (mut count, mut cur) = (0usize, String::new());
656 let mut i = 0;
657 while i < chars.len() {
658 let c = chars[i];
659 cur.push(c);
660 if matches!(c, '.' | '!' | '?') {
661 let mut j = i + 1;
662 while j < chars.len() && matches!(chars[j], '.' | '!' | '?' | '"' | '\'' | ')') {
663 cur.push(chars[j]);
664 j += 1;
665 }
666 if j >= chars.len() || chars[j].is_whitespace() {
667 if cur.split_whitespace().count() >= 2 {
668 count += 1;
669 }
670 cur.clear();
671 i = j;
672 continue;
673 }
674 i = j;
675 continue;
676 }
677 i += 1;
678 }
679 if cur.split_whitespace().count() >= 3 {
680 count += 1;
681 }
682 count
683}
684
685/// Sentences for `SingleSentence`, counted strictly: every stretch of words a
686/// stop (`.` `!` `?` `…` or a CJK stop) closes, however short ("Bye."), a stop
687/// glued to a capital ("Thanks.Bye."), and any words a line ends without a
688/// stop. Headings and fenced code are not prose. Only "e.g." / "i.e." and a
689/// title before a capitalised name ("Dr. Lee") do not end a sentence, so an
690/// unusual stop can only refuse a correct file, never pass a wrong one.
691fn count_every_sentence(content: &str) -> usize {
692 const STOPS: [char; 7] = [
693 '.', '!', '?', '\u{2026}', '\u{3002}', '\u{FF01}', '\u{FF1F}',
694 ];
695 const CLOSERS: [char; 8] = ['"', '\'', ')', ']', '*', '_', '\u{201D}', '\u{2019}'];
696 const TITLES: [&str; 4] = ["dr", "mr", "mrs", "prof"];
697 let mut count = 0usize;
698 for l in prose_lines(content) {
699 if l.trim_start().starts_with('#') {
700 continue;
701 }
702 let mut pieces: Vec<&str> = Vec::new();
703 for w in l.split_whitespace() {
704 let mut from = 0;
705 let mut it = w.char_indices().peekable();
706 while let Some((k, c)) = it.next() {
707 let cut = match it.peek() {
708 Some(&(_, next)) => {
709 matches!(c, '\u{3002}' | '\u{FF01}' | '\u{FF1F}')
710 || matches!(c, '.' | '!' | '?') && next.is_uppercase()
711 }
712 None => false,
713 };
714 if cut {
715 let at = k + c.len_utf8();
716 pieces.push(&w[from..at]);
717 from = at;
718 }
719 }
720 pieces.push(&w[from..]);
721 }
722 let mut open = false;
723 for (k, p) in pieces.iter().enumerate() {
724 open |= p.chars().any(char::is_alphanumeric);
725 let w = p.trim_end_matches(CLOSERS);
726 if !open || !w.ends_with(STOPS) {
727 continue;
728 }
729 let stem = w
730 .trim_end_matches(STOPS)
731 .trim_start_matches(['(', '"', '\''])
732 .to_lowercase();
733 let title = TITLES.contains(&stem.as_str())
734 && pieces
735 .get(k + 1)
736 .is_some_and(|n| n.starts_with(char::is_uppercase));
737 if !title && !matches!(stem.as_str(), "e.g" | "i.e") {
738 count += 1;
739 open = false;
740 }
741 }
742 count += usize::from(open);
743 }
744 count
745}
746
747fn numbered(t: &str) -> bool {
748 let d = t.chars().take_while(|c| c.is_ascii_digit()).count();
749 d > 0 && matches!(t[d..].chars().next(), Some('.') | Some(')')) && t[d + 1..].starts_with(' ')
750}
751
752/// A CommonMark code-fence line: its marker character (backtick or tilde),
753/// run length (3 or more) and whether an info string follows the run. A
754/// backtick fence whose info string holds a backtick is not a fence.
755fn fence_marker(l: &str) -> Option<(char, usize, bool)> {
756 let t = l.trim_start();
757 let c = t.chars().next().filter(|c| matches!(c, '`' | '~'))?;
758 let n = t.chars().take_while(|&x| x == c).count();
759 if n < 3 {
760 return None;
761 }
762 let info = t[n..].trim();
763 if c == '`' && info.contains('`') {
764 return None;
765 }
766 Some((c, n, !info.is_empty()))
767}
768
769/// The lines of `s` that are NOT inside a fenced code block and are not a
770/// fence marker line. A block opens at a fence line and closes at the first
771/// later line with the same marker character, at least as long a run and no
772/// info string (CommonMark); an unclosed block runs to the end.
773fn prose_lines(s: &str) -> Vec<&str> {
774 let mut open: Option<(char, usize)> = None;
775 let mut out = Vec::new();
776 for l in s.lines() {
777 match (open, fence_marker(l)) {
778 (None, Some((c, n, _))) => open = Some((c, n)),
779 (None, None) => out.push(l),
780 (Some((c, n)), Some((c2, n2, info))) if c2 == c && n2 >= n && !info => open = None,
781 (Some(_), _) => {}
782 }
783 }
784 out
785}
786
787/// Paragraphs: maximal runs of consecutive prose lines, following CommonMark
788/// closely enough that a document cannot reach the count with lines a reader
789/// would not call paragraphs.
790/// - A blank line ends a run (whitespace-only lines are blank).
791/// - Not prose, and the end of a run: a fence and everything inside it, an ATX
792/// heading (`#` to `######`), a thematic break (`---`, `***`, `___`, also
793/// spaced). A run directly above a line of only `=` or only `-` is a setext
794/// heading and does not count.
795/// - A table row (starts with `|`) or an HTML line (starts with `<`) is not
796/// prose when it starts a block; inside a run it continues the run.
797/// - A list item (`- `, `* `, `+ `, a numbered marker, or a bare `1.`) is not
798/// prose, and neither is the text that belongs to it: the following lines up
799/// to a blank line, and after a blank line any line indented 2+ spaces.
800/// - An indented line (a tab or 4+ spaces) continues a run but never starts
801/// one (indented code).
802/// - A line with no letter or digit never starts a run.
803/// - Everything else is prose, including blockquote lines (`> text`).
804pub fn count_paragraphs(content: &str) -> usize {
805 let mut open: Option<(char, usize)> = None;
806 // `in_item`: inside a list item; `blank`: a blank line came since the last line.
807 let (mut count, mut inside, mut in_item, mut blank) = (0, false, false, false);
808 for l in content.lines() {
809 let fence = fence_marker(l);
810 if let Some((c, n)) = open {
811 if matches!(fence, Some((c2, n2, info)) if c2 == c && n2 >= n && !info) {
812 open = None;
813 }
814 continue;
815 }
816 if let Some((c, n, _)) = fence {
817 open = Some((c, n));
818 (inside, in_item) = (false, false);
819 continue;
820 }
821 let t = l.trim();
822 if t.is_empty() {
823 (inside, blank) = (false, true);
824 continue;
825 }
826 let after_blank = std::mem::replace(&mut blank, false);
827 // A run right above a line of only `=` or only `-` is a setext heading.
828 let setext = t.chars().all(|x| x == '=') || t.chars().all(|x| x == '-');
829 if setext && inside {
830 count -= 1;
831 (inside, in_item) = (false, false);
832 continue;
833 }
834 let h = t.chars().take_while(|&c| c == '#').count();
835 let heading = (1..=6).contains(&h) && (t.len() == h || t[h..].starts_with([' ', '\t']));
836 let rule = t.len() >= 3
837 && ['-', '*', '_']
838 .iter()
839 .any(|&c| t.starts_with(c) && t.chars().all(|x| x == c || x == ' '));
840 // HTML and table lines start a block, but do not interrupt a paragraph.
841 let block = !inside && (t.starts_with('|') || t.starts_with('<'));
842 if heading || rule || setext || block {
843 (inside, in_item) = (false, false);
844 continue;
845 }
846 let empty_marker = t.len() >= 2
847 && t.ends_with(['.', ')'])
848 && t[..t.len() - 1].chars().all(|c| c.is_ascii_digit());
849 if t.starts_with("- ")
850 || t.starts_with("* ")
851 || t.starts_with("+ ")
852 || numbered(t)
853 || empty_marker
854 {
855 (inside, in_item) = (false, true);
856 continue;
857 }
858 // Text right under an item, or indented 2+ after a blank line, belongs to it.
859 if in_item && (!after_blank || l.starts_with(" ") || l.starts_with('\t')) {
860 continue;
861 }
862 in_item = false;
863 let indented = l.starts_with('\t') || l.starts_with(" ");
864 if !inside && (indented || !t.chars().any(char::is_alphanumeric)) {
865 continue;
866 }
867 if !inside {
868 count += 1;
869 }
870 inside = true;
871 }
872 count
873}
874
875fn count_items(k: ItemKind, s: &str) -> usize {
876 if k == ItemKind::CodeBlocks {
877 return count_code_blocks(s);
878 }
879 prose_lines(s)
880 .into_iter()
881 .map(str::trim)
882 .filter(|t| match k {
883 ItemKind::Items => {
884 t.starts_with("- ") || t.starts_with("* ") || t.starts_with("+ ") || numbered(t)
885 }
886 ItemKind::Steps => numbered(t),
887 ItemKind::Sections => {
888 let h = t.chars().take_while(|&c| c == '#').count();
889 (1..=6).contains(&h) && t[h..].starts_with(' ') && !t[h..].trim().is_empty()
890 }
891 ItemKind::Questions => t.ends_with('?'),
892 ItemKind::CodeBlocks => false,
893 })
894 .count()
895}
896
897/// Every unmet requirement, each as a short sentence. Empty = all met.
898pub fn unmet(reqs: &[Requirement], content: &str) -> Vec<String> {
899 reqs.iter().filter_map(|r| r.check(content)).collect()
900}
901
902/// The refusal reason a retry prompt carries; None when all are met.
903pub fn refusal_reason(reqs: &[Requirement], content: &str) -> Option<String> {
904 let u = unmet(reqs, content);
905 (!u.is_empty()).then(|| format!("unmet requirement: {}", u.join("; ")))
906}
907
908/// Fenced code blocks: every opening fence line counts one (same fence rule as
909/// `prose_lines`; an unclosed block counts once).
910fn count_code_blocks(s: &str) -> usize {
911 let mut open: Option<(char, usize)> = None;
912 let mut blocks = 0;
913 for l in s.lines() {
914 match (open, fence_marker(l)) {
915 (None, Some((c, n, _))) => {
916 open = Some((c, n));
917 blocks += 1;
918 }
919 (Some((c, n)), Some((c2, n2, info))) if c2 == c && n2 >= n && !info => open = None,
920 _ => {}
921 }
922 }
923 blocks
924}
925
926/// Largest line-pair table the added-line diff will build.
927const DIFF_MAX_CELLS: usize = 25_000_000;
928
929/// (added, lost): `added` counts the non-empty lines of `content` outside the longest
930/// common subsequence with the non-empty lines of `prior` (lines compared with
931/// trailing whitespace ignored); `lost` counts the prior non-empty lines outside it,
932/// i.e. changed or removed ones. For an edit, which keeps every prior line,
933/// this is the number of lines the edit added; for whole replacement bytes it
934/// is the diff against the file they replace.
935pub(crate) fn added_non_empty_lines(prior: &str, content: &str) -> Result<(usize, usize), String> {
936 let a: Vec<&str> = prior
937 .lines()
938 .map(str::trim_end)
939 .filter(|l| !l.trim().is_empty())
940 .collect();
941 let b: Vec<&str> = content
942 .lines()
943 .map(str::trim_end)
944 .filter(|l| !l.trim().is_empty())
945 .collect();
946 if a.len().saturating_mul(b.len()) > DIFF_MAX_CELLS {
947 return Err(format!(
948 "the diff is too large ({} prior lines x {} lines)",
949 a.len(),
950 b.len()
951 ));
952 }
953 // Rolling-row longest common subsequence length.
954 let mut row = vec![0usize; b.len() + 1];
955 for x in &a {
956 let mut diag = 0;
957 for (j, y) in b.iter().enumerate() {
958 let up = row[j + 1];
959 row[j + 1] = if x == y { diag + 1 } else { up.max(row[j]) };
960 diag = up;
961 }
962 }
963 let common = row[b.len()];
964 Ok((b.len() - common, a.len() - common))
965}