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