Skip to main content

agent86_core/
verify.rs

1//! The verification gate, beyond Python (slice 1 of the local-model work in
2//! `docs/PROJECT_PLAN.md`).
3//!
4//! With `[verify] command` set, a turn that changed the workspace does not end on
5//! the model's word: when the model gives its final answer, the harness runs the
6//! command as a `run_command` call (through the approval gate and the sandbox
7//! executor, as the model's own call would be), and a failure goes back to the
8//! model as a user message holding the command's output, up to `max_attempts`
9//! times. After that, or when the turn is out of steps, the answer stands, with
10//! the failure said. A turn that only read things is never checked.
11//!
12//! The command is the user's: it comes from their own config, or from a project
13//! file only once that file is trusted (`verify` is not in `trust::TRUST_FREE`).
14
15use crate::agent::{observation, Harness, TurnEvent};
16use crate::config::VerifyConfig;
17use crate::types::ToolCall;
18use serde::{Deserialize, Serialize};
19use serde_json::{json, Map, Value};
20use std::sync::Mutex;
21
22/// How much of a failing command's output goes back to the model: its end, where
23/// test runners put their summary.
24pub const FEEDBACK_CHARS: usize = 6000;
25
26/// Tools whose successful call means the turn may have changed the workspace.
27pub const CHANGING_TOOLS: &[&str] = &[
28    "write_file",
29    "edit_file",
30    "run_command",
31    "python_exec",
32    "delegate",
33];
34
35/// The gate's settings and what it found in the last turn.
36#[derive(Debug, Default)]
37pub struct Verify {
38    /// The command; `None` turns the gate off.
39    pub command: Option<String>,
40    /// Failures sent back to the model in one turn before the answer stands.
41    pub max_attempts: u32,
42    last: Mutex<Option<Verification>>,
43}
44
45impl Verify {
46    /// The gate as `[verify]` configures it: off when `command` is blank.
47    pub fn from_config(config: &VerifyConfig) -> Self {
48        Self::new(Some(config.command.as_str()), config.max_attempts)
49    }
50
51    /// A gate running `command` (off when it is blank or `None`).
52    pub fn new(command: Option<&str>, max_attempts: u32) -> Self {
53        Self {
54            command: command
55                .map(str::trim)
56                .filter(|command| !command.is_empty())
57                .map(str::to_owned),
58            max_attempts,
59            last: Mutex::new(None),
60        }
61    }
62
63    /// What the gate found in the last turn, if it was on (`run --json`'s
64    /// `verification`).
65    pub fn last(&self) -> Option<Verification> {
66        self.last.lock().ok().and_then(|last| last.clone())
67    }
68
69    pub(crate) fn set_last(&self, verification: Option<Verification>) {
70        if let Ok(mut last) = self.last.lock() {
71            *last = verification;
72        }
73    }
74}
75
76/// What the gate did in one turn.
77#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[non_exhaustive]
79pub struct Verification {
80    pub command: String,
81    /// `passed`, `failed` (the answer stands with the command still failing), or
82    /// `skipped` (`reason` says why).
83    pub status: VerifyStatus,
84    /// Times the command ran.
85    pub runs: u32,
86    /// Failures sent back to the model.
87    pub sent_back: u32,
88    #[serde(default, skip_serializing_if = "Option::is_none")]
89    pub reason: Option<String>,
90}
91
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
93#[serde(rename_all = "snake_case")]
94#[non_exhaustive]
95pub enum VerifyStatus {
96    Passed,
97    Failed,
98    Skipped,
99}
100
101/// The gate's progress through one turn.
102#[derive(Debug, Default)]
103pub(crate) struct VerifyRun {
104    /// A call that may have changed the workspace succeeded.
105    pub changed: bool,
106    pub runs: u32,
107    pub sent_back: u32,
108}
109
110impl VerifyRun {
111    /// Note a finished tool call.
112    pub fn saw(&mut self, tool: &str, ok: bool) {
113        if ok && CHANGING_TOOLS.contains(&tool) {
114            self.changed = true;
115        }
116    }
117}
118
119/// What the loop does with the model's final answer.
120pub(crate) enum Gate {
121    /// The answer stands.
122    Stand,
123    /// The answer goes back: this user message, then another step.
124    SendBack(String),
125}
126
127/// The message a failure goes back to the model as.
128pub fn feedback(command: &str, exit: Option<i64>, output: &str) -> String {
129    let status = match exit {
130        Some(code) => format!("failed with exit code {code}"),
131        None => "failed".to_owned(),
132    };
133    format!(
134        "[verification] The check `{command}` {status}, so the task is not done yet. \
135         Find and fix the cause, then give your final answer again.\n\n{}",
136        tail(output, FEEDBACK_CHARS)
137    )
138}
139
140/// The last `max` characters of `text`, saying how much was left out.
141pub fn tail(text: &str, max: usize) -> String {
142    let count = text.chars().count();
143    if count <= max {
144        return text.to_owned();
145    }
146    let kept: String = text.chars().skip(count - max).collect();
147    format!(
148        "[... {} earlier characters left out ...]\n{kept}",
149        count - max
150    )
151}
152
153impl Harness {
154    /// Check the model's final answer (see the module docs). `steps_left` says
155    /// whether another step may follow; with none, a failure is said and the
156    /// answer stands.
157    pub(crate) fn verify_answer(
158        &self,
159        run: &mut VerifyRun,
160        steps_left: bool,
161        sid: &str,
162        emit: &mut impl FnMut(TurnEvent<'_>),
163    ) -> Gate {
164        let Some(command) = self.verify.command.clone() else {
165            return Gate::Stand;
166        };
167        let record = |status, reason: Option<String>, run: &VerifyRun| {
168            self.verify.set_last(Some(Verification {
169                command: command.clone(),
170                status,
171                runs: run.runs,
172                sent_back: run.sent_back,
173                reason,
174            }));
175        };
176        if !run.changed {
177            record(VerifyStatus::Skipped, Some("nothing changed".into()), run);
178            return Gate::Stand;
179        }
180        if self.cancel.is_cancelled() {
181            record(VerifyStatus::Skipped, Some("cancelled".into()), run);
182            return Gate::Stand;
183        }
184
185        let mut arguments = Map::new();
186        arguments.insert("command".into(), Value::String(command.clone()));
187        let call = ToolCall {
188            id: format!("verify_{}", run.runs + 1),
189            name: "run_command".into(),
190            arguments,
191        };
192        // The gate decides as for the model's own call, so `deny`, a declined
193        // prompt, or a scope without `run_command` keeps the check from running.
194        let (refused, _) = self.resolve_call(&call, sid);
195        let result = match refused {
196            Some(result) => {
197                let reason = observation(&result);
198                emit(TurnEvent::Notice(&format!(
199                    "\n[verify] `{command}` not run: {reason}\n"
200                )));
201                self.record_verify(sid, &command, None, run, "skipped");
202                record(VerifyStatus::Skipped, Some(reason), run);
203                return Gate::Stand;
204            }
205            None => self.dispatch(&call, sid),
206        };
207        run.runs += 1;
208        let exit = result.metadata.get("returncode").and_then(Value::as_i64);
209        if result.ok {
210            emit(TurnEvent::Notice(&format!(
211                "\n[verify] `{command}` passed\n"
212            )));
213            self.record_verify(sid, &command, exit, run, "passed");
214            record(VerifyStatus::Passed, None, run);
215            return Gate::Stand;
216        }
217        if run.sent_back < self.verify.max_attempts && steps_left {
218            run.sent_back += 1;
219            emit(TurnEvent::Notice(&format!(
220                "\n[verify] `{command}` failed; sent back to the model ({} of {})\n",
221                run.sent_back, self.verify.max_attempts
222            )));
223            self.record_verify(sid, &command, exit, run, "sent_back");
224            let (output, _) = self.guardrails.observe(observation(&result));
225            return Gate::SendBack(feedback(&command, exit, &output));
226        }
227        emit(TurnEvent::Notice(&format!(
228            "\n[verify] `{command}` still fails; the answer stands unverified\n"
229        )));
230        self.record_verify(sid, &command, exit, run, "failed");
231        record(VerifyStatus::Failed, None, run);
232        Gate::Stand
233    }
234
235    /// A `verify` trace event (agent86's own kind; Python has no gate).
236    fn record_verify(
237        &self,
238        sid: &str,
239        command: &str,
240        exit: Option<i64>,
241        run: &VerifyRun,
242        outcome: &str,
243    ) {
244        self.recorder.event(
245            sid,
246            "verify",
247            vec![
248                ("command", json!(command)),
249                ("outcome", json!(outcome)),
250                ("returncode", json!(exit)),
251                ("runs", json!(run.runs)),
252                ("sent_back", json!(run.sent_back)),
253            ],
254        );
255    }
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn a_blank_command_turns_the_gate_off() {
264        assert_eq!(Verify::new(Some("  "), 2).command, None);
265        assert_eq!(Verify::new(None, 2).command, None);
266        assert_eq!(
267            Verify::new(Some(" cargo test "), 2).command.as_deref(),
268            Some("cargo test")
269        );
270    }
271
272    #[test]
273    fn only_a_successful_change_counts() {
274        let mut run = VerifyRun::default();
275        run.saw("read_file", true);
276        run.saw("write_file", false);
277        assert!(!run.changed);
278        run.saw("edit_file", true);
279        assert!(run.changed);
280    }
281
282    #[test]
283    fn feedback_keeps_the_end_of_the_output() {
284        let output = format!("{}FAILED (failures=1)", "x".repeat(FEEDBACK_CHARS));
285        let text = feedback("python -m unittest", Some(1), &output);
286        assert!(text
287            .starts_with("[verification] The check `python -m unittest` failed with exit code 1"));
288        assert!(text.ends_with("FAILED (failures=1)"));
289        assert!(text.contains("[... 19 earlier characters left out ...]"));
290        assert_eq!(tail("short", 10), "short");
291    }
292}