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. Kept by dated decision (2026-10-31): 9 corrections followed a turn it skipped in a
21/// team store, none about an existing lesson.
22pub const THRESHOLD: f64 = 8.0;
23
24/// What the state file gained since the last Stop: this turn's prompt and touches (plus the drone's
25/// final message, appended by the caller). A live check's ask (`#borg-asked` followed by `#borg-live`:
26/// before 0.7.6, or one such ask handed over after the upgrade, hook.rs `LEGACY_ASK`) came during the
27/// turn and does not end it.
28pub 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
42/// The gate's score of the state file + final message: this turn's best lesson match over the
43/// store's largest idf. 0 for an empty store or a turn that matches nothing.
44pub 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
51/// The threshold in force: `BORG_PREFILTER` = "off" (None: always ask the model), a number, or unset
52/// (`THRESHOLD`). An unparsable value keeps the default.
53pub 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
61/// Some(score) when the Stop hook should skip the model call for this state file + final message.
62pub 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
68/// `BORG_STOP_GATE=edits` (internal evaluation "whole-store", not published): instead of the lexical score, the model is asked
69/// whenever this turn changed something (an edit tool, or a shell command that is not read-only), and a
70/// read-only or talk-only turn skips. Default (unset or anything else): the lexical gate above.
71pub fn edits_gate() -> bool {
72    std::env::var("BORG_STOP_GATE").is_ok_and(|v| v.trim().eq_ignore_ascii_case("edits"))
73}
74
75/// Programs that only read (with the exceptions in `changes`). Anything else counts as a change.
76const 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
82/// git subcommands that only read.
83const GIT_READ: &[&str] = &["status", "log", "diff", "show", "blame", "branch", "rev-parse", "ls-files", "grep", "remote", "describe", "shortlog"];
84
85/// Whether a tool call changes state: an edit tool (Edit, Write, MultiEdit, NotebookEdit), or a Bash
86/// command any part of which is not read-only (`READ_ONLY`, read-only git), redirects output into a
87/// file, or edits in place (`sed -i`, `find -delete/-exec`). Other tools (Read, Grep, Glob, ...) read.
88pub 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                // The subcommand: the first word after `git` that is not an option (or `-C`/`-c`'s value).
108                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/// What the gate did in a store's session state (`borg status`): turn ends skipped at 0 tokens, turn
129/// ends that asked the model, and the model's cost as logged by `#borg-predict-cost` (USD for Claude,
130/// tokens for `codex:<model>`). Live checks (live.rs) log `#borg-predict-cost` too, and a `live` cost
131/// line each: they are counted apart (`live_checks`, `live_cost`), not as turn ends.
132#[derive(Debug, Default, PartialEq)]
133pub struct Tally {
134    pub skipped: usize,
135    pub asked: usize,
136    pub cost: f64,
137    /// R3b (main.rs `log_cost`): Stop blocks (extra rounds), the questions in them and their size;
138    /// free deliveries (context on a hook that forces no round), their lessons and size.
139    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    /// R1 (main.rs `record_verdicts`): model calls that also judged pending lessons, the lessons judged,
146    /// those that got a final verdict, and the characters the judging added to those prompts.
147    pub judge_calls: usize,
148    pub judged: usize,
149    pub judge_resolved: usize,
150    pub judge_chars: usize,
151    /// Live mode's model calls during the turn (before 0.7.6, history only), their cost and lessons shown.
152    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
201/// The gate's score and what an eval needs beside it (eval/preempt/stop_prefilter.py).
202pub 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        // A live check's ask is part of the turn, not its end.
234        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    /// A bookkeeping line in the turn (`#borg-answer` carries the drone's last proposal, `#borg-p` lesson
252    /// ids) is not the turn's work: it scores nothing.
253    #[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    /// Why the held-out result was fixed in advance (internal evaluation "stop-prefilter", not published): query words are a set
265    /// and every BM25 term is positive, so adding words to a turn never lowers its score. A checkpoint
266    /// whose brief alone reaches the threshold passes whatever the drone adds to it.
267    #[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        // A live check logs its call like a turn end's, and a `live` cost line: it is counted apart.
339        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}