1use std::collections::{HashMap, HashSet};
23use std::path::{Path, PathBuf};
24use std::sync::OnceLock;
25
26use regex::Regex;
27
28pub const MAX_PROBLEMS: usize = 40;
30
31const SLACK: usize = 5;
33
34const EXAMPLES_PER_BLOCK: usize = 3;
36
37const MAX_SUFFIX_MATCHES: usize = 20;
39
40const MAX_EVIDENCE_LINES: usize = 120;
42
43const MAX_EVIDENCE_BLOCKS: usize = 4;
45
46#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
48pub struct Claim {
49 pub id: usize,
50 pub line: usize,
51 pub text: String,
52 pub quoted: Option<String>,
53 pub evidence: Vec<Evidence>,
54}
55
56#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
58pub struct Evidence {
59 pub path: String,
60 pub start: usize,
61 pub end: usize,
62 pub lines: String,
63}
64
65pub struct Sources<'a> {
67 pub workspace: &'a Path,
69 pub read_roots: &'a [PathBuf],
71 pub listing: &'a [PathBuf],
74 pub read: &'a dyn Fn(&Path) -> Result<String, String>,
76}
77
78struct Citation {
79 path: String,
80 ranges: Vec<(usize, usize)>,
82 named: bool,
84}
85
86enum Resolved {
87 Files(Vec<(PathBuf, Vec<String>)>),
88 Skip,
90 Missing(String),
91}
92
93fn citation_re() -> &'static Regex {
94 static RE: OnceLock<Regex> = OnceLock::new();
95 RE.get_or_init(|| {
96 Regex::new(&format!(
97 r"((?:[\w./~-]*\.[A-Za-z][A-Za-z0-9_]*)|(?:[\w./~-]*/)?(?:{BARE_NAMES})):(\d+(?:-\d+)?(?:, ?\d+(?:-\d+)?)*)"
98 ))
99 .expect("citation regex")
100 })
101}
102
103const BARE_NAMES: &str =
105 "Makefile|Dockerfile|Containerfile|Justfile|Gemfile|Rakefile|Procfile|Jenkinsfile|Vagrantfile";
106
107const CODE_EXTENSIONS: &[&str] = &[
110 "py", "pyi", "rs", "go", "ts", "tsx", "js", "jsx", "mjs", "java", "kt", "scala", "rb", "php",
111 "cs", "c", "h", "cc", "cpp", "hpp", "swift", "lua", "sh", "tf", "hcl", "sql", "yaml", "yml",
112 "toml", "json", "ipynb",
113];
114
115const NOT_QUOTE_TAGS: &[&str] = &[
117 "proposed",
118 "diff",
119 "patch",
120 "bash",
121 "sh",
122 "shell",
123 "zsh",
124 "console",
125 "terminal",
126 "text",
127 "txt",
128 "plain",
129 "plaintext",
130 "output",
131 "log",
132 "csv",
133 "tsv",
134 "mermaid",
135 "markdown",
136 "md",
137];
138
139fn path_re() -> &'static Regex {
141 static RE: OnceLock<Regex> = OnceLock::new();
142 RE.get_or_init(|| {
143 Regex::new(&format!(
144 r"(?:^|[\s`(\[])((?:[\w.~-]+/)*(?:[\w.-]*\.[A-Za-z][A-Za-z0-9_]*|{BARE_NAMES}))(?:$|[\s`):,\]])"
145 ))
146 .expect("path regex")
147 })
148}
149
150fn prose_path_re() -> &'static Regex {
152 static RE: OnceLock<Regex> = OnceLock::new();
153 RE.get_or_init(|| {
154 Regex::new(&format!(
155 r"(?:^|[\s`(\[])(/?(?:[\w.~-]+/)+(?:[\w.-]*\.[A-Za-z][A-Za-z0-9_]*|{BARE_NAMES}))(?:$|[\s`):,\].;])"
156 ))
157 .expect("prose path regex")
158 })
159}
160
161fn missing_or_new_re() -> &'static Regex {
162 static RE: OnceLock<Regex> = OnceLock::new();
163 RE.get_or_init(|| {
164 Regex::new(
165 r"(?i)\b(?:new|create|creates|created|add|adds|added|adding|propose|proposed|missing|deleted|removed|renamed|absent)\b|does not exist|do not exist|no such file",
166 )
167 .expect("missing or new regex")
168 })
169}
170
171pub fn paths(text: &str) -> impl Iterator<Item = &str> {
173 let re = prose_path_re();
174 let mut pos = 0;
175 std::iter::from_fn(move || {
176 let c = re.captures_at(text, pos)?;
177 let m = c.get(1).expect("path group");
178 pos = m.end();
179 Some(m.as_str())
180 })
181}
182
183fn prose_change_ref_re() -> &'static Regex {
184 static RE: OnceLock<Regex> = OnceLock::new();
185 RE.get_or_init(|| {
186 Regex::new(
187 r"(?:^|[\s(\[])#(\d{2,6})\b|(?i:\b(?:pr|pull\s+request|issue))\s+#?(\d{1,6})\b|/(?:pull|issues)/(\d{1,6})\b",
188 )
189 .expect("prose change ref regex")
190 })
191}
192
193fn change_ref_re() -> &'static Regex {
194 static RE: OnceLock<Regex> = OnceLock::new();
195 RE.get_or_init(|| {
196 Regex::new(
197 r#"(?m)(?:^|[\s(\[])#(\d{2,6})\b|(?i:\b(?:pr|pull\s+request|issue))\s+#?(\d{1,6})\b|/(?:pull|issues)/(\d{1,6})\b|"number":\s*(\d{1,6})\b|^(\d{1,6})\t"#,
198 )
199 .expect("change ref regex")
200 })
201}
202
203pub fn change_refs(text: &str) -> impl Iterator<Item = &str> {
205 change_ref_re().captures_iter(text).map(|c| {
206 (1..=5)
207 .find_map(|i| c.get(i))
208 .expect("change ref group")
209 .as_str()
210 })
211}
212
213fn lines_re() -> &'static Regex {
214 static RE: OnceLock<Regex> = OnceLock::new();
215 RE.get_or_init(|| Regex::new(r"(?i)\blines?\s+(\d+)(?:\s*[-–]\s*(\d+))?").expect("lines regex"))
216}
217
218fn numbered_re() -> &'static Regex {
219 static RE: OnceLock<Regex> = OnceLock::new();
220 RE.get_or_init(|| {
221 Regex::new(r"^\s*(\d+)(?:\t|: |:$|\s*\|\s?|\s{2,}|\s*→)(.*)$").expect("numbered regex")
222 })
223}
224
225fn citations(line: &str) -> Vec<Citation> {
226 let mut out = Vec::new();
227 for caps in citation_re().captures_iter(line) {
228 let m = caps.get(0).expect("whole match");
229 let path = caps[1].trim_start_matches("./").to_string();
230 let before = &line[..m.start()];
231 if before.ends_with(':') || before.ends_with(|c: char| c.is_alphanumeric() || c == '_') {
233 continue;
234 }
235 if path.is_empty() || path.starts_with('~') || path.starts_with("..") {
236 continue;
237 }
238 let mut ranges = Vec::new();
239 for part in caps[2].split(',') {
240 let part = part.trim();
241 let (a, b) = match part.split_once('-') {
242 Some((a, b)) => (a.parse().unwrap_or(0), b.parse().unwrap_or(0)),
243 None => {
244 let n = part.parse().unwrap_or(0);
245 (n, n)
246 }
247 };
248 if a > 0 {
249 ranges.push((a, b.max(a)));
250 }
251 }
252 if !ranges.is_empty() {
253 out.push(Citation {
254 path,
255 ranges,
256 named: false,
257 });
258 }
259 }
260 out
261}
262
263fn normalize(s: &str) -> String {
264 s.split_whitespace().collect::<Vec<_>>().join(" ")
265}
266
267fn is_elision(line: &str) -> bool {
269 let t = line
270 .trim()
271 .trim_start_matches(['#', '/', '-', '*', ';'])
272 .trim_end_matches("*/")
273 .trim();
274 t.starts_with("...") || t.starts_with('…') || t.starts_with("[...]") || t.starts_with("[…]")
275}
276
277struct Resolver<'a> {
278 src: &'a Sources<'a>,
279 cache: HashMap<String, Resolved>,
280}
281
282impl<'a> Resolver<'a> {
283 fn lines_of(&self, p: &Path) -> Option<Vec<String>> {
284 (self.src.read)(p)
285 .ok()
286 .map(|t| t.lines().map(str::to_string).collect())
287 }
288
289 fn resolve(&mut self, path: &str) -> &Resolved {
290 if !self.cache.contains_key(path) {
291 let r = self.lookup(path);
292 self.cache.insert(path.to_string(), r);
293 }
294 &self.cache[path]
295 }
296
297 fn lookup(&self, path: &str) -> Resolved {
298 let p = Path::new(path);
299 if p.is_absolute() {
300 return match (self.src.read)(p) {
301 Ok(t) => Resolved::Files(vec![(
302 p.to_path_buf(),
303 t.lines().map(str::to_string).collect(),
304 )]),
305 Err(e) => Resolved::Missing(format!("cannot read {path}: {e}")),
306 };
307 }
308 let bases = std::iter::once(self.src.workspace)
310 .chain(self.src.read_roots.iter().map(|r| r.as_path()))
311 .chain(self.src.read_roots.iter().filter_map(|r| r.parent()));
312 for base in bases {
313 let candidate = base.join(p);
314 if let Some(lines) = self.lines_of(&candidate) {
315 return Resolved::Files(vec![(candidate, lines)]);
316 }
317 }
318 let suffix = format!("/{path}");
319 let mut hits: Vec<&PathBuf> = self
320 .src
321 .listing
322 .iter()
323 .filter(|f| f.to_string_lossy().ends_with(&suffix))
324 .collect();
325 hits.dedup();
326 if !hits.is_empty() && hits.len() <= MAX_SUFFIX_MATCHES {
327 let files: Vec<_> = hits
328 .into_iter()
329 .filter_map(|f| self.lines_of(f).map(|l| (f.clone(), l)))
330 .collect();
331 if !files.is_empty() {
332 return Resolved::Files(files);
333 }
334 } else if !hits.is_empty() {
335 return Resolved::Skip;
336 }
337 let ext = path.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase());
338 if path.contains('/') || ext.is_some_and(|e| CODE_EXTENSIONS.contains(&e.as_str())) {
339 Resolved::Missing(format!("no such file: {path}"))
340 } else {
341 Resolved::Skip
342 }
343 }
344}
345
346fn excerpt(s: &str) -> String {
347 let t = s.trim();
348 if t.chars().count() > 100 {
349 format!("{}…", t.chars().take(100).collect::<String>())
350 } else {
351 t.to_string()
352 }
353}
354
355fn cite_text(c: &Citation) -> String {
356 let ranges: Vec<String> = c
357 .ranges
358 .iter()
359 .map(|&(a, b)| {
360 if a == b {
361 a.to_string()
362 } else {
363 format!("{a}-{b}")
364 }
365 })
366 .collect();
367 if ranges.is_empty() {
368 c.path.clone()
369 } else {
370 format!("{}:{}", c.path, ranges.join(","))
371 }
372}
373
374fn find_line(lines: &[String], text: &str) -> Option<usize> {
376 lines
377 .iter()
378 .position(|l| normalize(l) == text)
379 .map(|i| i + 1)
380}
381
382fn matches_line(file_line: &str, quoted: &str) -> bool {
385 let f = normalize(file_line);
386 if f == quoted || (quoted.chars().count() >= 12 && f.contains(quoted)) {
387 return true;
388 }
389 if !quoted.contains("...") && !quoted.contains('…') {
390 return false;
391 }
392 let mut rest = f.as_str();
393 for part in quoted.split('…').flat_map(|p| p.split("...")) {
394 let part = part.trim();
395 if part.is_empty() {
396 continue;
397 }
398 match rest.find(part) {
399 Some(at) => rest = &rest[at + part.len()..],
400 None => return false,
401 }
402 }
403 true
404}
405
406fn check_quoted_line(
408 files: &[(PathBuf, Vec<String>)],
409 windows: &[(usize, usize)],
410 raw: &str,
411) -> Option<String> {
412 let whole = normalize(raw);
413 let numbered = numbered_re()
414 .captures(raw)
415 .and_then(|c| Some((c[1].parse::<usize>().ok()?, normalize(&c[2]))));
416 let near = |lines: &[String], text: &str| {
417 windows.iter().any(|&(lo, hi)| {
418 lines
419 .iter()
420 .enumerate()
421 .skip(lo - 1)
422 .take(hi + 1 - lo)
423 .any(|(_, l)| matches_line(l, text))
424 })
425 };
426 for (_, lines) in files {
427 if let Some((n, text)) = &numbered {
428 if lines
429 .get(n.wrapping_sub(1))
430 .is_some_and(|l| matches_line(l, text))
431 {
432 return None;
433 }
434 }
435 if near(lines, &whole) {
436 return None;
437 }
438 }
439 let (_, lines) = &files[0];
440 match &numbered {
441 Some((n, text)) => {
442 let actual = match lines.get(n.wrapping_sub(1)) {
443 Some(l) => format!("line {n} is `{}`", excerpt(l)),
444 None => format!("the file has {} lines", lines.len()),
445 };
446 let elsewhere = find_line(lines, text)
447 .map(|at| format!("; the quoted text is at line {at}"))
448 .unwrap_or_else(|| "; the quoted text is not in the file".to_string());
449 Some(format!("quoted `{}`: {actual}{elsewhere}", excerpt(raw)))
450 }
451 None => {
452 let elsewhere = find_line(lines, &whole)
453 .map(|at| format!("it is at line {at}, outside the cited lines"))
454 .unwrap_or_else(|| "it is not in the file".to_string());
455 Some(format!("quoted `{}`: {elsewhere}", excerpt(raw)))
456 }
457 }
458}
459
460pub fn check(report: &str, src: &Sources<'_>) -> Vec<String> {
462 let mut resolver = Resolver {
463 src,
464 cache: HashMap::new(),
465 };
466 let mut problems = Vec::new();
467 let mut last_text: Option<(usize, String)> = None;
468 let mut last_cite: Option<Citation> = None;
469 let lines: Vec<&str> = report.lines().collect();
470 let mut i = 0;
471 while i < lines.len() {
472 let line = lines[i];
473 let trimmed = line.trim_start();
474 let fence = if trimmed.starts_with("```") {
475 "```"
476 } else if trimmed.starts_with("~~~") {
477 "~~~"
478 } else {
479 ""
480 };
481 if fence.is_empty() {
482 if !line.trim().is_empty() {
483 check_prose(&mut resolver, i + 1, line, &mut problems);
484 if let Some(c) = citations(line).pop() {
485 last_cite = Some(c);
486 }
487 last_text = Some((i + 1, line.to_string()));
488 }
489 i += 1;
490 continue;
491 }
492 let marker_len = trimmed
493 .chars()
494 .take_while(|&c| c == fence.chars().next().unwrap())
495 .count();
496 let info = trimmed[marker_len..].trim().to_lowercase();
497 let close = fence.chars().next().unwrap().to_string().repeat(marker_len);
498 let start = i + 1;
499 let mut end = start;
500 while end < lines.len() && !lines[end].trim_start().starts_with(&close) {
501 end += 1;
502 }
503 let mut body = &lines[start..end.min(lines.len())];
504 let lang = info.split_whitespace().next().unwrap_or("");
505 let lead_in = last_text.take().map(|(_, t)| t);
506 let mut anchor = lead_in.as_deref().and_then(|t| citations(t).pop());
507 let first = body.iter().position(|l| !l.trim().is_empty());
509 if let Some(f) = first {
510 let head = body[f].trim_start();
511 if ["#", "//", "--", "/*"].iter().any(|c| head.starts_with(c)) {
512 if let Some(c) = citations(head).pop() {
513 anchor = Some(c);
514 body = &body[f + 1..];
515 }
516 }
517 }
518 if anchor.is_none() {
519 anchor = lead_in.as_deref().and_then(named_path);
520 }
521 if anchor.is_none() {
523 if let (Some(t), Some(prev)) = (lead_in.as_deref(), &last_cite) {
524 if let Some(ranges) = lead_in_lines(t) {
525 anchor = Some(Citation {
526 path: prev.path.clone(),
527 ranges,
528 named: true,
529 });
530 }
531 }
532 }
533 let numbered = mostly_numbered(body);
534 let anchor = match anchor {
537 Some(c) => Some(c),
538 None if numbered => last_cite.take(),
539 None => None,
540 };
541 let is_quote = !NOT_QUOTE_TAGS.contains(&lang) && (!lang.is_empty() || numbered);
542 match &anchor {
543 Some(cite) if !matches!(lang, "diff" | "patch" | "proposed") => {
544 check_block(&mut resolver, start, cite, body, &mut problems)
545 }
546 None if is_quote && body.iter().any(|l| !l.trim().is_empty()) => {
547 let tag = if lang.is_empty() { "numbered" } else { lang };
548 problems.push(format!(
549 "report.md:{start}: {tag} code block with no citation: put `path:N-M` on the \
550 line before it if it is quoted from a file, or tag it ```proposed if it is \
551 not in the repository"
552 ));
553 }
554 _ => {}
555 }
556 if anchor.is_some() {
557 last_cite = anchor;
558 }
559 i = end + 1;
560 }
561 problems
562}
563
564fn named_path(line: &str) -> Option<Citation> {
567 let path = path_re()
568 .captures_iter(line)
569 .map(|c| c[1].trim_start_matches("./").to_string())
570 .filter(|p| !p.starts_with('~') && !p.starts_with(".."))
571 .filter(|p| p.contains('/') || line.contains(&format!("`{p}`")) || p.ends_with("file"))
572 .last()?;
573 let ranges = lead_in_lines(line).unwrap_or_default();
574 Some(Citation {
575 path,
576 ranges,
577 named: true,
578 })
579}
580
581fn lead_in_lines(line: &str) -> Option<Vec<(usize, usize)>> {
583 let c = lines_re().captures(line)?;
584 let a: usize = c[1].parse().ok()?;
585 let b = c.get(2).and_then(|m| m.as_str().parse().ok()).unwrap_or(a);
586 (a > 0).then_some(vec![(a, b.max(a))])
587}
588
589fn mostly_numbered(body: &[&str]) -> bool {
591 let lines: Vec<&&str> = body
592 .iter()
593 .filter(|l| !l.trim().is_empty() && !is_elision(l))
594 .collect();
595 let numbered = lines.iter().filter(|l| numbered_re().is_match(l)).count();
596 !lines.is_empty() && numbered * 2 >= lines.len()
597}
598
599fn check_prose(resolver: &mut Resolver<'_>, at: usize, line: &str, problems: &mut Vec<String>) {
600 for cite in citations(line) {
601 match resolver.resolve(&cite.path) {
602 Resolved::Skip => {}
603 Resolved::Missing(why) => {
604 problems.push(format!("report.md:{at}: {}: {why}", cite_text(&cite)))
605 }
606 Resolved::Files(files) => {
607 let last = cite.ranges.iter().map(|&(_, b)| b).max().unwrap_or(0);
608 if files.iter().all(|(_, l)| last > l.len()) {
609 let (p, l) = &files[0];
610 problems.push(format!(
611 "report.md:{at}: {}: line {last} is past the end of {} ({} lines)",
612 cite_text(&cite),
613 p.display(),
614 l.len()
615 ));
616 }
617 }
618 }
619 }
620}
621
622fn check_block(
623 resolver: &mut Resolver<'_>,
624 start: usize,
625 cite: &Citation,
626 body: &[&str],
627 problems: &mut Vec<String>,
628) {
629 let files = match resolver.resolve(&cite.path) {
630 Resolved::Files(f) => f,
631 Resolved::Missing(why) if cite.named => {
633 let why = why.clone();
634 problems.push(format!(
635 "report.md:{start}: code block quoting {}: {why}; tag the block ```proposed if \
636 it is a file you propose",
637 cite.path
638 ));
639 return;
640 }
641 _ => return,
642 };
643 let quoted: Vec<&str> = body
644 .iter()
645 .copied()
646 .filter(|l| !l.trim().is_empty() && !is_elision(l))
647 .collect();
648 if quoted.is_empty() {
649 return;
650 }
651 let windows: Vec<(usize, usize)> = if cite.ranges.is_empty() {
653 vec![(1, usize::MAX / 2)]
654 } else {
655 cite.ranges
656 .iter()
657 .map(|&(a, b)| {
658 (
659 a.saturating_sub(SLACK).max(1),
660 b.max(a + body.len()) + SLACK,
661 )
662 })
663 .collect()
664 };
665 let bad: Vec<String> = quoted
666 .iter()
667 .filter_map(|l| check_quoted_line(files, &windows, l))
668 .collect();
669 if bad.is_empty() {
670 return;
671 }
672 let mut msg = format!(
673 "report.md:{start}: code block quoting {}: {} of {} lines do not match the file",
674 cite_text(cite),
675 bad.len(),
676 quoted.len()
677 );
678 for b in bad.iter().take(EXAMPLES_PER_BLOCK) {
679 msg.push_str("\n ");
680 msg.push_str(b);
681 }
682 problems.push(msg);
683}
684
685pub fn render(problems: &[String]) -> String {
687 let mut out = format!(
688 "report.md quote check: {} problem(s). A code block right after a `path:line` citation \
689 must be copied from that file, and cited lines must exist.\n",
690 problems.len()
691 );
692 for p in problems.iter().take(MAX_PROBLEMS) {
693 out.push_str("- ");
694 out.push_str(p);
695 out.push('\n');
696 }
697 if problems.len() > MAX_PROBLEMS {
698 out.push_str(&format!(
699 "- ... and {} more\n",
700 problems.len() - MAX_PROBLEMS
701 ));
702 }
703 out.push_str(
704 "Re-read each cited file with the read tool and quote it exactly, correct the line \
705 numbers, or remove the claim. Mark code you propose rather than quote as ```proposed.",
706 );
707 out
708}
709
710fn is_list_item(trimmed: &str) -> bool {
711 if trimmed.starts_with("- ")
712 || trimmed.starts_with("* ")
713 || trimmed.starts_with("+ ")
714 || trimmed.starts_with("-\t")
715 || trimmed.starts_with("*\t")
716 || trimmed.starts_with("+\t")
717 {
718 return true;
719 }
720 let digits = trimmed.bytes().take_while(|b| b.is_ascii_digit()).count();
721 if digits > 0 {
722 let rest = &trimmed[digits..];
723 if rest.starts_with(". ")
724 || rest.starts_with(") ")
725 || rest.starts_with(".\t")
726 || rest.starts_with(")\t")
727 {
728 return true;
729 }
730 }
731 false
732}
733
734fn flush_claim_unit(
735 unit_lines: &mut Vec<(usize, &str)>,
736 resolver: &mut Resolver<'_>,
737 last_path: &mut Option<String>,
738 out: &mut Vec<Claim>,
739 attach_quote_to_last: &mut bool,
740) {
741 if unit_lines.is_empty() {
742 return;
743 }
744 let first_line = unit_lines[0].0;
745 let text = unit_lines
746 .iter()
747 .map(|(_, l)| *l)
748 .collect::<Vec<_>>()
749 .join("\n")
750 .trim()
751 .to_string();
752 unit_lines.clear();
753 if text.is_empty() {
754 return;
755 }
756
757 let mut cites = Vec::new();
758 for line in text.lines() {
759 let line_cites = citations(line);
760 if !line_cites.is_empty() {
761 cites.extend(line_cites);
762 } else if let Some(c) = named_path(line) {
763 if !c.ranges.is_empty() || cites.is_empty() {
764 cites.push(c);
765 }
766 }
767 }
768 if cites.is_empty() {
769 if let Some(c) = named_path(&text) {
770 cites.push(c);
771 } else if let (Some(ranges), Some(prev)) = (lead_in_lines(&text), last_path.as_deref()) {
772 cites.push(Citation {
773 path: prev.to_string(),
774 ranges,
775 named: true,
776 });
777 }
778 }
779
780 let mut evidence = Vec::new();
781 for cite in cites {
782 let Resolved::Files(files) = resolver.resolve(&cite.path) else {
783 continue;
784 };
785 let Some((_, file_lines)) = files.first() else {
786 continue;
787 };
788 let total = file_lines.len();
789 if total == 0 {
790 continue;
791 }
792 *last_path = Some(cite.path.clone());
793 let ranges = if cite.ranges.is_empty() {
794 vec![(1, total)]
795 } else {
796 cite.ranges
797 };
798 for (a, b) in ranges {
799 if evidence.len() >= MAX_EVIDENCE_BLOCKS {
800 break;
801 }
802 let cite_start = a.clamp(1, total);
803 let cite_end = b.max(a).clamp(1, total);
804 let mut start = cite_start.saturating_sub(SLACK).max(1);
805 let mut end = (cite_end + SLACK).min(total);
806 while end - start + 1 > MAX_EVIDENCE_LINES {
807 if end > cite_end {
808 end -= 1;
809 } else if start < cite_start {
810 start += 1;
811 } else {
812 end = start + MAX_EVIDENCE_LINES - 1;
813 break;
814 }
815 }
816 let lines = (start..=end)
817 .map(|n| format!("{n}\t{}", file_lines[n - 1]))
818 .collect::<Vec<_>>()
819 .join("\n");
820 evidence.push(Evidence {
821 path: cite.path.clone(),
822 start,
823 end,
824 lines,
825 });
826 }
827 if evidence.len() >= MAX_EVIDENCE_BLOCKS {
828 break;
829 }
830 }
831
832 if !evidence.is_empty() {
833 let id = out.len() + 1;
834 out.push(Claim {
835 id,
836 line: first_line,
837 text,
838 quoted: None,
839 evidence,
840 });
841 *attach_quote_to_last = true;
842 } else {
843 *attach_quote_to_last = false;
844 }
845}
846
847pub fn claims(report: &str, src: &Sources<'_>) -> Vec<Claim> {
851 let mut resolver = Resolver {
852 src,
853 cache: HashMap::new(),
854 };
855 let mut out = Vec::new();
856 let mut unit_lines: Vec<(usize, &str)> = Vec::new();
857 let mut last_path: Option<String> = None;
858 let mut attach_quote_to_last = false;
859
860 let lines: Vec<&str> = report.lines().collect();
861 let mut i = 0;
862 while i < lines.len() {
863 let line = lines[i];
864 let trimmed = line.trim_start();
865 let fence = if trimmed.starts_with("```") {
866 "```"
867 } else if trimmed.starts_with("~~~") {
868 "~~~"
869 } else {
870 ""
871 };
872 if !fence.is_empty() {
873 flush_claim_unit(
874 &mut unit_lines,
875 &mut resolver,
876 &mut last_path,
877 &mut out,
878 &mut attach_quote_to_last,
879 );
880 let marker_len = trimmed
881 .chars()
882 .take_while(|&c| c == fence.chars().next().unwrap())
883 .count();
884 let close = fence.chars().next().unwrap().to_string().repeat(marker_len);
885 let start = i + 1;
886 let mut end = start;
887 while end < lines.len() && !lines[end].trim_start().starts_with(&close) {
888 end += 1;
889 }
890 let body = &lines[start..end.min(lines.len())];
891 if attach_quote_to_last {
892 if let Some(last_claim) = out.last_mut() {
893 last_claim.quoted = Some(body.join("\n"));
894 }
895 attach_quote_to_last = false;
896 }
897 i = end + 1;
898 continue;
899 }
900
901 if trimmed.is_empty() {
902 flush_claim_unit(
903 &mut unit_lines,
904 &mut resolver,
905 &mut last_path,
906 &mut out,
907 &mut attach_quote_to_last,
908 );
909 i += 1;
910 continue;
911 }
912
913 if trimmed.starts_with('#') {
914 flush_claim_unit(
915 &mut unit_lines,
916 &mut resolver,
917 &mut last_path,
918 &mut out,
919 &mut attach_quote_to_last,
920 );
921 attach_quote_to_last = false;
922 i += 1;
923 continue;
924 }
925
926 if is_list_item(trimmed) {
927 flush_claim_unit(
928 &mut unit_lines,
929 &mut resolver,
930 &mut last_path,
931 &mut out,
932 &mut attach_quote_to_last,
933 );
934 unit_lines.push((i + 1, line));
935 i += 1;
936 continue;
937 }
938
939 unit_lines.push((i + 1, line));
940 i += 1;
941 }
942
943 flush_claim_unit(
944 &mut unit_lines,
945 &mut resolver,
946 &mut last_path,
947 &mut out,
948 &mut attach_quote_to_last,
949 );
950 out
951}
952
953fn is_commit_like(tok: &str) -> bool {
956 (7..=40).contains(&tok.len())
957 && tok
958 .bytes()
959 .all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
960 && tok.bytes().any(|b| b.is_ascii_digit())
961 && tok.bytes().any(|b| b.is_ascii_lowercase())
962}
963
964pub fn identifiers(text: &str) -> impl Iterator<Item = &str> {
968 text.split(|c: char| !c.is_ascii_alphanumeric() && c != '_')
969 .filter(|s| {
970 s.len() >= 3
971 && (s
972 .as_bytes()
973 .first()
974 .is_some_and(|b| b.is_ascii_alphabetic() || *b == b'_')
975 || is_commit_like(s))
976 })
977 .chain(paths(text))
978 .chain(change_refs(text))
979}
980
981fn has_inner_capital(s: &str) -> bool {
982 let mut saw_lower = false;
983 for b in s.bytes() {
984 if b.is_ascii_lowercase() {
985 saw_lower = true;
986 } else if b.is_ascii_uppercase() && saw_lower {
987 return true;
988 }
989 }
990 false
991}
992
993fn inline_spans(mut s: &str) -> Vec<&str> {
994 let mut out = Vec::new();
995 while let Some(pos) = s.find('`') {
996 let after = &s[pos..];
997 let ticks = after.bytes().take_while(|&b| b == b'`').count();
998 let needle = &after[..ticks];
999 let rest = &after[ticks..];
1000 if let Some(end) = rest.find(needle) {
1001 out.push(&rest[..end]);
1002 s = &rest[end + ticks..];
1003 } else {
1004 break;
1005 }
1006 }
1007 out
1008}
1009
1010fn strip_inline_spans(mut s: &str) -> String {
1011 let mut out = String::with_capacity(s.len());
1012 while let Some(pos) = s.find('`') {
1013 out.push_str(&s[..pos]);
1014 let after = &s[pos..];
1015 let ticks = after.bytes().take_while(|&b| b == b'`').count();
1016 let needle = &after[..ticks];
1017 let rest = &after[ticks..];
1018 if let Some(end) = rest.find(needle) {
1019 out.push('`');
1020 s = &rest[end + ticks..];
1021 } else {
1022 out.push_str(after);
1023 return out;
1024 }
1025 }
1026 out.push_str(s);
1027 out
1028}
1029
1030pub fn unseen_names(report: &str, seen: &HashSet<String>) -> Vec<String> {
1032 let mut problems = Vec::new();
1033 let mut reported: HashSet<&str> = HashSet::new();
1034 let lines: Vec<&str> = report.lines().collect();
1035 let mut i = 0;
1036 while i < lines.len() {
1037 let line = lines[i];
1038 let trimmed = line.trim_start();
1039 let fence = if trimmed.starts_with("```") {
1040 "```"
1041 } else if trimmed.starts_with("~~~") {
1042 "~~~"
1043 } else {
1044 ""
1045 };
1046 if !fence.is_empty() {
1047 let marker_len = trimmed
1048 .chars()
1049 .take_while(|&c| c == fence.chars().next().unwrap())
1050 .count();
1051 let close = fence.chars().next().unwrap().to_string().repeat(marker_len);
1052 let mut end = i + 1;
1053 while end < lines.len() && !lines[end].trim_start().starts_with(&close) {
1054 end += 1;
1055 }
1056 i = end + 1;
1057 continue;
1058 }
1059 let line_no = i + 1;
1060 for span in inline_spans(line) {
1061 let bytes = span.as_bytes();
1062 for tok in identifiers(span) {
1063 if tok.starts_with(|c: char| c.is_ascii_digit()) || tok.contains('/') {
1064 continue;
1065 }
1066 let end = (tok.as_ptr() as usize - span.as_ptr() as usize) + tok.len();
1067 let followed_by_paren = bytes.get(end) == Some(&b'(');
1068 if (tok.contains('_') || has_inner_capital(tok) || followed_by_paren)
1069 && !seen.contains(tok)
1070 && reported.insert(tok)
1071 {
1072 problems.push(format!(
1073 "report.md:{line_no}: `{tok}` does not appear in anything this run read \
1074 (the task, files or command output); name only what you have seen"
1075 ));
1076 }
1077 }
1078 }
1079 i += 1;
1080 }
1081 problems.extend(unseen_commit_ids(&lines, seen));
1082 problems.extend(unseen_change_refs(report, seen));
1083 problems
1084}
1085
1086pub fn unseen_change_refs(report: &str, seen: &HashSet<String>) -> Vec<String> {
1089 let mut problems = Vec::new();
1090 let mut reported: HashSet<String> = HashSet::new();
1091 let lines: Vec<&str> = report.lines().collect();
1092 let mut i = 0;
1093 while i < lines.len() {
1094 let line = lines[i];
1095 let trimmed = line.trim_start();
1096 let fence = if trimmed.starts_with("```") {
1097 "```"
1098 } else if trimmed.starts_with("~~~") {
1099 "~~~"
1100 } else {
1101 ""
1102 };
1103 if !fence.is_empty() {
1104 let marker_len = trimmed
1105 .chars()
1106 .take_while(|&c| c == fence.chars().next().unwrap())
1107 .count();
1108 let close = fence.chars().next().unwrap().to_string().repeat(marker_len);
1109 let mut end = i + 1;
1110 while end < lines.len() && !lines[end].trim_start().starts_with(&close) {
1111 end += 1;
1112 }
1113 i = end + 1;
1114 continue;
1115 }
1116 let line_no = i + 1;
1117 let prose = strip_inline_spans(line);
1118 for caps in prose_change_ref_re().captures_iter(&prose) {
1119 let n = (1..=3)
1120 .find_map(|g| caps.get(g))
1121 .expect("change ref group")
1122 .as_str();
1123 if !seen.contains(n) && reported.insert(n.to_string()) {
1124 problems.push(format!(
1125 "report.md:{line_no}: #{n} does not appear in anything this run read \
1126 (the task, files or command output); cite only pull requests and issues you \
1127 have seen"
1128 ));
1129 }
1130 }
1131 i += 1;
1132 }
1133 problems
1134}
1135
1136fn unseen_commit_ids(lines: &[&str], seen: &HashSet<String>) -> Vec<String> {
1138 let mut problems = Vec::new();
1139 let mut reported: HashSet<&str> = HashSet::new();
1140 let mut fence: Option<(char, usize)> = None;
1141 for (idx, &line) in lines.iter().enumerate() {
1142 let trimmed = line.trim_start();
1143 let marker = trimmed.chars().next().filter(|c| *c == '`' || *c == '~');
1144 let run = marker.map_or(0, |m| trimmed.chars().take_while(|&c| c == m).count());
1145 if let Some((m, n)) = fence {
1146 if marker == Some(m) && run >= n {
1147 fence = None;
1148 }
1149 continue;
1150 }
1151 if run >= 3 {
1152 fence = marker.map(|m| (m, run));
1153 continue;
1154 }
1155 for tok in identifiers(line) {
1156 if !is_commit_like(tok) {
1157 continue;
1158 }
1159 let seen_id = seen
1160 .iter()
1161 .any(|s| is_commit_like(s) && (s.starts_with(tok) || tok.starts_with(s.as_str())));
1162 if !seen_id && reported.insert(tok) {
1163 problems.push(format!(
1164 "report.md:{}: commit id `{tok}` does not appear in anything this run read \
1165 (the task, files or command output); cite only commit ids you have seen",
1166 idx + 1
1167 ));
1168 }
1169 }
1170 }
1171 problems
1172}
1173
1174fn opens_proposed_diff_or_patch(line: &str) -> bool {
1175 let trimmed = line.trim_start();
1176 let fence_char = if trimmed.starts_with("```") {
1177 '`'
1178 } else if trimmed.starts_with("~~~") {
1179 '~'
1180 } else {
1181 return false;
1182 };
1183 let marker_len = trimmed.chars().take_while(|&c| c == fence_char).count();
1184 let info = trimmed[marker_len..].trim();
1185 let lang = info.split_whitespace().next().unwrap_or("");
1186 lang.eq_ignore_ascii_case("proposed")
1187 || lang.eq_ignore_ascii_case("diff")
1188 || lang.eq_ignore_ascii_case("patch")
1189}
1190
1191pub fn unseen_paths(report: &str, src: &Sources<'_>, seen: &HashSet<String>) -> Vec<String> {
1193 let mut resolver = Resolver {
1194 src,
1195 cache: HashMap::new(),
1196 };
1197 let mut problems = Vec::new();
1198 let mut reported: HashSet<String> = HashSet::new();
1199 let lines: Vec<&str> = report.lines().collect();
1200 let mut i = 0;
1201 while i < lines.len() {
1202 let line = lines[i];
1203 let trimmed = line.trim_start();
1204 let fence = if trimmed.starts_with("```") {
1205 "```"
1206 } else if trimmed.starts_with("~~~") {
1207 "~~~"
1208 } else {
1209 ""
1210 };
1211 if !fence.is_empty() {
1212 let marker_len = trimmed
1213 .chars()
1214 .take_while(|&c| c == fence.chars().next().unwrap())
1215 .count();
1216 let close = fence.chars().next().unwrap().to_string().repeat(marker_len);
1217 let mut end = i + 1;
1218 while end < lines.len() && !lines[end].trim_start().starts_with(&close) {
1219 end += 1;
1220 }
1221 i = end + 1;
1222 continue;
1223 }
1224 let line_no = i + 1;
1225 let line_cites = citations(line);
1226 let said_missing_or_new = missing_or_new_re().is_match(line);
1227 let next_is_proposed = lines[i + 1..]
1228 .iter()
1229 .find(|l| !l.trim().is_empty())
1230 .is_some_and(|l| opens_proposed_diff_or_patch(l));
1231 for raw_p in paths(line) {
1232 let p = raw_p.strip_prefix("./").unwrap_or(raw_p);
1233 let file_name = p.rsplit_once('/').map_or(p, |(_, f)| f);
1234 let ext = file_name
1235 .rsplit_once('.')
1236 .map(|(_, e)| e.to_ascii_lowercase());
1237 let is_code_ext = ext.is_some_and(|e| CODE_EXTENSIONS.contains(&e.as_str()));
1238 let is_bare_name = BARE_NAMES.split('|').any(|b| b == file_name);
1239 if !is_code_ext && !is_bare_name {
1240 continue;
1241 }
1242 if p.starts_with('~') || p.starts_with("..") {
1243 continue;
1244 }
1245 if line_cites.iter().any(|c| c.path == p) {
1246 continue;
1247 }
1248 if said_missing_or_new || next_is_proposed {
1249 continue;
1250 }
1251 if matches!(resolver.resolve(p), Resolved::Files(_) | Resolved::Skip) {
1252 continue;
1253 }
1254 let slash_p = format!("/{p}");
1255 let was_seen = seen.iter().any(|s| {
1256 s.contains('/')
1257 && (s == p || s.ends_with(&slash_p) || p.ends_with(&format!("/{s}")))
1258 });
1259 if was_seen {
1260 continue;
1261 }
1262 if reported.insert(p.to_string()) {
1263 problems.push(format!(
1264 "report.md:{line_no}: `{p}`: no such file, and the path does not appear in \
1265 anything this run read (the task, files or command output); name only files \
1266 you have seen, or say on the same line that the file is new or missing"
1267 ));
1268 }
1269 }
1270 i += 1;
1271 }
1272 problems
1273}