Skip to main content

borg/
prefilter.rs

1//! The free gate before the Stop model call (internal evaluation "stop-prefilter", not published).
2//!
3//! The consequence model (predict.rs) costs one model call (~6 s, ~$0.03-0.07) per turn end, and
4//! most turn ends touch no lesson at all. So word matching first scores this turn alone: the best
5//! BM25 match of its prompt, touches and final message against the lessons, divided by the largest
6//! idf a word can have in this store (scores grow with the number of lessons; this keeps one
7//! threshold valid for a store of 10 or of 100). Below the threshold the hook asks nothing and
8//! costs 0 tokens; at or above it, predict decides as before. Calibrated on the graded preempt
9//! cases and the engineer's real turn ends (eval/preempt/stop_prefilter.py).
10
11use crate::conscience::{self, Challenge};
12
13/// State-file markers that close a turn (hook.rs appends one at every Stop that reaches the conscience).
14/// Never a selection line (`#borg-select`, `#borg-pf`, `#borg-placebo`, `#borg-routed`): those come
15/// mid-turn too and close nothing. Protocol.
16pub const MARKERS: [&str; 2] = ["#borg-asked", "#borg-skip"];
17
18/// Learned (evaluation-decided): pre-registered in the internal evaluation "stop-prefilter" (not
19/// published): 0.9 × the lowest score of any labelled checkpoint with a relevant lesson in its shortlist
20/// (9.28), rounded down.
21pub const THRESHOLD: f64 = 8.0;
22
23/// What the state file gained since the last Stop: this turn's prompt and touches (plus the drone's
24/// final message, appended by the caller). A live check's ask (`#borg-asked` followed by `#borg-live`,
25/// main.rs `ask_live`) comes during the turn and does not end it.
26pub 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
40/// The gate's score of the state file + final message: this turn's best lesson match over the
41/// store's largest idf. 0 for an empty store or a turn that matches nothing.
42pub 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
49/// The threshold in force: `BORG_PREFILTER` = "off" (None: always ask the model), a number, or unset
50/// (`THRESHOLD`). An unparsable value keeps the default.
51pub 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
59/// Some(score) when the Stop hook should skip the model call for this state file + final message.
60pub 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
66/// `BORG_STOP_GATE=edits` (internal evaluation "whole-store", not published): instead of the lexical score, the model is asked
67/// whenever this turn changed something (an edit tool, or a shell command that is not read-only), and a
68/// read-only or talk-only turn skips. Default (unset or anything else): the lexical gate above.
69pub fn edits_gate() -> bool {
70    std::env::var("BORG_STOP_GATE").is_ok_and(|v| v.trim().eq_ignore_ascii_case("edits"))
71}
72
73/// Programs that only read (with the exceptions in `changes`). Anything else counts as a change.
74const 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
80/// git subcommands that only read.
81const GIT_READ: &[&str] = &["status", "log", "diff", "show", "blame", "branch", "rev-parse", "ls-files", "grep", "remote", "describe", "shortlog"];
82
83/// Whether a tool call changes state: an edit tool (Edit, Write, MultiEdit, NotebookEdit), or a Bash
84/// command any part of which is not read-only (`READ_ONLY`, read-only git), redirects output into a
85/// file, or edits in place (`sed -i`, `find -delete/-exec`). Other tools (Read, Grep, Glob, ...) read.
86pub 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                // The subcommand: the first word after `git` that is not an option (or `-C`/`-c`'s value).
106                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/// What the gate did in a store's session state (`borg status`): turn ends skipped at 0 tokens, turn
127/// ends that asked the model, and the model's cost as logged by `#borg-predict-cost` (USD for Claude,
128/// tokens for `codex:<model>`). Live checks (live.rs) log `#borg-predict-cost` too, and a `live` cost
129/// line each: they are counted apart (`live_checks`, `live_cost`), not as turn ends.
130#[derive(Debug, Default, PartialEq)]
131pub struct Tally {
132    pub skipped: usize,
133    pub asked: usize,
134    pub cost: f64,
135    /// R3b (main.rs `log_cost`): Stop blocks (extra rounds), the questions in them and their size;
136    /// free deliveries (context on a hook that forces no round), their lessons and size.
137    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    /// R1 (main.rs `record_verdicts`): model calls that also judged pending lessons, the lessons judged,
144    /// those that got a final verdict, and the characters the judging added to those prompts.
145    pub judge_calls: usize,
146    pub judged: usize,
147    pub judge_resolved: usize,
148    pub judge_chars: usize,
149    /// Live mode (main.rs `live_check`): model calls during the turn, their cost and lessons shown.
150    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
199/// The gate's score and what an eval needs beside it (eval/preempt/stop_prefilter.py).
200pub 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        // A live check's ask is part of the turn, not its end.
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");
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    /// A bookkeeping line in the turn (`#borg-answer` carries the drone's last proposal, `#borg-p` lesson
250    /// ids) is not the turn's work: it scores nothing.
251    #[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    /// Why the held-out result was fixed in advance (internal evaluation "stop-prefilter", not published): query words are a set
263    /// and every BM25 term is positive, so adding words to a turn never lowers its score. A checkpoint
264    /// whose brief alone reaches the threshold passes whatever the drone adds to it.
265    #[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        // A live check logs its call like a turn end's, and a `live` cost line: it is counted apart.
337        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}