Skip to main content

blyte_cli/
research_breadth.rs

1//! Breadth and split checks for `blyte review` on research runs.
2
3use std::collections::{BTreeMap, BTreeSet};
4use std::path::Path;
5
6/// A prompt above this many tokens (fresh plus cached input) counts as large.
7pub const LARGE_PROMPT_TOKENS: u64 = 100_000;
8/// A run with at least this many large-prompt turns is flagged as broad.
9pub const BROAD_TURNS: usize = 10;
10/// Most directories a split suggestion lists.
11pub const MAX_DIRS: usize = 8;
12
13/// (turns with a prompt over `LARGE_PROMPT_TOKENS`, turns in all) from a run report's `turn_usage`.
14/// `Err` names what is wrong when `turn_usage` is missing or an entry lacks `input` or `cached`.
15pub fn large_prompt_turns(report: &serde_json::Value) -> Result<(usize, usize), String> {
16    let Some(turns) = report.get("turn_usage").and_then(|v| v.as_array()) else {
17        return Err("report is missing turn_usage array".to_string());
18    };
19    let mut large = 0usize;
20    for (idx, turn) in turns.iter().enumerate() {
21        let Some(input) = turn.get("input").and_then(|v| v.as_u64()) else {
22            return Err(format!("turn_usage[{idx}] is missing u64 input"));
23        };
24        let Some(cached) = turn.get("cached").and_then(|v| v.as_u64()) else {
25            return Err(format!("turn_usage[{idx}] is missing u64 cached"));
26        };
27        if input.saturating_add(cached) > LARGE_PROMPT_TOKENS {
28            large += 1;
29        }
30    }
31    Ok((large, turns.len()))
32}
33
34/// The flag for a broad run, or `None` when fewer than `BROAD_TURNS` turns were large.
35pub fn breadth_flag(large: usize, total: usize) -> Option<String> {
36    if large < BROAD_TURNS {
37        return None;
38    }
39    Some(format!(
40        "broad research run: {large} of {total} turns had prompts over 100K tokens; narrower questions run faster and fail less"
41    ))
42}
43
44/// Directories the run read files from, with the number of distinct files read in each,
45/// most files first, then by name; at most `MAX_DIRS`.
46pub fn read_dirs(log: &str, root: &Path) -> Vec<(String, usize)> {
47    let mut files = BTreeSet::new();
48    for line in log.lines() {
49        let trimmed = line.trim_start_matches(' ');
50        let Some(after_read) = trimmed.strip_prefix("● read ") else {
51            continue;
52        };
53        let Some((raw_path, _)) = after_read.split_once(" -> ") else {
54            continue;
55        };
56        let path_str = strip_line_range(raw_path);
57        if !path_str.is_empty() {
58            files.insert(path_str.to_string());
59        }
60    }
61
62    let mut counts: BTreeMap<String, usize> = BTreeMap::new();
63    for file in files {
64        let path = Path::new(&file);
65        let Some(parent) = path.parent() else {
66            continue;
67        };
68        let dir = match parent.strip_prefix(root) {
69            Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(),
70            Ok(rel) => rel.to_string_lossy().into_owned(),
71            Err(_) if parent.as_os_str().is_empty() => ".".to_string(),
72            Err(_) => parent.to_string_lossy().into_owned(),
73        };
74        *counts.entry(dir).or_insert(0) += 1;
75    }
76
77    let mut dirs: Vec<(String, usize)> = counts.into_iter().collect();
78    dirs.sort_by(|a, b| b.1.cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
79    dirs.truncate(MAX_DIRS);
80    dirs
81}
82
83fn strip_line_range(s: &str) -> &str {
84    let Some(before_close) = s.strip_suffix(')') else {
85        return s;
86    };
87    let Some((path, range)) = before_close.rsplit_once(" (L") else {
88        return s;
89    };
90    let Some((start, end)) = range.split_once("-L") else {
91        return s;
92    };
93    if !start.is_empty()
94        && start.bytes().all(|b| b.is_ascii_digit())
95        && !end.is_empty()
96        && end.bytes().all(|b| b.is_ascii_digit())
97    {
98        path
99    } else {
100        s
101    }
102}
103
104/// The flag for a run that ran out of budget, or `None` when `dirs` is empty.
105pub fn split_flag(dirs: &[(String, usize)]) -> Option<String> {
106    if dirs.is_empty() {
107        return None;
108    }
109    let listed: Vec<String> = dirs
110        .iter()
111        .map(|(dir, count)| format!("{dir} ({count})"))
112        .collect();
113    Some(format!(
114        "ran out of budget: split the question; files read by directory: {}",
115        listed.join(", ")
116    ))
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122    use serde_json::json;
123
124    #[test]
125    fn large_turns_are_counted() {
126        let report = json!({
127            "turn_usage": [
128                {"input": 60000, "cached": 50000, "output": 100},
129                {"input": 100000, "cached": 0, "output": 100},
130                {"input": 1, "cached": 100000, "output": 100}
131            ]
132        });
133        assert_eq!(large_prompt_turns(&report), Ok((2, 3)));
134    }
135
136    #[test]
137    fn a_report_without_turn_usage_is_an_error() {
138        let empty = json!({});
139        let err = large_prompt_turns(&empty).unwrap_err();
140        assert!(err.contains("turn_usage"), "unexpected error: {err}");
141
142        let missing_cached = json!({
143            "turn_usage": [
144                {"input": 1000}
145            ]
146        });
147        let err = large_prompt_turns(&missing_cached).unwrap_err();
148        assert!(err.contains("cached"), "unexpected error: {err}");
149    }
150
151    #[test]
152    fn the_breadth_flag_needs_ten_large_turns() {
153        assert_eq!(breadth_flag(9, 40), None);
154        assert_eq!(
155            breadth_flag(10, 40),
156            Some(
157                "broad research run: 10 of 40 turns had prompts over 100K tokens; narrower questions run faster and fail less"
158                    .to_string()
159            )
160        );
161    }
162
163    #[test]
164    fn read_dirs_groups_distinct_files() {
165        let log = "\
166  ● read /r/crates/a/src/x.rs -> 800 lines
167  ● read /r/crates/a/src/x.rs (L1-L800) -> 800 lines
168● read /r/crates/a/src/y.rs -> 200 lines
169  ● read /r/docs/u.md -> 50 lines
170  ● read /r/README.md -> 30 lines
171  ● read /other/z.rs -> 10 lines
172  ● bash ls -> exit 0
173  ● read /r/broken
174";
175        let dirs = read_dirs(log, Path::new("/r"));
176        assert_eq!(
177            dirs,
178            vec![
179                ("crates/a/src".to_string(), 2),
180                (".".to_string(), 1),
181                ("/other".to_string(), 1),
182                ("docs".to_string(), 1),
183            ]
184        );
185    }
186
187    #[test]
188    fn read_dirs_lists_at_most_eight() {
189        let mut log = String::new();
190        for i in 0..10 {
191            log.push_str(&format!("● read /r/dir{i}/file.rs -> 10 lines\n"));
192        }
193        let dirs = read_dirs(&log, Path::new("/r"));
194        assert_eq!(dirs.len(), 8);
195    }
196
197    #[test]
198    fn the_split_flag_lists_directories() {
199        let dirs = vec![("crates/a/src".to_string(), 12), ("docs".to_string(), 3)];
200        assert_eq!(
201            split_flag(&dirs),
202            Some(
203                "ran out of budget: split the question; files read by directory: crates/a/src (12), docs (3)"
204                    .to_string()
205            )
206        );
207        assert_eq!(split_flag(&[]), None);
208    }
209}