Skip to main content

blyte_cli/
research_brief.rs

1use std::path::{Path, PathBuf};
2
3/// The first words of the line blyte puts at the top of a research report that did not pass its checks.
4pub const NOT_VERIFIED_PREFIX: &str = "> **Not verified.**";
5
6/// The sections a research question must have, in order.
7pub const SECTIONS: [&str; 4] = ["Objective", "Start from", "Out of scope", "Answer format"];
8
9/// A question to fill in: a title line and the four sections, each with a one-line prompt.
10pub const TEMPLATE: &str = "\
11# Question: <one line>
12
13## Objective
14<what you need to know, and what you will do with the answer>
15
16## Start from
17<the files or directories to read first, as absolute paths>
18
19## Out of scope
20<what not to read or answer; other questions being asked separately>
21
22## Answer format
23<what the report must contain: a table, paths with line numbers, a recommendation; and a length limit>
24";
25
26/// The sections of `SECTIONS` that `question` has no heading for, in `SECTIONS` order.
27pub fn missing_sections(question: &str) -> Vec<&'static str> {
28    let mut found = [false; SECTIONS.len()];
29    let mut in_fence = false;
30
31    for line in question.lines() {
32        let trimmed = line.trim_start();
33        if trimmed.starts_with("```") {
34            in_fence = !in_fence;
35            continue;
36        }
37        if in_fence {
38            continue;
39        }
40        let hashes = trimmed.bytes().take_while(|&b| b == b'#').count();
41        if !(1..=6).contains(&hashes) {
42            continue;
43        }
44        let after_hashes = &trimmed[hashes..];
45        if !after_hashes.starts_with(' ') {
46            continue;
47        }
48        let heading = after_hashes.trim().trim_end_matches(':').trim();
49        for (i, section) in SECTIONS.iter().enumerate() {
50            if heading
51                .get(..section.len())
52                .is_some_and(|prefix| prefix.eq_ignore_ascii_case(section))
53            {
54                found[i] = true;
55            }
56        }
57    }
58
59    SECTIONS
60        .iter()
61        .enumerate()
62        .filter_map(|(i, &section)| (!found[i]).then_some(section))
63        .collect()
64}
65
66/// Markdown files named in `question` that exist and start with `NOT_VERIFIED_PREFIX`.
67pub fn unverified_inputs(question: &str, base: &Path) -> Vec<PathBuf> {
68    let mut out = Vec::new();
69
70    for piece in question.split(|c: char| {
71        c.is_whitespace()
72            || matches!(
73                c,
74                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
75            )
76    }) {
77        let cleaned = piece.trim_end_matches(['.', ',', ';', ':']);
78        if !cleaned.ends_with(".md") {
79            continue;
80        }
81        let path = Path::new(cleaned);
82        let resolved = if path.is_absolute() {
83            path.to_path_buf()
84        } else {
85            base.join(path)
86        };
87        if out.contains(&resolved) {
88            continue;
89        }
90        if std::fs::read_to_string(&resolved).is_ok_and(|c| c.starts_with(NOT_VERIFIED_PREFIX)) {
91            out.push(resolved);
92        }
93    }
94
95    out
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn the_template_has_every_section() {
104        assert!(missing_sections(TEMPLATE).is_empty());
105    }
106
107    #[test]
108    fn missing_sections_are_named_in_order() {
109        let partial = "## Objective\nfind X\n\n## Answer format\na table\n";
110        assert_eq!(
111            missing_sections(partial),
112            vec!["Start from", "Out of scope"]
113        );
114        assert_eq!(missing_sections(""), SECTIONS.to_vec());
115    }
116
117    #[test]
118    fn headings_match_without_case_and_with_extras() {
119        let q = "\
120### objective:
121find X
122
123# START FROM (files)
124/tmp/a
125
126## Out of scope
127none
128
129#### Answer format: a table
13010 lines
131";
132        assert!(missing_sections(q).is_empty());
133    }
134
135    #[test]
136    fn a_heading_in_a_code_block_does_not_count() {
137        let q = "\
138```markdown
139## Objective
140inside fence
141```
142## Start from
143/tmp/a
144## Out of scope
145none
146## Answer format
147short
148";
149        assert_eq!(missing_sections(q), vec!["Objective"]);
150    }
151
152    #[test]
153    fn a_line_that_is_not_a_heading_does_not_count() {
154        let q = "\
155Objective: find X
156**Objective**
157####### Objective
158##Objective
159";
160        assert_eq!(missing_sections(q), SECTIONS.to_vec());
161    }
162
163    #[test]
164    fn an_unverified_report_is_found() {
165        let dir = tempfile::tempdir().unwrap();
166        let a = dir.path().join("a.report.md");
167        let b = dir.path().join("b.report.md");
168        std::fs::write(&a, "> **Not verified.** This research run ended as\n").unwrap();
169        std::fs::write(&b, "# Findings\nAll good.\n").unwrap();
170
171        let q = format!("Read `{}` and also {}.", a.display(), b.display());
172        assert_eq!(unverified_inputs(&q, dir.path()), vec![a]);
173    }
174
175    #[test]
176    fn a_relative_path_resolves_against_base() {
177        let dir = tempfile::tempdir().unwrap();
178        let notes = dir.path().join("notes");
179        std::fs::create_dir_all(&notes).unwrap();
180        let a = notes.join("a.md");
181        std::fs::write(&a, "> **Not verified.** incomplete\n").unwrap();
182
183        let q = "See notes/a.md for background.";
184        assert_eq!(unverified_inputs(q, dir.path()), vec![a]);
185    }
186
187    #[test]
188    fn a_missing_file_and_a_repeat_are_not_reported_twice() {
189        let dir = tempfile::tempdir().unwrap();
190        let a = dir.path().join("a.md");
191        std::fs::write(&a, "> **Not verified.** incomplete\n").unwrap();
192
193        let q = "Check missing.md, then a.md, and again (a.md).";
194        assert_eq!(unverified_inputs(q, dir.path()), vec![a]);
195    }
196}