lean-ctx 3.9.20

Local Context SDK for AI agents. Select, shape, reuse, recover, and measure context before inference.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Deterministic scorers (#236): objective, reproducible scoring of a model answer.
//!
//! * [`QaScorer`] — SQuAD-style normalization → exact-match, token-overlap F1 and containment.
//! * [`CodeScorer`] — copies the workspace into a throwaway sandbox, writes the model output to
//!   the target file, runs the task's unit-test command and reports pass/fail by exit code.
//!
//! Both are fully deterministic given a fixed model output, which is what lets the harness
//! prove a non-regression rather than estimate one.

use std::path::Path;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};

use super::suite::{Domain, Task};

const MAX_EVALUATION_FIXTURE_FILES: usize = 128;
const MAX_EVALUATION_FIXTURE_BYTES: u64 = 4 * 1024 * 1024;
const MAX_EVALUATION_FIXTURE_DEPTH: usize = 16;

/// A scored answer. `value` is the continuous metric in `[0,1]`; `passed` is the binary verdict
/// used for win/tie/loss accounting.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Score {
    pub value: f64,
    pub passed: bool,
    /// `f1`, `exact_match` or `unit_test`.
    pub metric: String,
    /// Short human-readable explanation (e.g. `em=1 f1=1.00 contain=1`).
    pub detail: String,
}

/// Anything that can deterministically score a model answer for a task.
pub trait Scorer {
    fn score(&self, task: &Task, output: &str, workspace: &Path) -> Result<Score>;
}

/// Dispatches to the scorer for the task's domain.
pub fn score_task(task: &Task, output: &str, workspace: &Path) -> Result<Score> {
    match task.domain {
        Domain::Qa => QaScorer.score(task, output, workspace),
        Domain::Code => CodeScorer::default().score(task, output, workspace),
    }
}

// ---------------------------------------------------------------------------
// QA scorer
// ---------------------------------------------------------------------------

/// SQuAD-style QA scorer (exact-match / F1 / containment over a set of gold answers).
pub struct QaScorer;

impl Scorer for QaScorer {
    fn score(&self, task: &Task, output: &str, _workspace: &Path) -> Result<Score> {
        let pred = normalize(output);
        let pred_tokens: Vec<&str> = pred.split_whitespace().collect();

        let mut best_em = false;
        let mut best_contain = false;
        let mut best_f1 = 0.0f64;
        for gold in &task.answers {
            let g = normalize(gold);
            if g.is_empty() {
                continue;
            }
            let g_tokens: Vec<&str> = g.split_whitespace().collect();
            best_em |= pred == g;
            best_contain |= !g.is_empty() && pred.contains(&g);
            best_f1 = best_f1.max(token_f1(&pred_tokens, &g_tokens));
        }

        Ok(Score {
            value: best_f1,
            passed: best_em || best_contain,
            metric: "f1".to_string(),
            detail: format!(
                "em={} f1={best_f1:.2} contain={}",
                u8::from(best_em),
                u8::from(best_contain)
            ),
        })
    }
}

/// SQuAD token-overlap F1 between a prediction and a single gold answer.
/// Reusable building block for other harnesses (e.g. the LoCoMo memory bench, #291).
pub fn qa_f1(pred: &str, gold: &str) -> f64 {
    let p = normalize(pred);
    let g = normalize(gold);
    let pt: Vec<&str> = p.split_whitespace().collect();
    let gt: Vec<&str> = g.split_whitespace().collect();
    token_f1(&pt, &gt)
}

/// SQuAD exact match between a prediction and a gold answer (after normalization).
pub fn qa_exact_match(pred: &str, gold: &str) -> bool {
    normalize(pred) == normalize(gold)
}

/// True iff the normalized gold answer is contained in the normalized prediction.
pub fn qa_contains(pred: &str, gold: &str) -> bool {
    let g = normalize(gold);
    !g.is_empty() && normalize(pred).contains(&g)
}

/// SQuAD normalization: lowercase, drop punctuation, drop articles, collapse whitespace.
fn normalize(s: &str) -> String {
    let lowered = s.to_lowercase();
    let cleaned: String = lowered
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { ' ' })
        .collect();
    cleaned
        .split_whitespace()
        .filter(|w| !matches!(*w, "a" | "an" | "the"))
        .collect::<Vec<_>>()
        .join(" ")
}

/// Token-overlap F1 over multisets (SQuAD definition).
fn token_f1(pred: &[&str], gold: &[&str]) -> f64 {
    if pred.is_empty() && gold.is_empty() {
        return 1.0;
    }
    if pred.is_empty() || gold.is_empty() {
        return 0.0;
    }
    let mut gold_counts: std::collections::HashMap<&str, i64> = std::collections::HashMap::new();
    for &t in gold {
        *gold_counts.entry(t).or_insert(0) += 1;
    }
    let mut common = 0i64;
    let mut pred_counts: std::collections::HashMap<&str, i64> = std::collections::HashMap::new();
    for &t in pred {
        let entry = pred_counts.entry(t).or_insert(0);
        *entry += 1;
        if *entry <= gold_counts.get(t).copied().unwrap_or(0) {
            common += 1;
        }
    }
    if common == 0 {
        return 0.0;
    }
    let precision = common as f64 / pred.len() as f64;
    let recall = common as f64 / gold.len() as f64;
    2.0 * precision * recall / (precision + recall)
}

// ---------------------------------------------------------------------------
// Code scorer
// ---------------------------------------------------------------------------

/// Runs the task's unit-test command against the model output inside a sandbox copy.
pub struct CodeScorer {
    /// Wall-clock cap for the test command.
    pub timeout: Duration,
    /// New benchmark-spec code evaluators require process and filesystem isolation.
    require_isolation: bool,
}

impl Default for CodeScorer {
    fn default() -> Self {
        // Seconds granularity is the natural unit for a test timeout.
        #[allow(clippy::duration_suboptimal_units)]
        Self {
            timeout: Duration::from_secs(60),
            require_isolation: false,
        }
    }
}

impl CodeScorer {
    /// Runs a code fixture with the platform sandbox enabled, or fails closed
    /// when the host cannot provide the required isolation.
    pub fn isolated() -> Self {
        Self {
            require_isolation: true,
            ..Self::default()
        }
    }
}

impl Scorer for CodeScorer {
    fn score(&self, task: &Task, output: &str, workspace: &Path) -> Result<Score> {
        if let Err(reason) = task.validate_code_evaluation() {
            bail!("invalid task {}: {reason}", task.id);
        }
        let metadata = std::fs::symlink_metadata(workspace)
            .with_context(|| format!("inspecting workspace {}", workspace.display()))?;
        if metadata.file_type().is_symlink() {
            bail!(
                "refusing symlinked code-evaluation workspace {}",
                workspace.display()
            );
        }
        if !metadata.is_dir() {
            bail!("code-evaluation workspace is not a directory");
        }
        let workspace = std::fs::canonicalize(workspace)
            .with_context(|| format!("canonicalizing workspace {}", workspace.display()))?;

        let target = task
            .target_file
            .as_deref()
            .ok_or_else(|| anyhow!("code task {} has no target_file", task.id))?;
        let test_cmd = task
            .test_cmd
            .as_deref()
            .ok_or_else(|| anyhow!("code task {} has no test_cmd", task.id))?;

        let sandbox = tempfile::tempdir().context("creating sandbox")?;
        let mut copy_budget = CopyBudget::default();
        copy_dir_all(&workspace, sandbox.path(), 0, &mut copy_budget)
            .with_context(|| format!("copying workspace {}", workspace.display()))?;

        let target_path = sandbox.path().join(target);
        if let Some(parent) = target_path.parent() {
            std::fs::create_dir_all(parent).ok();
        }
        std::fs::write(&target_path, extract_code(output))
            .with_context(|| format!("writing solution to {}", target_path.display()))?;

        let passed = run_with_timeout(
            test_cmd,
            sandbox.path(),
            self.timeout,
            self.require_isolation,
        )?;
        Ok(Score {
            value: f64::from(u8::from(passed)),
            passed,
            metric: "unit_test".to_string(),
            detail: format!("test_cmd={test_cmd:?} passed={passed}"),
        })
    }
}

/// Strips a single Markdown code fence if the model wrapped its answer in one; otherwise returns
/// the trimmed text. Keeps the sandboxed file syntactically valid.
fn extract_code(output: &str) -> String {
    let trimmed = output.trim();
    if let Some(rest) = trimmed.strip_prefix("```") {
        // Drop the optional language tag on the opening fence, then everything up to the close.
        let after_lang = rest.find('\n').map_or(rest, |i| &rest[i + 1..]);
        if let Some(end) = after_lang.rfind("```") {
            return after_lang[..end].trim_end().to_string();
        }
    }
    trimmed.to_string()
}

#[derive(Default)]
struct CopyBudget {
    files: usize,
    bytes: u64,
}

/// Recursively copies a deliberately small, regular-file-only fixture into
/// `dst` (which must already exist).  A benchmark evaluator never needs a full
/// repository checkout, device, FIFO, symlink, or unbounded file tree.
fn copy_dir_all(
    src: &Path,
    dst: &Path,
    depth: usize,
    budget: &mut CopyBudget,
) -> std::io::Result<()> {
    if depth > MAX_EVALUATION_FIXTURE_DEPTH {
        return Err(std::io::Error::other(
            "code-evaluation fixture is nested too deeply",
        ));
    }
    for entry in std::fs::read_dir(src)? {
        let entry = entry?;
        let from = entry.path();
        let to = dst.join(entry.file_name());
        let file_type = entry.file_type()?;
        if file_type.is_symlink() {
            return Err(std::io::Error::other(format!(
                "refusing symlink in code-evaluation workspace: {}",
                from.display()
            )));
        }
        if file_type.is_dir() {
            std::fs::create_dir_all(&to)?;
            copy_dir_all(&from, &to, depth + 1, budget)?;
        } else if file_type.is_file() {
            let file_bytes = entry.metadata()?.len();
            budget.files = budget.files.saturating_add(1);
            budget.bytes = budget.bytes.saturating_add(file_bytes);
            if budget.files > MAX_EVALUATION_FIXTURE_FILES
                || budget.bytes > MAX_EVALUATION_FIXTURE_BYTES
            {
                return Err(std::io::Error::other(
                    "code-evaluation fixture exceeds file or byte limit",
                ));
            }
            std::fs::copy(&from, &to)?;
        } else {
            return Err(std::io::Error::other(format!(
                "refusing non-regular entry in code-evaluation workspace: {}",
                from.display()
            )));
        }
    }
    Ok(())
}

/// Runs `cmd` via the POSIX shell in `dir`, returning `true` iff it exits 0 within `timeout`.
fn run_with_timeout(
    cmd: &str,
    dir: &Path,
    timeout: Duration,
    require_isolation: bool,
) -> Result<bool> {
    // macOS temporary directories are commonly exposed through `/var`, a
    // symlink to `/private/var`. sandbox-exec evaluates canonical paths, so
    // grant and enter the same canonical fixture directory or a valid fixture
    // can be denied as outside the sandbox.
    let execution_dir = if require_isolation {
        std::fs::canonicalize(dir)
            .with_context(|| format!("canonicalizing isolated fixture {}", dir.display()))?
    } else {
        dir.to_path_buf()
    };
    let mut command = if require_isolation {
        isolated_test_command(cmd, &execution_dir)?
    } else {
        let mut command = Command::new("sh");
        command.arg("-c").arg(cmd);
        command
    };
    let stderr_path = require_isolation.then(|| execution_dir.join(".leanctx-evaluator-stderr"));
    if let Some(path) = &stderr_path {
        let stderr = std::fs::File::create(path).with_context(|| {
            format!(
                "creating isolated evaluator diagnostics at {}",
                path.display()
            )
        })?;
        command.stderr(Stdio::from(stderr));
    } else {
        command.stderr(Stdio::null());
    }
    let mut child = command
        .current_dir(&execution_dir)
        .stdout(Stdio::null())
        .stdin(Stdio::null())
        .spawn()
        .with_context(|| format!("spawning test command: {cmd}"))?;

    let start = Instant::now();
    loop {
        if let Some(status) = child.try_wait()? {
            if status.success() {
                return Ok(true);
            }
            if let Some(path) = stderr_path {
                let diagnostics = std::fs::read_to_string(path).unwrap_or_default();
                if !diagnostics.trim().is_empty() {
                    anyhow::bail!(
                        "isolated evaluator could not execute test command: {}",
                        diagnostics.trim()
                    );
                }
            }
            return Ok(false);
        }
        if start.elapsed() > timeout {
            let _ = child.kill();
            let _ = child.wait();
            return Ok(false);
        }
        std::thread::sleep(Duration::from_millis(25));
    }
}

#[cfg(target_os = "macos")]
fn isolated_test_command(cmd: &str, dir: &Path) -> Result<Command> {
    let directory = dir
        .to_str()
        .ok_or_else(|| anyhow!("code-evaluation directory is not valid UTF-8"))?
        .replace('\\', "\\\\")
        .replace('"', "\\\"");
    // The evaluator owns the copied fixture. The sandbox can read that fixture
    // plus the system shell/runtime only; it cannot read the caller's home,
    // repository, or arbitrary user-readable files. The fixture may fork a
    // bounded shell child and receives strict CPU, file-size, and descriptor
    // limits. macOS applies `RLIMIT_NPROC` per user, so setting a tiny process
    // limit would deny a valid fixture whenever the user already has more
    // processes than that limit.
    let profile = format!(
        "(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*)"
    );
    let mut command = Command::new("/usr/bin/sandbox-exec");
    command.args([
        "-p",
        &profile,
        "/bin/sh",
        "-c",
        "ulimit -t 5 -f 8192 -n 16; exec /bin/sh -c \"$1\"",
        "leanctx-code-evaluator",
        cmd,
    ]);
    Ok(command)
}

#[cfg(not(target_os = "macos"))]
fn isolated_test_command(_cmd: &str, _dir: &Path) -> Result<Command> {
    Err(anyhow!(
        "isolated code evaluation requires a supported local sandbox; this host has none"
    ))
}

#[cfg(test)]
mod tests {
    use super::*;

    fn qa_task() -> Task {
        Task {
            id: "q".into(),
            domain: Domain::Qa,
            prompt: "p".into(),
            workspace: "w".into(),
            retrieval_query: None,
            answers: vec!["bm25 graph knowledge session".into()],
            target_file: None,
            test_cmd: None,
        }
    }

    #[test]
    fn qa_exact_match_scores_one() {
        let s = QaScorer
            .score(
                &qa_task(),
                "BM25, graph, knowledge, session.",
                Path::new("."),
            )
            .unwrap();
        assert!(s.passed);
        assert_eq!(s.value, 1.0);
    }

    #[test]
    fn qa_partial_overlap_gives_fractional_f1() {
        let s = QaScorer
            .score(&qa_task(), "the graph and session stores", Path::new("."))
            .unwrap();
        assert!(s.value > 0.0 && s.value < 1.0, "f1 was {}", s.value);
    }

    #[test]
    fn qa_unrelated_answer_scores_zero() {
        let s = QaScorer
            .score(&qa_task(), "cats and weather forecasts", Path::new("."))
            .unwrap();
        assert_eq!(s.value, 0.0);
        assert!(!s.passed);
    }

    #[test]
    fn extract_code_unwraps_fence() {
        assert_eq!(extract_code("```sh\necho hi\n```"), "echo hi");
        assert_eq!(extract_code("plain text"), "plain text");
    }

    #[test]
    fn code_scorer_rejects_unsafe_task_before_workspace_access() {
        let task = Task {
            id: "c".into(),
            domain: Domain::Code,
            prompt: "implement add".into(),
            workspace: ".".into(),
            retrieval_query: None,
            answers: vec![],
            target_file: Some("../solution.sh".into()),
            test_cmd: Some("sh test.sh".into()),
        };
        assert!(
            CodeScorer::default()
                .score(&task, "ignored", Path::new("/missing/workspace"))
                .is_err()
        );
    }

    #[cfg(unix)]
    #[test]
    fn code_scorer_runs_unit_test() {
        let ws = tempfile::tempdir().unwrap();
        std::fs::write(
            ws.path().join("test.sh"),
            ". ./solution.sh\n[ \"$(add 2 3)\" = \"5\" ] || exit 1\n",
        )
        .unwrap();
        std::fs::write(ws.path().join("solution.sh"), "add() { echo 0; }\n").unwrap();

        let task = Task {
            id: "c".into(),
            domain: Domain::Code,
            prompt: "implement add".into(),
            workspace: "code".into(),
            retrieval_query: None,
            answers: vec![],
            target_file: Some("solution.sh".into()),
            test_cmd: Some("sh test.sh".into()),
        };

        let good = CodeScorer::default()
            .score(&task, "add() { echo $(( $1 + $2 )); }", ws.path())
            .unwrap();
        assert!(good.passed, "correct solution should pass: {good:?}");

        let bad = CodeScorer::default()
            .score(&task, "add() { echo 99; }", ws.path())
            .unwrap();
        assert!(!bad.passed, "wrong solution should fail");
    }
}