1use 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
22pub const FEEDBACK_CHARS: usize = 6000;
25
26pub const CHANGING_TOOLS: &[&str] = &[
28 "write_file",
29 "edit_file",
30 "run_command",
31 "python_exec",
32 "delegate",
33];
34
35#[derive(Debug, Default)]
37pub struct Verify {
38 pub command: Option<String>,
40 pub max_attempts: u32,
42 last: Mutex<Option<Verification>>,
43}
44
45impl Verify {
46 pub fn from_config(config: &VerifyConfig) -> Self {
48 Self::new(Some(config.command.as_str()), config.max_attempts)
49 }
50
51 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
78#[non_exhaustive]
79pub struct Verification {
80 pub command: String,
81 pub status: VerifyStatus,
84 pub runs: u32,
86 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#[derive(Debug, Default)]
103pub(crate) struct VerifyRun {
104 pub changed: bool,
106 pub runs: u32,
107 pub sent_back: u32,
108}
109
110impl VerifyRun {
111 pub fn saw(&mut self, tool: &str, ok: bool) {
113 if ok && CHANGING_TOOLS.contains(&tool) {
114 self.changed = true;
115 }
116 }
117}
118
119pub(crate) enum Gate {
121 Stand,
123 SendBack(String),
125}
126
127pub 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
140pub 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 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 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 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}