1use serde::Serialize;
14use std::path::{Path, PathBuf};
15use std::process::Command;
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
19#[serde(rename_all = "lowercase")]
20pub enum Freshness {
21 Fresh,
23 Stale,
25 Unpinned,
27}
28
29#[derive(Debug, Clone, Serialize)]
30pub struct VerifyResult {
31 pub freshness: Freshness,
32 pub pinned: String,
34 pub dataset: Option<String>,
36 pub current_sha: String,
38 pub detail: String,
39}
40
41pub 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
50pub 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
56pub 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
67fn 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
97fn 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
115pub(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
125fn 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
135pub 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
148pub(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
163fn 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
183pub 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, ¤t_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
218pub 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 let existing_dataset = idx.and_then(|i| {
233 let after = lines[i].split_once("context_version:")?.1.trim();
234 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 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")); assert!(is_sha_like("ce013625030ba8dba906f756967f9e9ca394464a")); assert!(!is_sha_like("frozen-poc")); assert!(!is_sha_like("abc")); }
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 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 assert_eq!(classify(&sha_before, &sha_before), Freshness::Fresh);
321
322 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 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}