1use crate::conscience::{self, Challenge};
12
13pub const MARKERS: [&str; 2] = ["#borg-asked", "#borg-skip"];
17
18pub const THRESHOLD: f64 = 8.0;
23
24pub fn turn(context: &str) -> &str {
29 let mut start = 0;
30 let mut at = 0;
31 let mut lines = context.split_inclusive('\n').peekable();
32 while let Some(line) = lines.next() {
33 at += line.len();
34 let live = lines.peek().is_some_and(|next| next.starts_with("#borg-live "));
35 if MARKERS.iter().any(|m| line.starts_with(m)) && !live {
36 start = at;
37 }
38 }
39 &context[start..]
40}
41
42pub fn score(challenges: &[Challenge], context: &str) -> f64 {
45 let n = challenges.len() as f64;
46 let top = conscience::rank(challenges, &conscience::work_text(turn(context))).first().map(|(s, _)| *s).unwrap_or(0.0);
47 let idf_max = (1.0 + (n - 0.5) / 1.5).ln();
48 if idf_max > 0.0 { top / idf_max } else { 0.0 }
49}
50
51pub fn threshold() -> Option<f64> {
54 match std::env::var("BORG_PREFILTER") {
55 Ok(v) if v.trim().eq_ignore_ascii_case("off") => None,
56 Ok(v) => Some(v.trim().parse().unwrap_or(THRESHOLD)),
57 Err(_) => Some(THRESHOLD),
58 }
59}
60
61pub fn skip(challenges: &[Challenge], context: &str) -> Option<f64> {
63 let threshold = threshold()?;
64 let s = score(challenges, context);
65 (s < threshold).then_some(s)
66}
67
68pub fn edits_gate() -> bool {
72 std::env::var("BORG_STOP_GATE").is_ok_and(|v| v.trim().eq_ignore_ascii_case("edits"))
73}
74
75const READ_ONLY: &[&str] = &[
77 "ls", "cat", "head", "tail", "less", "more", "grep", "egrep", "rg", "ag", "find", "fd", "tree", "wc", "file", "stat", "du", "df", "pwd", "echo", "printf",
78 "which", "type", "whereis", "env", "printenv", "date", "whoami", "id", "uname", "ps", "jq", "yq", "sort", "uniq", "cut", "tr", "diff", "cmp", "column",
79 "nl", "realpath", "dirname", "basename", "sed", "awk", "cd", "true",
80];
81
82const GIT_READ: &[&str] = &["status", "log", "diff", "show", "blame", "branch", "rev-parse", "ls-files", "grep", "remote", "describe", "shortlog"];
84
85pub fn changes(tool: &str, input: &serde_json::Value) -> bool {
89 let tool = tool.to_ascii_lowercase();
90 if ["edit", "write", "multiedit", "notebookedit"].contains(&tool.as_str()) {
91 return true;
92 }
93 if tool != "bash" {
94 return false;
95 }
96 let cmd = input.get("command").and_then(serde_json::Value::as_str).unwrap_or_default();
97 let cmd = ["2>&1", "&>/dev/null", "2>/dev/null", ">/dev/null", "> /dev/null"].iter().fold(cmd.to_string(), |c, r| c.replace(r, " "));
98 if cmd.contains('>') {
99 return true;
100 }
101 cmd.split(['\n', ';', '|', '&', '(', ')', '`']).map(str::trim).filter(|p| !p.is_empty()).any(|part| {
102 let words: Vec<&str> = part.split_whitespace().skip_while(|w| w.contains('=') && !w.starts_with('-')).collect();
103 let Some(&prog) = words.first() else { return false };
104 let prog = prog.rsplit('/').next().unwrap_or(prog);
105 match prog {
106 "git" => {
107 let mut rest = words[1..].iter();
109 let sub = loop {
110 match rest.next() {
111 Some(&("-C" | "-c")) => {
112 rest.next();
113 }
114 Some(w) if w.starts_with('-') => {}
115 other => break other.copied(),
116 }
117 };
118 let mutating_flag = rest.any(|w| ["-d", "-D", "-m", "-M", "--delete", "add", "remove", "rename", "set-url"].contains(w));
119 !sub.is_some_and(|s| GIT_READ.contains(&s)) || mutating_flag
120 }
121 "sed" => words.iter().any(|w| w.starts_with("-i") || *w == "--in-place"),
122 "find" => words.iter().any(|w| ["-delete", "-exec", "-execdir", "-ok"].contains(w)),
123 p => !READ_ONLY.contains(&p),
124 }
125 })
126}
127
128#[derive(Debug, Default, PartialEq)]
133pub struct Tally {
134 pub skipped: usize,
135 pub asked: usize,
136 pub cost: f64,
137 pub rounds: usize,
140 pub questions: usize,
141 pub block_chars: usize,
142 pub free: usize,
143 pub free_lessons: usize,
144 pub free_chars: usize,
145 pub judge_calls: usize,
148 pub judged: usize,
149 pub judge_resolved: usize,
150 pub judge_chars: usize,
151 pub live_checks: usize,
153 pub live_cost: f64,
154 pub live_lessons: usize,
155}
156
157pub fn tally(state: &std::path::Path) -> Tally {
158 let mut t = Tally::default();
159 for e in std::fs::read_dir(state).into_iter().flatten().flatten() {
160 if e.path().extension().is_some_and(|x| x == "cost") {
161 for line in std::fs::read_to_string(e.path()).unwrap_or_default().lines() {
162 let field = |k: &str| line.split_whitespace().find_map(|w| w.strip_prefix(k)).and_then(|v| v.parse::<usize>().ok()).unwrap_or(0);
163 if line.starts_with("block ") {
164 t.rounds += 1;
165 t.questions += field("questions=");
166 t.block_chars += field("chars=");
167 } else if line.starts_with("free ") {
168 t.free += 1;
169 t.free_lessons += field("lessons=");
170 t.free_chars += field("chars=");
171 } else if line.starts_with("live ") {
172 t.live_checks += 1;
173 t.live_lessons += field("lessons=");
174 t.live_cost += line.split_whitespace().find_map(|w| w.strip_prefix("usd=")).and_then(|v| v.parse::<f64>().ok()).unwrap_or(0.0);
175 } else if line.starts_with("judge ") {
176 t.judge_calls += 1;
177 t.judged += field("pending=");
178 t.judge_resolved += field("resolved=");
179 t.judge_chars += field("chars=");
180 }
181 }
182 continue;
183 }
184 if e.path().extension().is_none_or(|x| x != "ctx") {
185 continue;
186 }
187 for line in std::fs::read_to_string(e.path()).unwrap_or_default().lines() {
188 if line.starts_with("#borg-skip") {
189 t.skipped += 1;
190 } else if let Some(c) = line.strip_prefix("#borg-predict-cost ") {
191 t.asked += 1;
192 t.cost += c.trim().parse::<f64>().unwrap_or(0.0);
193 }
194 }
195 }
196 t.asked = t.asked.saturating_sub(t.live_checks);
197 t.cost = (t.cost - t.live_cost).max(0.0);
198 t
199}
200
201pub fn features(challenges: &[Challenge], context: &str) -> serde_json::Value {
203 let t = conscience::work_text(turn(context));
204 let t = t.as_ref();
205 let ranked = conscience::rank(challenges, t);
206 let shortlist = conscience::select(challenges, &conscience::work_text(context), 20);
207 let q: std::collections::HashSet<String> = conscience::tokens(t).into_iter().collect();
208 serde_json::json!({
209 "score": score(challenges, context),
210 "turn_scores": ranked.iter().take(20).map(|(s, _)| *s).collect::<Vec<_>>(),
211 "turn_ids": ranked.iter().take(20).map(|(_, c)| c.id.clone()).collect::<Vec<_>>(),
212 "qtokens": q.len(),
213 "turn_chars": t.len(),
214 "n": challenges.len(),
215 "shortlist": shortlist.iter().map(|c| c.id.clone()).collect::<Vec<_>>(),
216 })
217}
218
219#[cfg(test)]
220mod tests {
221 use super::*;
222
223 fn lesson(id: &str, q: &str) -> Challenge {
224 Challenge { id: id.into(), question: q.into(), ..Default::default() }
225 }
226
227 #[test]
228 fn a_turn_starts_after_the_last_stop_marker() {
229 let ctx = "first prompt\nsrc/a.rs\n#borg-predict-cost 0.05\n#borg-asked L1\nsecond prompt\n#borg-skip 1.20\nthird\nsrc/b.rs\n";
230 assert_eq!(turn(ctx), "third\nsrc/b.rs\n");
231 assert_eq!(turn("only\n"), "only\n");
232 assert_eq!(turn("x\n#borg-asked \n"), "");
233 assert_eq!(turn("a\n#borg-asked L1\nb\n#borg-asked L2\n#borg-live L2 ms=5\nc\n"), "b\n#borg-asked L2\n#borg-live L2 ms=5\nc\n");
235 }
236
237 #[test]
238 fn scores_this_turn_only_and_normalises_by_store_size() {
239 let ls: Vec<Challenge> = (0..30)
240 .map(|i| lesson(&format!("L{i}"), &format!("unrelated filler words number{i} about gardening")))
241 .chain([lesson("lock", "Did I hold the websocket send lock across the await on the delivery queue?")])
242 .collect();
243 let hit = "plan: hold the websocket send lock while awaiting the delivery queue";
244 assert!(score(&ls, hit) > score(&ls, "ok, thanks"), "a turn about a lesson scores above chat");
245 let earlier = format!("{hit}\n#borg-asked lock\nok, thanks\n");
246 assert_eq!(score(&ls, &earlier), score(&ls, "ok, thanks"), "earlier turns do not count");
247 assert_eq!(score(&[], hit), 0.0);
248 assert_eq!(score(&ls[..1], "nothing matches here"), 0.0, "a store of one has idf 0 or no match");
249 }
250
251 #[test]
254 fn bookkeeping_lines_score_nothing() {
255 let ls: Vec<Challenge> = (0..30)
256 .map(|i| lesson(&format!("L{i}"), &format!("unrelated filler words number{i} about gardening")))
257 .chain([lesson("lock", "Did I hold the websocket send lock across the await on the delivery queue?")])
258 .collect();
259 let marked = "ok, thanks\n#borg-answer hold the websocket send lock while awaiting the delivery queue\n#borg-p lock=0.9\n";
260 assert_eq!(score(&ls, marked), score(&ls, "ok, thanks\n"));
261 assert!(features(&ls, marked)["turn_ids"].as_array().unwrap().is_empty(), "{}", features(&ls, marked));
262 }
263
264 #[test]
268 fn adding_words_to_a_turn_never_lowers_its_score() {
269 let ls: Vec<Challenge> = (0..20)
270 .map(|i| lesson(&format!("L{i}"), &format!("question {i} about retries, timeouts and module{i} wiring")))
271 .chain([lesson("lock", "Did I hold the websocket send lock across the await on the delivery queue?")])
272 .collect();
273 let brief = "plan: hold the websocket send lock while awaiting the delivery queue";
274 let base = score(&ls, brief);
275 assert!(base > 0.0);
276 let mut turn = brief.to_string();
277 for extra in ["ok", "retries retries retries", "module3 wiring timeouts", "lock lock lock lock", "unrelated gardening words"] {
278 turn.push('\n');
279 turn.push_str(extra);
280 let s = score(&ls, &turn);
281 assert!(s >= base - 1e-12, "{extra:?} lowered the score: {s} < {base}");
282 }
283 }
284
285 #[test]
286 fn edit_tools_and_state_changing_commands_count_as_changes() {
287 let bash = |c: &str| changes("Bash", &serde_json::json!({"command": c}));
288 assert!(changes("Edit", &serde_json::json!({})) && changes("write", &serde_json::json!({})) && changes("MultiEdit", &serde_json::json!({})));
289 assert!(!changes("Read", &serde_json::json!({"file_path": "/x"})) && !changes("Grep", &serde_json::json!({})));
290 for read in [
291 "ls -la src",
292 "cat a.rs | head -20 2>&1",
293 "rg -n foo crates/ > /dev/null",
294 "git status && git log --oneline -5",
295 "git -C /repo diff HEAD~1",
296 "sed -n 1,80p main.rs",
297 "find . -name '*.rs' | wc -l",
298 "cd /x && grep -r foo .",
299 "LANG=C sort a | uniq -c",
300 ] {
301 assert!(!bash(read), "{read}");
302 }
303 for change in [
304 "cargo build",
305 "rm -rf target",
306 "echo x > notes.md",
307 "git commit -m x",
308 "git -C /repo checkout -b y",
309 "git branch -D old",
310 "sed -i s/a/b/ f.rs",
311 "find . -name '*.tmp' -delete",
312 "ls && mv a b",
313 "python3 script.py",
314 ] {
315 assert!(bash(change), "{change}");
316 }
317 assert!(!bash(""));
318 }
319
320 #[test]
321 fn tallies_skips_and_model_calls_across_sessions() {
322 let d = std::env::temp_dir().join(format!("borg-prefilter-tally-{}", std::process::id()));
323 let _ = std::fs::remove_dir_all(&d);
324 std::fs::create_dir_all(&d).unwrap();
325 std::fs::write(d.join("a.ctx"), "p\n#borg-skip 1.50\nq\n#borg-predict-cost 0.0500\n#borg-asked L1\n").unwrap();
326 std::fs::write(d.join("b.ctx"), "#borg-skip 0.00\n#borg-predict-cost 0.0250\n#borg-asked \n").unwrap();
327 std::fs::write(d.join("b.prompts"), "#borg-skip in a prompt file does not count\n").unwrap();
328 std::fs::write(d.join("a.cost"), "free event=UserPromptSubmit lessons=3 chars=900\nblock questions=7 chars=2100\nblock questions=2 chars=600\n")
329 .unwrap();
330 std::fs::write(d.join("b.cost"), "free event=PostToolUse lessons=1 chars=300\njudge call=2 pending=3 resolved=2 chars=4100\n").unwrap();
331 let t = tally(&d);
332 assert_eq!((t.skipped, t.asked), (2, 2));
333 assert_eq!((t.live_checks, t.live_lessons), (0, 0));
334 assert_eq!((t.rounds, t.questions, t.block_chars), (2, 9, 2700));
335 assert_eq!((t.free, t.free_lessons, t.free_chars), (2, 4, 1200));
336 assert_eq!((t.judge_calls, t.judged, t.judge_resolved, t.judge_chars), (1, 3, 2, 4100));
337 assert!((t.cost - 0.075).abs() < 1e-9);
338 std::fs::write(d.join("c.ctx"), "p\n#borg-predict-cost 0.0400\n#borg-live-skip 1.00\n").unwrap();
340 std::fs::write(d.join("c.cost"), "live usd=0.0400 lessons=8\n").unwrap();
341 let t = tally(&d);
342 assert_eq!((t.skipped, t.asked, t.live_checks, t.live_lessons), (2, 2, 1, 8));
343 assert!((t.cost - 0.075).abs() < 1e-9 && (t.live_cost - 0.04).abs() < 1e-9);
344 assert_eq!(tally(&d.join("absent")), Tally::default());
345 }
346}