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