Skip to main content

warble_eval_runner/
context.rs

1//! MDL-version reverify — golden lifecycle (roadmap Phase 1.4 step 6).
2//!
3//! A golden's `context_version` pins the MDL+Knowledge it was confirmed against. When the bound MDL
4//! changes, the golden's ground truth may have silently rotted. This module
5//! computes the **git SHA of the bound MDL files** (host-side, content-addressed via
6//! `git hash-object` — no ContextLoader, Phase-2-independent), compares it to the
7//! golden's pin, and flags a mismatch as `stale`. Stale goldens can be re-stamped (accept the new
8//! MDL) or re-verified (re-run to see which cases the MDL change actually moved).
9//!
10//! Only the MDL semantics travel into the SHA (`*.yml`/`*.yaml`/`*.md` under the project), so a pure
11//! connection/credential edit that leaves the models untouched does not spuriously mark goldens stale.
12
13use serde::Serialize;
14use std::path::{Path, PathBuf};
15use std::process::Command;
16
17/// Whether a golden's pinned `context_version` still matches the bound MDL.
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
19#[serde(rename_all = "lowercase")]
20pub enum Freshness {
21    /// Pin is a SHA and matches the current MDL SHA (exact or abbreviated prefix).
22    Fresh,
23    /// Pin is a SHA but the MDL has since changed — ground truth may have rotted.
24    Stale,
25    /// Pin is symbolic (not a SHA), so it can't be checked; stamp it to start tracking.
26    Unpinned,
27}
28
29#[derive(Debug, Clone, Serialize)]
30pub struct VerifyResult {
31    pub freshness: Freshness,
32    /// The pin recorded in the golden's `context_version` (the part after `@`, or the whole value).
33    pub pinned: String,
34    /// The dataset prefix (the part before `@`), when present.
35    pub dataset: Option<String>,
36    /// The freshly computed MDL SHA.
37    pub current_sha: String,
38    pub detail: String,
39}
40
41/// Split a `context_version` (`<dataset>@<pin>`) into its dataset prefix and pin. With no `@`, the
42/// whole value is the pin and there is no dataset.
43pub fn parse_context_version(cv: &str) -> (Option<String>, String) {
44    match cv.split_once('@') {
45        Some((dataset, pin)) => (Some(dataset.to_string()), pin.to_string()),
46        None => (None, cv.to_string()),
47    }
48}
49
50/// A pin looks like a git SHA when it is 7–64 hex chars (git's abbreviated..full range).
51pub fn is_sha_like(pin: &str) -> bool {
52    let len = pin.len();
53    (7..=64).contains(&len) && pin.chars().all(|c| c.is_ascii_hexdigit())
54}
55
56/// Classify a pin against a freshly computed MDL SHA.
57pub fn classify(pin: &str, current_sha: &str) -> Freshness {
58    if !is_sha_like(pin) {
59        Freshness::Unpinned
60    } else if current_sha == pin || current_sha.starts_with(pin) {
61        Freshness::Fresh
62    } else {
63        Freshness::Stale
64    }
65}
66
67/// Collect the MDL files under `project` (`*.yml`/`*.yaml`/`*.md`), sorted by relative path, skipping
68/// runtime dirs (`.git`, `.claude`, `.venv`) that are not part of the semantic definition.
69fn mdl_files(project: &Path) -> Result<Vec<PathBuf>, String> {
70    let mut out = Vec::new();
71    collect(project, &mut out)?;
72    out.sort();
73    Ok(out)
74}
75
76fn collect(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), String> {
77    for entry in std::fs::read_dir(dir).map_err(|e| format!("read {}: {e}", dir.display()))? {
78        let entry = entry.map_err(|e| e.to_string())?;
79        let path = entry.path();
80        let name = entry.file_name();
81        let name = name.to_string_lossy();
82        if path.is_dir() {
83            if matches!(name.as_ref(), ".git" | ".claude" | ".venv" | "node_modules") {
84                continue;
85            }
86            collect(&path, out)?;
87        } else if matches!(
88            path.extension().and_then(|e| e.to_str()),
89            Some("yml") | Some("yaml") | Some("md")
90        ) {
91            out.push(path);
92        }
93    }
94    Ok(())
95}
96
97/// One `git hash-object <file>` blob SHA (content-addressed; works outside a repo, stable across
98/// machines — the property we want for a pin).
99fn blob_sha(file: &Path) -> Result<String, String> {
100    let output = Command::new("git")
101        .arg("hash-object")
102        .arg(file)
103        .output()
104        .map_err(|e| format!("git hash-object {}: {e}", file.display()))?;
105    if !output.status.success() {
106        return Err(format!(
107            "git hash-object {} failed: {}",
108            file.display(),
109            String::from_utf8_lossy(&output.stderr).trim()
110        ));
111    }
112    Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
113}
114
115/// Hash an arbitrary string to a stable 40-hex git blob SHA (content-addressed; no repo needed).
116/// Written via a temp file rather than a `--stdin` pipe, matching [`blob_sha`]. Shared by the MDL
117/// SHA, the agent-artifact SHA, and the trace-cache key hash — same content → same hash on any
118/// machine, which is exactly the property a cache key wants.
119pub(crate) fn hash_str(s: &str) -> Result<String, String> {
120    let tmp = tempfile::NamedTempFile::new().map_err(|e| format!("tempfile: {e}"))?;
121    std::fs::write(tmp.path(), s).map_err(|e| format!("write hash input: {e}"))?;
122    blob_sha(tmp.path())
123}
124
125/// Build a `<relpath> <blob-sha>\n` manifest over `files` (already sorted), relative to `root`.
126fn file_manifest(root: &Path, files: &[PathBuf]) -> Result<String, String> {
127    let mut manifest = String::new();
128    for file in files {
129        let rel = file.strip_prefix(root).unwrap_or(file);
130        manifest.push_str(&format!("{} {}\n", rel.display(), blob_sha(file)?));
131    }
132    Ok(manifest)
133}
134
135/// Compute a single stable SHA over all MDL files: hash each file's content (git blob SHA), build a
136/// sorted `<relpath> <sha>` manifest, and hash the manifest. Any content or path change moves it.
137pub fn compute_mdl_sha(project: &Path) -> Result<String, String> {
138    let files = mdl_files(project)?;
139    if files.is_empty() {
140        return Err(format!(
141            "no MDL files (*.yml/*.yaml/*.md) under {}",
142            project.display()
143        ));
144    }
145    hash_str(&file_manifest(project, &files)?)
146}
147
148/// Compute a stable SHA over every file under `dir` (all extensions, recursive), the same way
149/// [`compute_mdl_sha`] hashes MDL files. Used for the **agent-artifact SHA**: the dispatched agent
150/// dir (`.claude/agents/*.md`, `settings.json`, `.mcp.json`, …) fully determines the agent's
151/// behavior, so hashing it gives the `agent_sha` component of the trace-cache key — a change to any
152/// emitted file (prompt, tier binding, settings) moves the SHA and correctly misses the cache.
153pub(crate) fn compute_dir_sha(dir: &Path) -> Result<String, String> {
154    let mut files = Vec::new();
155    all_files(dir, &mut files)?;
156    if files.is_empty() {
157        return Err(format!("no files under {}", dir.display()));
158    }
159    files.sort();
160    hash_str(&file_manifest(dir, &files)?)
161}
162
163/// Collect every regular file under `dir` recursively, skipping the same runtime dirs as
164/// [`collect`] (`.git`, `.venv`, `node_modules`) so build/VCS noise stays out of the SHA.
165fn all_files(dir: &Path, out: &mut Vec<PathBuf>) -> Result<(), String> {
166    for entry in std::fs::read_dir(dir).map_err(|e| format!("read {}: {e}", dir.display()))? {
167        let entry = entry.map_err(|e| e.to_string())?;
168        let path = entry.path();
169        let name = entry.file_name();
170        let name = name.to_string_lossy();
171        if path.is_dir() {
172            if matches!(name.as_ref(), ".git" | ".venv" | "node_modules" | "target") {
173                continue;
174            }
175            all_files(&path, out)?;
176        } else {
177            out.push(path);
178        }
179    }
180    Ok(())
181}
182
183/// Verify a golden's `context_version` against the bound project's current MDL SHA.
184pub fn verify_context(
185    golden_context_version: Option<&str>,
186    project: &Path,
187) -> Result<VerifyResult, String> {
188    let current_sha = compute_mdl_sha(project)?;
189    let cv = golden_context_version.unwrap_or("");
190    let (dataset, pinned) = parse_context_version(cv);
191    let freshness = if cv.is_empty() {
192        Freshness::Unpinned
193    } else {
194        classify(&pinned, &current_sha)
195    };
196    let detail = match freshness {
197        Freshness::Fresh => format!("pin '{pinned}' matches current MDL SHA"),
198        Freshness::Stale => format!(
199            "pin '{pinned}' != current MDL SHA {current_sha} — MDL changed; ground truth may be stale"
200        ),
201        Freshness::Unpinned => {
202            if cv.is_empty() {
203                format!("golden has no context_version; current MDL SHA is {current_sha}")
204            } else {
205                format!("pin '{pinned}' is symbolic (not a SHA); current MDL SHA is {current_sha}")
206            }
207        }
208    };
209    Ok(VerifyResult {
210        freshness,
211        pinned,
212        dataset,
213        current_sha,
214        detail,
215    })
216}
217
218/// Rewrite a golden YAML's `context_version:` line to `<dataset>@<sha>`, preserving the dataset
219/// prefix when the golden already had one (else falling back to `fallback_dataset`). Line-based so
220/// comments and formatting survive. Returns the new document text.
221pub fn stamp_context_version(
222    golden_text: &str,
223    sha: &str,
224    fallback_dataset: Option<&str>,
225) -> Result<String, String> {
226    let mut lines: Vec<String> = golden_text.lines().map(str::to_string).collect();
227    let idx = lines
228        .iter()
229        .position(|l| l.trim_start().starts_with("context_version:"));
230
231    // Derive the dataset prefix from the existing value, else the golden's `dataset:`, else none.
232    let existing_dataset = idx.and_then(|i| {
233        let after = lines[i].split_once("context_version:")?.1.trim();
234        // strip trailing inline comment
235        let value = after
236            .split_once('#')
237            .map(|(v, _)| v.trim())
238            .unwrap_or(after);
239        parse_context_version(value).0
240    });
241    let dataset = existing_dataset.or_else(|| fallback_dataset.map(str::to_string));
242    let new_value = match &dataset {
243        Some(d) => format!("{d}@{sha}"),
244        None => sha.to_string(),
245    };
246    let new_line = format!(
247        "context_version: {new_value}      # stamped by `warble eval verify-context --stamp`"
248    );
249
250    match idx {
251        Some(i) => lines[i] = new_line,
252        None => {
253            // Insert after `dataset:` if present, else at the top.
254            let insert_at = lines
255                .iter()
256                .position(|l| l.trim_start().starts_with("dataset:"))
257                .map(|i| i + 1)
258                .unwrap_or(0);
259            lines.insert(insert_at, new_line);
260        }
261    }
262    Ok(format!("{}\n", lines.join("\n")))
263}
264
265#[cfg(test)]
266mod tests {
267    use super::*;
268    use std::fs;
269
270    #[test]
271    fn parse_splits_dataset_and_pin() {
272        assert_eq!(
273            parse_context_version("jaffle_shop@a1b2c3d"),
274            (Some("jaffle_shop".into()), "a1b2c3d".into())
275        );
276        assert_eq!(parse_context_version("bareword"), (None, "bareword".into()));
277    }
278
279    #[test]
280    fn sha_like_detection() {
281        assert!(is_sha_like("a1b2c3d")); // 7 hex
282        assert!(is_sha_like("ce013625030ba8dba906f756967f9e9ca394464a")); // 40 hex
283        assert!(!is_sha_like("frozen-poc")); // has '-'
284        assert!(!is_sha_like("abc")); // too short
285    }
286
287    #[test]
288    fn classify_fresh_stale_unpinned() {
289        let sha = "ce013625030ba8dba906f756967f9e9ca394464a";
290        assert_eq!(classify(sha, sha), Freshness::Fresh);
291        assert_eq!(
292            classify("ce01362", sha),
293            Freshness::Fresh,
294            "abbrev prefix matches"
295        );
296        assert_eq!(classify("deadbeef", sha), Freshness::Stale);
297        assert_eq!(classify("frozen-poc", sha), Freshness::Unpinned);
298    }
299
300    #[test]
301    fn mdl_change_moves_the_sha_and_marks_stale() {
302        // The deliverable: an MDL edit must move the SHA → stale detection fires.
303        let dir = tempfile::tempdir().unwrap();
304        fs::create_dir_all(dir.path().join("models")).unwrap();
305        fs::write(
306            dir.path().join("wren_project.yml"),
307            "catalog: c\nschema: s\n",
308        )
309        .unwrap();
310        fs::write(
311            dir.path().join("models/orders.yml"),
312            "name: orders\ncolumns: [id, amount]\n",
313        )
314        .unwrap();
315
316        let sha_before = compute_mdl_sha(dir.path()).unwrap();
317        assert_eq!(sha_before.len(), 40, "40-hex git sha");
318
319        // A pin equal to the pre-change SHA is Fresh…
320        assert_eq!(classify(&sha_before, &sha_before), Freshness::Fresh);
321
322        // …edit an MDL file…
323        fs::write(
324            dir.path().join("models/orders.yml"),
325            "name: orders\ncolumns: [id, amount, discount]\n",
326        )
327        .unwrap();
328        let sha_after = compute_mdl_sha(dir.path()).unwrap();
329        assert_ne!(sha_before, sha_after, "MDL change must move the SHA");
330
331        // …and the old pin is now Stale against the new MDL.
332        let verify = verify_context(Some(&format!("jaffle@{sha_before}")), dir.path()).unwrap();
333        assert_eq!(verify.freshness, Freshness::Stale);
334        assert_eq!(verify.current_sha, sha_after);
335    }
336
337    #[test]
338    fn adding_a_model_file_moves_the_sha() {
339        let dir = tempfile::tempdir().unwrap();
340        fs::write(dir.path().join("a.yml"), "x: 1\n").unwrap();
341        let before = compute_mdl_sha(dir.path()).unwrap();
342        fs::write(dir.path().join("b.yml"), "y: 2\n").unwrap();
343        let after = compute_mdl_sha(dir.path()).unwrap();
344        assert_ne!(before, after, "adding an MDL file changes the manifest SHA");
345    }
346
347    #[test]
348    fn stamp_rewrites_pin_preserving_dataset_and_comments() {
349        let golden = "# header\ndataset: jaffle_shop\ncontext_version: jaffle_shop@frozen-poc   # pin\ncases: []\n";
350        let stamped = stamp_context_version(golden, "abc1234def", None).unwrap();
351        assert!(stamped.contains("context_version: jaffle_shop@abc1234def"));
352        assert!(stamped.contains("# header"), "comments preserved");
353        assert!(stamped.contains("cases: []"));
354        assert!(!stamped.contains("frozen-poc"), "old pin replaced");
355    }
356
357    #[test]
358    fn stamp_inserts_when_absent_using_fallback_dataset() {
359        let golden = "dataset: shop\ncases: []\n";
360        let stamped = stamp_context_version(golden, "abc1234", Some("shop")).unwrap();
361        assert!(stamped.contains("context_version: shop@abc1234"));
362    }
363}