Skip to main content

eclipse_core/
judge.rs

1//! `#340`: a third approval mode, where the aux route answers allow / deny / escalate.
2//!
3//! The gate has two settings today and neither reads the call: `ask` puts a card in front of a
4//! person, `auto` never does. This is the third, and it is deliberately the narrowest of them: the
5//! judge is consulted **only** for a call the registry already marked `ask` and whose tool says it
6//! needs approval. A `deny` policy never reaches it — a judge that can override the registry turns
7//! the registry into advice — and it can neither widen a policy nor allow a call that was not
8//! already going to be asked about.
9//!
10//! Three answers, and the mapping is the whole design:
11//!
12//! - `allow` → [`Decision::Allow`], the call runs, no card;
13//! - `deny: <reason>` → [`Decision::Deny`], the sentence reaches the model as the tool result;
14//! - anything else — `escalate`, an answer in the wrong words, a timeout, a dead route, a body that
15//!   does not parse — → the person's own gate, exactly as if the mode were `ask`.
16//!
17//! **The failure path is the feature.** This is the one call in the system where a timeout must
18//! never read as "carry on": the trimmed-turn summary falling back to `Allow` would be a shell
19//! command nobody approved. So every doubt escalates, and after [`FAILURES_BEFORE_QUIET`] failures
20//! in one turn the judge stops being consulted at all — a turn that makes forty `shell` calls is
21//! forty judge calls, and a route that is down should not cost forty timeouts before the person
22//! sees the first card.
23//!
24//! What the judge sees is the call, not the session: the tool name, its arguments, the one-line
25//! summary the person would have been shown, and the user's current ask. A judge fed the whole
26//! transcript is a second model billing for context and a new place private content goes, to answer
27//! a question four fields settle.
28
29use crate::approvals::{Decision, Pending};
30use crate::message::Message;
31use crate::provider::ChatProvider;
32use crate::tools::Approver;
33use std::sync::atomic::{AtomicUsize, Ordering};
34use std::time::Duration;
35
36/// How many times the judge may fail in one turn before it stops being asked.
37///
38/// Not a retry count — the provider's own retries are underneath this. This is the point at which
39/// "the route is down" stops costing a timeout per gated call for the rest of the turn.
40pub const FAILURES_BEFORE_QUIET: usize = 3;
41
42/// How much of the user's ask the judge is given. The ask is context for the call, not the task
43/// itself; a pasted file must not become a second prompt.
44const ASK_BUDGET: usize = 2_000;
45/// How much of the call's arguments the judge is given, for the same reason.
46const ARGS_BUDGET: usize = 4_000;
47
48/// Where a ruling goes so a later reader can find it: the store's append-only log, in practice.
49/// A named alias because the closure type is otherwise three lines of noise in every signature.
50pub type RulingLog = std::sync::Arc<dyn Fn(&Pending, &Decision, Option<&str>) + Send + Sync>;
51
52const SYSTEM: &str = "\
53You decide whether an autonomous coding agent may run one tool call, on behalf of a person who is \
54asleep or busy. You are given the person's current ask and the single call the agent wants to make.
55
56Answer with exactly one line, in one of these three forms:
57allow — the call is an ordinary part of the ask, and a reasonable person who asked for that would \
58not want to be woken up for it
59deny — the call is destructive, dishonest, or clearly outside what the ask is about, or you cannot \
60tell what it does
61escalate — the call is consequential enough that a person must decide: anything that deletes or \
62overwrites work they did not name, sends data off the machine, touches credentials, spends money, \
63or changes the system outside the working directory
64
65`deny` and `escalate` take a reason after a colon, addressed to the agent, in at most one short \
66sentence. No other words, no punctuation beyond that, no code fences.
67
68When in doubt, escalate. A wrong `allow` is a call nobody approved; a wrong `escalate` costs one \
69glance.";
70
71/// What the model said, once its words have been read.
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum Ruling {
74    Allow,
75    Deny(String),
76    /// Hand it to the person, with the model's reason if it gave one worth showing.
77    Escalate(String),
78}
79
80impl Ruling {
81    pub fn as_str(&self) -> &'static str {
82        match self {
83            Ruling::Allow => "allow",
84            Ruling::Deny(_) => "deny",
85            Ruling::Escalate(_) => "escalate",
86        }
87    }
88}
89
90/// Read the answer.
91///
92/// Fail-closed in the strongest sense available: the *only* text that produces [`Ruling::Allow`] is
93/// a line that starts with `allow`. Everything else is escalate, because an answer this build does
94/// not understand is not permission. `deny` keeps its reason, since that sentence is what teaches
95/// the model something; a `deny` with no reason still denies.
96pub fn parse_reply(text: &str) -> Ruling {
97    let line = text
98        .lines()
99        .map(str::trim)
100        .find(|l| !l.is_empty())
101        .unwrap_or_default();
102    let cleaned = line
103        .trim_start_matches(['"', '\'', '`', '*', '-', ' '])
104        .trim();
105    // The separator is a colon or an em dash, the two the prompt allows. A hyphen is part of a word:
106    // splitting on it read `allow-list check failed — deny` as the word `allow` plus a remainder, so
107    // a denial that happened to mention an allow-list came back as permission (`#551`).
108    let (word, rest) = match cleaned.split_once([':', '—']) {
109        Some((word, rest)) => (word.trim(), rest.trim()),
110        None => (cleaned, ""),
111    };
112    // A trailing full stop is the one punctuation the prompt tolerates.
113    let word = word.trim_end_matches('.');
114    match word.to_ascii_lowercase().as_str() {
115        // `allow` takes no reason — the prompt says so — so a line that says it and keeps talking is
116        // not one of the three answers. `allowed: false` and `allow: but it deletes the repo` are a
117        // judge refusing, and reading them as consent ran a gated call with no card (`#551`).
118        "allow" | "allowed" if rest.is_empty() => Ruling::Allow,
119        "deny" | "denied" => Ruling::Deny(if rest.is_empty() {
120            "the judge refused this call".to_string()
121        } else {
122            rest.to_string()
123        }),
124        "escalate" | "escalated" => Ruling::Escalate(if rest.is_empty() {
125            "the judge passed this call to you".to_string()
126        } else {
127            rest.to_string()
128        }),
129        _ => Ruling::Escalate(format!(
130            "the judge did not give one of the three answers ({})",
131            clip(line, 80)
132        )),
133    }
134}
135
136fn clip(text: &str, max: usize) -> String {
137    if text.chars().count() <= max {
138        return text.to_string();
139    }
140    let head: String = text.chars().take(max).collect();
141    format!("{head}…")
142}
143
144/// The two messages the judge is given: its instructions, and the call.
145pub fn prompt(ask: &str, call: &Pending) -> [Message; 2] {
146    let mut user = String::from("THE PERSON'S CURRENT ASK:\n");
147    let trimmed = ask.trim();
148    if trimmed.is_empty() {
149        user.push_str("(nothing — this run has no user prompt)");
150    } else {
151        user.push_str(&clip(trimmed, ASK_BUDGET));
152    }
153    user.push_str("\n\nTHE CALL THE AGENT WANTS TO MAKE:\n");
154    user.push_str(&format!("tool: {}\n", call.tool));
155    user.push_str(&format!("what it does: {}\n", call.summary));
156    let args = call.args.trim();
157    user.push_str("arguments: ");
158    if args.is_empty() || args == "{}" {
159        user.push_str("(none)\n");
160    } else {
161        user.push_str(&format!("\n{}\n", clip(args, ARGS_BUDGET)));
162    }
163    [Message::system(SYSTEM), Message::user(user)]
164}
165
166/// The gate's judge: one aux call per call that would otherwise be a card.
167///
168/// Wraps the person's own approver, so every doubt lands there. It is installed by
169/// [`crate::runtime::Agent`] for the duration of one run — `smart` is a mode of the run, not a
170/// property of whoever built the gate — and counts its own failures for that run.
171pub struct Judge<'a> {
172    aux: &'a std::sync::Arc<dyn ChatProvider>,
173    /// The user's ask, as context for the call.
174    ask: &'a str,
175    timeout: Duration,
176    /// Where an escalate goes: the person, exactly as they would have been asked anyway.
177    inner: &'a dyn Approver,
178    /// How many times this judge has failed in this run, against [`FAILURES_BEFORE_QUIET`].
179    failures: AtomicUsize,
180    /// Somewhere to leave the ruling, so what the model waved through is answerable later.
181    log: Option<RulingLog>,
182}
183
184impl<'a> Judge<'a> {
185    pub fn new(
186        aux: &'a std::sync::Arc<dyn ChatProvider>,
187        ask: &'a str,
188        timeout: Duration,
189        inner: &'a dyn Approver,
190    ) -> Self {
191        Self {
192            aux,
193            ask,
194            timeout,
195            inner,
196            failures: AtomicUsize::new(0),
197            log: None,
198        }
199    }
200
201    /// Record each ruling where a later reader can find it.
202    pub fn with_log(mut self, log: RulingLog) -> Self {
203        self.log = Some(log);
204        self
205    }
206
207    /// Ask, and turn every failure into the person's card.
208    async fn consult(&self, call: &Pending) -> (Ruling, Option<String>) {
209        let request = prompt(self.ask, call);
210        match tokio::time::timeout(self.timeout, self.aux.chat(&request, &[])).await {
211            Err(_) => (
212                Ruling::Escalate(format!(
213                    "the judge did not answer within {}s",
214                    self.timeout.as_secs()
215                )),
216                None,
217            ),
218            Ok(Err(e)) => (
219                Ruling::Escalate(format!("the judge call failed: {e}")),
220                None,
221            ),
222            Ok(Ok(answer)) => {
223                let text = answer.content.as_deref().unwrap_or_default().to_string();
224                match parse_reply(&text) {
225                    Ruling::Allow => (Ruling::Allow, None),
226                    Ruling::Deny(reason) => (Ruling::Deny(reason), None),
227                    Ruling::Escalate(why) => (Ruling::Escalate(why), None),
228                }
229            }
230        }
231    }
232}
233
234#[async_trait::async_trait]
235impl Approver for Judge<'_> {
236    async fn decide(&self, call: &Pending) -> Decision {
237        // A judge that has failed this many times is a route that is down: stop paying a timeout
238        // per call and let the person answer, which is what happens without the mode at all.
239        if self.failures.load(Ordering::Relaxed) >= FAILURES_BEFORE_QUIET {
240            return self.inner.decide(call).await;
241        }
242        let (ruling, _) = self.consult(call).await;
243        let decision = match ruling {
244            Ruling::Allow => Decision::Allow,
245            Ruling::Deny(reason) => Decision::Deny(reason),
246            Ruling::Escalate(why) => {
247                // Counted as a failure only when the judge did not actually rule — an explicit
248                // `escalate` is a working judge doing its job, and it must not be discouraged.
249                if why.starts_with("the judge did not") || why.starts_with("the judge call failed")
250                {
251                    self.failures.fetch_add(1, Ordering::Relaxed);
252                }
253                if let Some(log) = &self.log {
254                    log(call, &Decision::Defer, Some(&why));
255                }
256                return self.inner.decide(call).await;
257            }
258        };
259        if let Some(log) = &self.log {
260            log(call, &decision, None);
261        }
262        decision
263    }
264}
265
266#[cfg(test)]
267mod tests {
268    use super::*;
269
270    fn call() -> Pending {
271        Pending::new(
272            "call_1",
273            "shell",
274            "run `ls`".to_string(),
275            r#"{"command":"ls"}"#.into(),
276        )
277    }
278
279    /// `#551`: the allow arm ignored everything after a separator and the separator list included a
280    /// bare hyphen, so a judge that *refused* in prose was read as permission and the gated call ran
281    /// with no card. The prompt says `allow` takes no reason, so anything after it is not consent.
282    #[test]
283    fn a_refusal_that_mentions_allow_is_not_permission() {
284        for text in [
285            "allowed: false",
286            "allow-list check failed — deny",
287            "allow: but it deletes the repository",
288            "allow — read-only, still needs a card",
289            "allowance denied",
290            "allowed by policy, except it is not",
291        ] {
292            let ruling = parse_reply(text);
293            assert!(
294                matches!(ruling, Ruling::Escalate(_)),
295                "{text:?} read as {ruling:?}, and only a bare `allow` is permission"
296            );
297        }
298        // The three words on their own are still the three answers, full stop or not.
299        for text in ["allow", "Allow.", "ALLOW", "  allow  "] {
300            assert_eq!(parse_reply(text), Ruling::Allow, "{text:?}");
301        }
302        assert_eq!(
303            parse_reply("deny."),
304            Ruling::Deny("the judge refused this call".into())
305        );
306    }
307
308    #[test]
309    fn the_three_words_are_read_and_nothing_else_is_permission() {
310        assert_eq!(parse_reply("allow"), Ruling::Allow);
311        assert_eq!(parse_reply("ALLOW.\n"), Ruling::Allow);
312        assert_eq!(parse_reply(" allow "), Ruling::Allow);
313        assert_eq!(
314            parse_reply("deny: that deletes the repository"),
315            Ruling::Deny("that deletes the repository".into())
316        );
317        assert_eq!(
318            parse_reply("escalate: it writes outside the working directory"),
319            Ruling::Escalate("it writes outside the working directory".into())
320        );
321        // Fail closed: words this build did not ask for are not permission.
322        assert!(matches!(parse_reply("sure, go ahead"), Ruling::Escalate(_)));
323        assert!(matches!(parse_reply(""), Ruling::Escalate(_)));
324        assert!(matches!(
325            parse_reply("{\"allow\": true}"),
326            Ruling::Escalate(_)
327        ));
328    }
329
330    #[test]
331    fn a_deny_without_a_reason_still_says_why_it_is_a_denial() {
332        assert_eq!(
333            parse_reply("deny"),
334            Ruling::Deny("the judge refused this call".into())
335        );
336        assert_eq!(
337            parse_reply("deny:"),
338            Ruling::Deny("the judge refused this call".into())
339        );
340    }
341
342    #[test]
343    fn the_judge_is_given_the_call_and_the_ask_not_a_transcript() {
344        let [system, user] = prompt("fix the failing test", &call());
345        assert!(system.content.as_deref().unwrap().contains("escalate"));
346        let user = user.content.unwrap();
347        assert!(user.contains("fix the failing test"));
348        assert!(user.contains("tool: shell"));
349        assert!(user.contains("run `ls`"));
350        assert!(user.contains(r#"{"command":"ls"}"#));
351    }
352
353    #[test]
354    fn a_pasted_file_is_not_carried_into_the_judge_whole() {
355        let ask = "x".repeat(10_000);
356        let [_, user] = prompt(&ask, &call());
357        let user = user.content.unwrap();
358        assert!(
359            user.len() < ASK_BUDGET + 500,
360            "the ask is clipped: {}",
361            user.len()
362        );
363        assert!(user.ends_with('…') || user.contains('…'));
364    }
365}