1use std::path::Path;
11use std::process::{Command, Stdio};
12use std::time::{Duration, Instant};
13
14use anyhow::{Context, Result, anyhow, bail};
15use serde::{Deserialize, Serialize};
16
17use super::suite::{Domain, Task};
18
19const MAX_EVALUATION_FIXTURE_FILES: usize = 128;
20const MAX_EVALUATION_FIXTURE_BYTES: u64 = 4 * 1024 * 1024;
21const MAX_EVALUATION_FIXTURE_DEPTH: usize = 16;
22
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
26pub struct Score {
27 pub value: f64,
28 pub passed: bool,
29 pub metric: String,
31 pub detail: String,
33}
34
35pub trait Scorer {
37 fn score(&self, task: &Task, output: &str, workspace: &Path) -> Result<Score>;
38}
39
40pub fn score_task(task: &Task, output: &str, workspace: &Path) -> Result<Score> {
42 match task.domain {
43 Domain::Qa => QaScorer.score(task, output, workspace),
44 Domain::Code => CodeScorer::default().score(task, output, workspace),
45 }
46}
47
48pub struct QaScorer;
54
55impl Scorer for QaScorer {
56 fn score(&self, task: &Task, output: &str, _workspace: &Path) -> Result<Score> {
57 let pred = normalize(output);
58 let pred_tokens: Vec<&str> = pred.split_whitespace().collect();
59
60 let mut best_em = false;
61 let mut best_contain = false;
62 let mut best_f1 = 0.0f64;
63 for gold in &task.answers {
64 let g = normalize(gold);
65 if g.is_empty() {
66 continue;
67 }
68 let g_tokens: Vec<&str> = g.split_whitespace().collect();
69 best_em |= pred == g;
70 best_contain |= !g.is_empty() && pred.contains(&g);
71 best_f1 = best_f1.max(token_f1(&pred_tokens, &g_tokens));
72 }
73
74 Ok(Score {
75 value: best_f1,
76 passed: best_em || best_contain,
77 metric: "f1".to_string(),
78 detail: format!(
79 "em={} f1={best_f1:.2} contain={}",
80 u8::from(best_em),
81 u8::from(best_contain)
82 ),
83 })
84 }
85}
86
87pub fn qa_f1(pred: &str, gold: &str) -> f64 {
90 let p = normalize(pred);
91 let g = normalize(gold);
92 let pt: Vec<&str> = p.split_whitespace().collect();
93 let gt: Vec<&str> = g.split_whitespace().collect();
94 token_f1(&pt, >)
95}
96
97pub fn qa_exact_match(pred: &str, gold: &str) -> bool {
99 normalize(pred) == normalize(gold)
100}
101
102pub fn qa_contains(pred: &str, gold: &str) -> bool {
104 let g = normalize(gold);
105 !g.is_empty() && normalize(pred).contains(&g)
106}
107
108fn normalize(s: &str) -> String {
110 let lowered = s.to_lowercase();
111 let cleaned: String = lowered
112 .chars()
113 .map(|c| if c.is_alphanumeric() { c } else { ' ' })
114 .collect();
115 cleaned
116 .split_whitespace()
117 .filter(|w| !matches!(*w, "a" | "an" | "the"))
118 .collect::<Vec<_>>()
119 .join(" ")
120}
121
122fn token_f1(pred: &[&str], gold: &[&str]) -> f64 {
124 if pred.is_empty() && gold.is_empty() {
125 return 1.0;
126 }
127 if pred.is_empty() || gold.is_empty() {
128 return 0.0;
129 }
130 let mut gold_counts: std::collections::HashMap<&str, i64> = std::collections::HashMap::new();
131 for &t in gold {
132 *gold_counts.entry(t).or_insert(0) += 1;
133 }
134 let mut common = 0i64;
135 let mut pred_counts: std::collections::HashMap<&str, i64> = std::collections::HashMap::new();
136 for &t in pred {
137 let entry = pred_counts.entry(t).or_insert(0);
138 *entry += 1;
139 if *entry <= gold_counts.get(t).copied().unwrap_or(0) {
140 common += 1;
141 }
142 }
143 if common == 0 {
144 return 0.0;
145 }
146 let precision = common as f64 / pred.len() as f64;
147 let recall = common as f64 / gold.len() as f64;
148 2.0 * precision * recall / (precision + recall)
149}
150
151pub struct CodeScorer {
157 pub timeout: Duration,
159 require_isolation: bool,
161}
162
163impl Default for CodeScorer {
164 fn default() -> Self {
165 #[allow(clippy::duration_suboptimal_units)]
167 Self {
168 timeout: Duration::from_secs(60),
169 require_isolation: false,
170 }
171 }
172}
173
174impl CodeScorer {
175 pub fn isolated() -> Self {
178 Self {
179 require_isolation: true,
180 ..Self::default()
181 }
182 }
183}
184
185impl Scorer for CodeScorer {
186 fn score(&self, task: &Task, output: &str, workspace: &Path) -> Result<Score> {
187 if let Err(reason) = task.validate_code_evaluation() {
188 bail!("invalid task {}: {reason}", task.id);
189 }
190 let metadata = std::fs::symlink_metadata(workspace)
191 .with_context(|| format!("inspecting workspace {}", workspace.display()))?;
192 if metadata.file_type().is_symlink() {
193 bail!(
194 "refusing symlinked code-evaluation workspace {}",
195 workspace.display()
196 );
197 }
198 if !metadata.is_dir() {
199 bail!("code-evaluation workspace is not a directory");
200 }
201 let workspace = std::fs::canonicalize(workspace)
202 .with_context(|| format!("canonicalizing workspace {}", workspace.display()))?;
203
204 let target = task
205 .target_file
206 .as_deref()
207 .ok_or_else(|| anyhow!("code task {} has no target_file", task.id))?;
208 let test_cmd = task
209 .test_cmd
210 .as_deref()
211 .ok_or_else(|| anyhow!("code task {} has no test_cmd", task.id))?;
212
213 let sandbox = tempfile::tempdir().context("creating sandbox")?;
214 let mut copy_budget = CopyBudget::default();
215 copy_dir_all(&workspace, sandbox.path(), 0, &mut copy_budget)
216 .with_context(|| format!("copying workspace {}", workspace.display()))?;
217
218 let target_path = sandbox.path().join(target);
219 if let Some(parent) = target_path.parent() {
220 std::fs::create_dir_all(parent).ok();
221 }
222 std::fs::write(&target_path, extract_code(output))
223 .with_context(|| format!("writing solution to {}", target_path.display()))?;
224
225 let passed = run_with_timeout(
226 test_cmd,
227 sandbox.path(),
228 self.timeout,
229 self.require_isolation,
230 )?;
231 Ok(Score {
232 value: f64::from(u8::from(passed)),
233 passed,
234 metric: "unit_test".to_string(),
235 detail: format!("test_cmd={test_cmd:?} passed={passed}"),
236 })
237 }
238}
239
240fn extract_code(output: &str) -> String {
243 let trimmed = output.trim();
244 if let Some(rest) = trimmed.strip_prefix("```") {
245 let after_lang = rest.find('\n').map_or(rest, |i| &rest[i + 1..]);
247 if let Some(end) = after_lang.rfind("```") {
248 return after_lang[..end].trim_end().to_string();
249 }
250 }
251 trimmed.to_string()
252}
253
254#[derive(Default)]
255struct CopyBudget {
256 files: usize,
257 bytes: u64,
258}
259
260fn copy_dir_all(
264 src: &Path,
265 dst: &Path,
266 depth: usize,
267 budget: &mut CopyBudget,
268) -> std::io::Result<()> {
269 if depth > MAX_EVALUATION_FIXTURE_DEPTH {
270 return Err(std::io::Error::other(
271 "code-evaluation fixture is nested too deeply",
272 ));
273 }
274 for entry in std::fs::read_dir(src)? {
275 let entry = entry?;
276 let from = entry.path();
277 let to = dst.join(entry.file_name());
278 let file_type = entry.file_type()?;
279 if file_type.is_symlink() {
280 return Err(std::io::Error::other(format!(
281 "refusing symlink in code-evaluation workspace: {}",
282 from.display()
283 )));
284 }
285 if file_type.is_dir() {
286 std::fs::create_dir_all(&to)?;
287 copy_dir_all(&from, &to, depth + 1, budget)?;
288 } else if file_type.is_file() {
289 let file_bytes = entry.metadata()?.len();
290 budget.files = budget.files.saturating_add(1);
291 budget.bytes = budget.bytes.saturating_add(file_bytes);
292 if budget.files > MAX_EVALUATION_FIXTURE_FILES
293 || budget.bytes > MAX_EVALUATION_FIXTURE_BYTES
294 {
295 return Err(std::io::Error::other(
296 "code-evaluation fixture exceeds file or byte limit",
297 ));
298 }
299 std::fs::copy(&from, &to)?;
300 } else {
301 return Err(std::io::Error::other(format!(
302 "refusing non-regular entry in code-evaluation workspace: {}",
303 from.display()
304 )));
305 }
306 }
307 Ok(())
308}
309
310fn run_with_timeout(
312 cmd: &str,
313 dir: &Path,
314 timeout: Duration,
315 require_isolation: bool,
316) -> Result<bool> {
317 let execution_dir = if require_isolation {
322 std::fs::canonicalize(dir)
323 .with_context(|| format!("canonicalizing isolated fixture {}", dir.display()))?
324 } else {
325 dir.to_path_buf()
326 };
327 let mut command = if require_isolation {
328 isolated_test_command(cmd, &execution_dir)?
329 } else {
330 let mut command = Command::new("sh");
331 command.arg("-c").arg(cmd);
332 command
333 };
334 let stderr_path = require_isolation.then(|| execution_dir.join(".leanctx-evaluator-stderr"));
335 if let Some(path) = &stderr_path {
336 let stderr = std::fs::File::create(path).with_context(|| {
337 format!(
338 "creating isolated evaluator diagnostics at {}",
339 path.display()
340 )
341 })?;
342 command.stderr(Stdio::from(stderr));
343 } else {
344 command.stderr(Stdio::null());
345 }
346 let mut child = command
347 .current_dir(&execution_dir)
348 .stdout(Stdio::null())
349 .stdin(Stdio::null())
350 .spawn()
351 .with_context(|| format!("spawning test command: {cmd}"))?;
352
353 let start = Instant::now();
354 loop {
355 if let Some(status) = child.try_wait()? {
356 if status.success() {
357 return Ok(true);
358 }
359 if let Some(path) = stderr_path {
360 let diagnostics = std::fs::read_to_string(path).unwrap_or_default();
361 if !diagnostics.trim().is_empty() {
362 anyhow::bail!(
363 "isolated evaluator could not execute test command: {}",
364 diagnostics.trim()
365 );
366 }
367 }
368 return Ok(false);
369 }
370 if start.elapsed() > timeout {
371 let _ = child.kill();
372 let _ = child.wait();
373 return Ok(false);
374 }
375 std::thread::sleep(Duration::from_millis(25));
376 }
377}
378
379#[cfg(target_os = "macos")]
380fn isolated_test_command(cmd: &str, dir: &Path) -> Result<Command> {
381 let directory = dir
382 .to_str()
383 .ok_or_else(|| anyhow!("code-evaluation directory is not valid UTF-8"))?
384 .replace('\\', "\\\\")
385 .replace('"', "\\\"");
386 let profile = format!(
394 "(version 1)\n(deny default)\n(allow process*)\n(allow file-read* (literal \"/\") (subpath \"{directory}\") (subpath \"/bin\") (subpath \"/usr/bin\") (subpath \"/usr/lib\") (subpath \"/System\") (subpath \"/private/var/db\") (subpath \"/private/var/select\") (subpath \"/private/var/folders\") (subpath \"/var/folders\") (literal \"/dev/null\"))\n(allow file-write* (subpath \"{directory}\"))\n(deny network*)"
395 );
396 let mut command = Command::new("/usr/bin/sandbox-exec");
397 command.args([
398 "-p",
399 &profile,
400 "/bin/sh",
401 "-c",
402 "ulimit -t 5 -f 8192 -n 16; exec /bin/sh -c \"$1\"",
403 "leanctx-code-evaluator",
404 cmd,
405 ]);
406 Ok(command)
407}
408
409#[cfg(not(target_os = "macos"))]
410fn isolated_test_command(_cmd: &str, _dir: &Path) -> Result<Command> {
411 Err(anyhow!(
412 "isolated code evaluation requires a supported local sandbox; this host has none"
413 ))
414}
415
416#[cfg(test)]
417mod tests {
418 use super::*;
419
420 fn qa_task() -> Task {
421 Task {
422 id: "q".into(),
423 domain: Domain::Qa,
424 prompt: "p".into(),
425 workspace: "w".into(),
426 retrieval_query: None,
427 answers: vec!["bm25 graph knowledge session".into()],
428 target_file: None,
429 test_cmd: None,
430 }
431 }
432
433 #[test]
434 fn qa_exact_match_scores_one() {
435 let s = QaScorer
436 .score(
437 &qa_task(),
438 "BM25, graph, knowledge, session.",
439 Path::new("."),
440 )
441 .unwrap();
442 assert!(s.passed);
443 assert_eq!(s.value, 1.0);
444 }
445
446 #[test]
447 fn qa_partial_overlap_gives_fractional_f1() {
448 let s = QaScorer
449 .score(&qa_task(), "the graph and session stores", Path::new("."))
450 .unwrap();
451 assert!(s.value > 0.0 && s.value < 1.0, "f1 was {}", s.value);
452 }
453
454 #[test]
455 fn qa_unrelated_answer_scores_zero() {
456 let s = QaScorer
457 .score(&qa_task(), "cats and weather forecasts", Path::new("."))
458 .unwrap();
459 assert_eq!(s.value, 0.0);
460 assert!(!s.passed);
461 }
462
463 #[test]
464 fn extract_code_unwraps_fence() {
465 assert_eq!(extract_code("```sh\necho hi\n```"), "echo hi");
466 assert_eq!(extract_code("plain text"), "plain text");
467 }
468
469 #[test]
470 fn code_scorer_rejects_unsafe_task_before_workspace_access() {
471 let task = Task {
472 id: "c".into(),
473 domain: Domain::Code,
474 prompt: "implement add".into(),
475 workspace: ".".into(),
476 retrieval_query: None,
477 answers: vec![],
478 target_file: Some("../solution.sh".into()),
479 test_cmd: Some("sh test.sh".into()),
480 };
481 assert!(
482 CodeScorer::default()
483 .score(&task, "ignored", Path::new("/missing/workspace"))
484 .is_err()
485 );
486 }
487
488 #[cfg(unix)]
489 #[test]
490 fn code_scorer_runs_unit_test() {
491 let ws = tempfile::tempdir().unwrap();
492 std::fs::write(
493 ws.path().join("test.sh"),
494 ". ./solution.sh\n[ \"$(add 2 3)\" = \"5\" ] || exit 1\n",
495 )
496 .unwrap();
497 std::fs::write(ws.path().join("solution.sh"), "add() { echo 0; }\n").unwrap();
498
499 let task = Task {
500 id: "c".into(),
501 domain: Domain::Code,
502 prompt: "implement add".into(),
503 workspace: "code".into(),
504 retrieval_query: None,
505 answers: vec![],
506 target_file: Some("solution.sh".into()),
507 test_cmd: Some("sh test.sh".into()),
508 };
509
510 let good = CodeScorer::default()
511 .score(&task, "add() { echo $(( $1 + $2 )); }", ws.path())
512 .unwrap();
513 assert!(good.passed, "correct solution should pass: {good:?}");
514
515 let bad = CodeScorer::default()
516 .score(&task, "add() { echo 99; }", ws.path())
517 .unwrap();
518 assert!(!bad.passed, "wrong solution should fail");
519 }
520}