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    let (word, rest) = match cleaned.split_once([':', '—', '-']) {
106        Some((word, rest)) => (word.trim(), rest.trim()),
107        None => (cleaned, ""),
108    };
109    match word.to_ascii_lowercase().as_str() {
110        "allow" | "allowed" | "allow." => Ruling::Allow,
111        "deny" | "denied" | "deny." => Ruling::Deny(if rest.is_empty() {
112            "the judge refused this call".to_string()
113        } else {
114            rest.to_string()
115        }),
116        "escalate" | "escalated" | "escalate." => Ruling::Escalate(if rest.is_empty() {
117            "the judge passed this call to you".to_string()
118        } else {
119            rest.to_string()
120        }),
121        _ => Ruling::Escalate(format!(
122            "the judge did not give one of the three answers ({})",
123            clip(line, 80)
124        )),
125    }
126}
127
128fn clip(text: &str, max: usize) -> String {
129    if text.chars().count() <= max {
130        return text.to_string();
131    }
132    let head: String = text.chars().take(max).collect();
133    format!("{head}…")
134}
135
136/// The two messages the judge is given: its instructions, and the call.
137pub fn prompt(ask: &str, call: &Pending) -> [Message; 2] {
138    let mut user = String::from("THE PERSON'S CURRENT ASK:\n");
139    let trimmed = ask.trim();
140    if trimmed.is_empty() {
141        user.push_str("(nothing — this run has no user prompt)");
142    } else {
143        user.push_str(&clip(trimmed, ASK_BUDGET));
144    }
145    user.push_str("\n\nTHE CALL THE AGENT WANTS TO MAKE:\n");
146    user.push_str(&format!("tool: {}\n", call.tool));
147    user.push_str(&format!("what it does: {}\n", call.summary));
148    let args = call.args.trim();
149    user.push_str("arguments: ");
150    if args.is_empty() || args == "{}" {
151        user.push_str("(none)\n");
152    } else {
153        user.push_str(&format!("\n{}\n", clip(args, ARGS_BUDGET)));
154    }
155    [Message::system(SYSTEM), Message::user(user)]
156}
157
158/// The gate's judge: one aux call per call that would otherwise be a card.
159///
160/// Wraps the person's own approver, so every doubt lands there. It is installed by
161/// [`crate::runtime::Agent`] for the duration of one run — `smart` is a mode of the run, not a
162/// property of whoever built the gate — and counts its own failures for that run.
163pub struct Judge<'a> {
164    aux: &'a std::sync::Arc<dyn ChatProvider>,
165    /// The user's ask, as context for the call.
166    ask: &'a str,
167    timeout: Duration,
168    /// Where an escalate goes: the person, exactly as they would have been asked anyway.
169    inner: &'a dyn Approver,
170    /// How many times this judge has failed in this run, against [`FAILURES_BEFORE_QUIET`].
171    failures: AtomicUsize,
172    /// Somewhere to leave the ruling, so what the model waved through is answerable later.
173    log: Option<RulingLog>,
174}
175
176impl<'a> Judge<'a> {
177    pub fn new(
178        aux: &'a std::sync::Arc<dyn ChatProvider>,
179        ask: &'a str,
180        timeout: Duration,
181        inner: &'a dyn Approver,
182    ) -> Self {
183        Self {
184            aux,
185            ask,
186            timeout,
187            inner,
188            failures: AtomicUsize::new(0),
189            log: None,
190        }
191    }
192
193    /// Record each ruling where a later reader can find it.
194    pub fn with_log(mut self, log: RulingLog) -> Self {
195        self.log = Some(log);
196        self
197    }
198
199    /// Ask, and turn every failure into the person's card.
200    async fn consult(&self, call: &Pending) -> (Ruling, Option<String>) {
201        let request = prompt(self.ask, call);
202        match tokio::time::timeout(self.timeout, self.aux.chat(&request, &[])).await {
203            Err(_) => (
204                Ruling::Escalate(format!(
205                    "the judge did not answer within {}s",
206                    self.timeout.as_secs()
207                )),
208                None,
209            ),
210            Ok(Err(e)) => (
211                Ruling::Escalate(format!("the judge call failed: {e}")),
212                None,
213            ),
214            Ok(Ok(answer)) => {
215                let text = answer.content.as_deref().unwrap_or_default().to_string();
216                match parse_reply(&text) {
217                    Ruling::Allow => (Ruling::Allow, None),
218                    Ruling::Deny(reason) => (Ruling::Deny(reason), None),
219                    Ruling::Escalate(why) => (Ruling::Escalate(why), None),
220                }
221            }
222        }
223    }
224}
225
226#[async_trait::async_trait]
227impl Approver for Judge<'_> {
228    async fn decide(&self, call: &Pending) -> Decision {
229        // A judge that has failed this many times is a route that is down: stop paying a timeout
230        // per call and let the person answer, which is what happens without the mode at all.
231        if self.failures.load(Ordering::Relaxed) >= FAILURES_BEFORE_QUIET {
232            return self.inner.decide(call).await;
233        }
234        let (ruling, _) = self.consult(call).await;
235        let decision = match ruling {
236            Ruling::Allow => Decision::Allow,
237            Ruling::Deny(reason) => Decision::Deny(reason),
238            Ruling::Escalate(why) => {
239                // Counted as a failure only when the judge did not actually rule — an explicit
240                // `escalate` is a working judge doing its job, and it must not be discouraged.
241                if why.starts_with("the judge did not") || why.starts_with("the judge call failed")
242                {
243                    self.failures.fetch_add(1, Ordering::Relaxed);
244                }
245                if let Some(log) = &self.log {
246                    log(call, &Decision::Defer, Some(&why));
247                }
248                return self.inner.decide(call).await;
249            }
250        };
251        if let Some(log) = &self.log {
252            log(call, &decision, None);
253        }
254        decision
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    fn call() -> Pending {
263        Pending::new(
264            "call_1",
265            "shell",
266            "run `ls`".to_string(),
267            r#"{"command":"ls"}"#.into(),
268        )
269    }
270
271    #[test]
272    fn the_three_words_are_read_and_nothing_else_is_permission() {
273        assert_eq!(parse_reply("allow"), Ruling::Allow);
274        assert_eq!(parse_reply("ALLOW.\n"), Ruling::Allow);
275        assert_eq!(parse_reply(" allow "), Ruling::Allow);
276        assert_eq!(
277            parse_reply("deny: that deletes the repository"),
278            Ruling::Deny("that deletes the repository".into())
279        );
280        assert_eq!(
281            parse_reply("escalate: it writes outside the working directory"),
282            Ruling::Escalate("it writes outside the working directory".into())
283        );
284        // Fail closed: words this build did not ask for are not permission.
285        assert!(matches!(parse_reply("sure, go ahead"), Ruling::Escalate(_)));
286        assert!(matches!(parse_reply(""), Ruling::Escalate(_)));
287        assert!(matches!(
288            parse_reply("{\"allow\": true}"),
289            Ruling::Escalate(_)
290        ));
291    }
292
293    #[test]
294    fn a_deny_without_a_reason_still_says_why_it_is_a_denial() {
295        assert_eq!(
296            parse_reply("deny"),
297            Ruling::Deny("the judge refused this call".into())
298        );
299        assert_eq!(
300            parse_reply("deny:"),
301            Ruling::Deny("the judge refused this call".into())
302        );
303    }
304
305    #[test]
306    fn the_judge_is_given_the_call_and_the_ask_not_a_transcript() {
307        let [system, user] = prompt("fix the failing test", &call());
308        assert!(system.content.as_deref().unwrap().contains("escalate"));
309        let user = user.content.unwrap();
310        assert!(user.contains("fix the failing test"));
311        assert!(user.contains("tool: shell"));
312        assert!(user.contains("run `ls`"));
313        assert!(user.contains(r#"{"command":"ls"}"#));
314    }
315
316    #[test]
317    fn a_pasted_file_is_not_carried_into_the_judge_whole() {
318        let ask = "x".repeat(10_000);
319        let [_, user] = prompt(&ask, &call());
320        let user = user.content.unwrap();
321        assert!(
322            user.len() < ASK_BUDGET + 500,
323            "the ask is clipped: {}",
324            user.len()
325        );
326        assert!(user.ends_with('…') || user.contains('…'));
327    }
328}