返回 CodeWhale
golden.rs
根目录 / crates / tui / src / conformance / golden.rs
1 //! Fixture discovery, golden comparison, the update mode, and the masking
2 //! rules every family shares. Masking is deliberately small and named: a mask
3 //! hides a fact that genuinely varies between hosts or runs (temp paths,
4 //! UUIDs, clocks), never a fact the migration could change by accident.
5
6 use std::collections::{BTreeMap, HashMap};
7 use std::path::{Path, PathBuf};
8
9 use serde_json::Value;
10
11 use crate::test_support::{EnvVarGuard, TestEnvLock, lock_test_env};
12 pub(super) use codewhale_engine::test_support::{UPDATE_ENV, check_golden};
13 use codewhale_engine::tools::spec::ToolError;
14
15 pub(super) fn fixture_root() -> PathBuf {
16 Path::new(env!("CARGO_MANIFEST_DIR"))
17 .join("tests")
18 .join("fixtures")
19 .join("conformance")
20 }
21
22 pub(super) fn family_dir(family: &str) -> PathBuf {
23 fixture_root().join(family)
24 }
25
26 /// Case names (`<name>.case.json`) in one family, sorted. Panics on an empty
27 /// family: a filter that silently runs zero cases is not a pass.
28 pub(super) fn case_names(family: &str) -> Vec<String> {
29 let dir = family_dir(family);
30 let mut names: Vec<String> = std::fs::read_dir(&dir)
31 .unwrap_or_else(|error| panic!("read fixture dir {}: {error}", dir.display()))
32 .filter_map(|entry| {
33 let name = entry.ok()?.file_name().into_string().ok()?;
34 name.strip_suffix(".case.json").map(str::to_string)
35 })
36 .collect();
37 names.sort();
38 assert!(
39 !names.is_empty(),
40 "conformance family `{family}` has no *.case.json fixtures in {}",
41 dir.display()
42 );
43 names
44 }
45
46 pub(super) fn read_case(family: &str, name: &str) -> Value {
47 let path = family_dir(family).join(format!("{name}.case.json"));
48 let text = std::fs::read_to_string(&path)
49 .unwrap_or_else(|error| panic!("read {}: {error}", path.display()));
50 serde_json::from_str(&text).unwrap_or_else(|error| panic!("parse {}: {error}", path.display()))
51 }
52
53 /// A harness deadline is missing evidence, never a provider outcome or a
54 /// recordable golden. Keep this boundary shared by every asynchronous family.
55 pub(super) async fn complete_within<T>(
56 operation: &str,
57 deadline: std::time::Duration,
58 future: impl std::future::Future<Output = T>,
59 ) -> Result<T, String> {
60 tokio::time::timeout(deadline, future)
61 .await
62 .map_err(|_| format!("harness timeout: {operation} did not complete within {deadline:?}"))
63 }
64
65 /// Rebuild every object with keys in sorted order. Used where map order is an
66 /// implementation accident (HashMap-backed metadata); the prompt family does
67 /// not use it, because there key order is part of the cached prefix bytes.
68 pub(super) fn canonical(value: &Value) -> Value {
69 match value {
70 Value::Object(map) => {
71 let sorted: BTreeMap<&String, &Value> = map.iter().collect();
72 Value::Object(
73 sorted
74 .into_iter()
75 .map(|(key, value)| (key.clone(), canonical(value)))
76 .collect(),
77 )
78 }
79 Value::Array(items) => Value::Array(items.iter().map(canonical).collect()),
80 other => other.clone(),
81 }
82 }
83
84 /// One compact JSON document per line, trailing newline.
85 pub(super) fn jsonl(lines: &[Value]) -> String {
86 let mut out = String::new();
87 for line in lines {
88 out.push_str(&serde_json::to_string(line).expect("serialize golden line"));
89 out.push('\n');
90 }
91 out
92 }
93
94 pub(super) fn pretty(value: &Value) -> String {
95 let mut out = serde_json::to_string_pretty(value).expect("serialize golden");
96 out.push('\n');
97 out
98 }
99
100 /// Replaces host- and run-specific substrings in every string of a JSON tree.
101 ///
102 /// - literal path prefixes (workspace, home) → `<WORKSPACE>` / `<HOME>`,
103 /// including their canonicalized spellings (`/private/var` on macOS);
104 /// - UUIDs → `<uuid:N>`, numbered by first appearance so that two events
105 /// naming the same id still visibly agree;
106 /// - RFC 3339 timestamps → `<timestamp>` (applied first);
107 /// - values of the named volatile keys (durations, clocks) → `"<masked>"`.
108 pub(super) struct Masker {
109 literals: Vec<(String, String)>,
110 volatile_keys: &'static [&'static str],
111 uuids: HashMap<String, String>,
112 uuid_re: regex::Regex,
113 timestamp_re: regex::Regex,
114 }
115
116 impl Masker {
117 pub(super) fn new(volatile_keys: &'static [&'static str]) -> Self {
118 Self {
119 literals: Vec::new(),
120 volatile_keys,
121 uuids: HashMap::new(),
122 uuid_re: regex::Regex::new(
123 r"[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}",
124 )
125 .expect("uuid regex"),
126 timestamp_re: regex::Regex::new(
127 r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})",
128 )
129 .expect("timestamp regex"),
130 }
131 }
132
133 /// Mask `path` (and its canonical spelling) as `label`. Longer literals
134 /// are applied first so a home nested in a workspace cannot half-match.
135 pub(super) fn path(mut self, path: &Path, label: &str) -> Self {
136 let mut spellings = vec![path.to_string_lossy().into_owned()];
137 if let Ok(canonical) = path.canonicalize() {
138 spellings.push(canonical.to_string_lossy().into_owned());
139 }
140 for spelling in spellings {
141 if !spelling.is_empty() && !self.literals.iter().any(|(known, _)| *known == spelling) {
142 self.literals.push((spelling, label.to_string()));
143 }
144 }
145 self.literals
146 .sort_by(|(left, _), (right, _)| right.len().cmp(&left.len()).then(left.cmp(right)));
147 self
148 }
149
150 /// Mask an arbitrary literal (a random session id, say).
151 pub(super) fn literal(mut self, literal: &str, label: &str) -> Self {
152 if !literal.is_empty() {
153 self.literals.push((literal.to_string(), label.to_string()));
154 self.literals.sort_by(|(left, _), (right, _)| {
155 right.len().cmp(&left.len()).then(left.cmp(right))
156 });
157 }
158 self
159 }
160
161 pub(super) fn text(&mut self, text: &str) -> String {
162 // Timestamps first: a literal (today's date, say) must not split one.
163 let mut out = self
164 .timestamp_re
165 .replace_all(text, "<timestamp>")
166 .into_owned();
167 for (literal, label) in &self.literals {
168 if out.contains(literal.as_str()) {
169 out = out.replace(literal.as_str(), label);
170 }
171 }
172 let uuids = &mut self.uuids;
173 self.uuid_re
174 .replace_all(&out, |captures: &regex::Captures<'_>| {
175 let raw = captures[0].to_ascii_lowercase();
176 let next = uuids.len() + 1;
177 uuids
178 .entry(raw)
179 .or_insert_with(|| format!("<uuid:{next}>"))
180 .clone()
181 })
182 .into_owned()
183 }
184
185 pub(super) fn value(&mut self, value: &mut Value) {
186 match value {
187 Value::String(text) => *text = self.text(text),
188 Value::Array(items) => {
189 for item in items {
190 self.value(item);
191 }
192 }
193 Value::Object(map) => {
194 for (key, item) in map.iter_mut() {
195 if self.volatile_keys.contains(&key.as_str()) && !item.is_null() {
196 *item = Value::String("<masked>".to_string());
197 } else {
198 self.value(item);
199 }
200 }
201 }
202 _ => {}
203 }
204 }
205 }
206
207 /// Stable snake_case name of a `ToolError` variant. The golden also pins its
208 /// full detail bytes; migration does not weaken either part of the contract.
209 pub(super) fn tool_error_kind(error: &ToolError) -> &'static str {
210 match error {
211 ToolError::InvalidInput { .. } => "invalid_input",
212 ToolError::MissingField { .. } => "missing_field",
213 ToolError::PathEscape { .. } => "path_escape",
214 ToolError::ExecutionFailed { .. } => "execution_failed",
215 ToolError::Timeout { .. } => "timeout",
216 ToolError::Cancelled { .. } => "cancelled",
217 ToolError::NotAvailable { .. } => "not_available",
218 ToolError::PermissionDenied { .. } => "permission_denied",
219 }
220 }
221
222 /// A hermetic home + workspace for one case. Holds the process test
223 /// env lock for its lifetime; field order is drop order (guards restore the
224 /// environment before the lock is released).
225 pub(super) struct Sandbox {
226 _guards: Vec<EnvVarGuard>,
227 _lock: TestEnvLock,
228 pub(super) home: std::path::PathBuf,
229 pub(super) workspace: std::path::PathBuf,
230 root: tempfile::TempDir,
231 }
232
233 impl Sandbox {
234 pub(super) fn new(case: &Value) -> Self {
235 let lock = lock_test_env();
236 let root = tempfile::tempdir().expect("tempdir");
237 let home = root.path().join("home");
238 let workspace = root.path().join("workspace");
239 std::fs::create_dir_all(&home).expect("home");
240 std::fs::create_dir_all(&workspace).expect("workspace");
241 let guards = vec![
242 EnvVarGuard::set("HOME", &home),
243 EnvVarGuard::set("USERPROFILE", &home),
244 EnvVarGuard::set("CODEWHALE_HOME", home.join(".codewhale")),
245 // Model-visible host facts that would otherwise follow the
246 // developer's shell and locale.
247 EnvVarGuard::set("SHELL", "/bin/bash"),
248 EnvVarGuard::set("LC_ALL", "en_US.UTF-8"),
249 EnvVarGuard::set("LANG", "en_US.UTF-8"),
250 EnvVarGuard::remove("LC_MESSAGES"),
251 ];
252 write_workspace(&workspace, case);
253 if case["trusted_workspace"].as_bool() == Some(true) {
254 // Repository instructions, commands and skills load only here.
255 crate::test_support::trust_workspace(&workspace);
256 }
257 Self {
258 _guards: guards,
259 _lock: lock,
260 home,
261 workspace,
262 root,
263 }
264 }
265
266 pub(super) fn masker(&self, volatile_keys: &'static [&'static str]) -> Masker {
267 // `<turn_meta>` states the local date; it is a clock, not a contract.
268 let today = chrono::Local::now().format("%Y-%m-%d").to_string();
269 Masker::new(volatile_keys)
270 .path(&self.workspace, "<WORKSPACE>")
271 .path(&self.home, "<HOME>")
272 .path(self.root.path(), "<TMP>")
273 .literal(&today, "<today>")
274 }
275 }
276
277 pub(super) fn write_workspace(workspace: &Path, case: &Value) {
278 if let Some(files) = case.get("workspace_files").and_then(Value::as_object) {
279 for (relative, content) in files {
280 let path = workspace.join(relative);
281 if let Some(parent) = path.parent() {
282 std::fs::create_dir_all(parent).expect("create fixture dir");
283 }
284 std::fs::write(
285 &path,
286 content.as_str().expect("workspace file content is text"),
287 )
288 .expect("write fixture file");
289 }
290 }
291 }
292
293 /// Collects per-case failures so one run reports every drifted case.
294 #[derive(Default)]
295 pub(super) struct Failures(Vec<String>);
296
297 impl Failures {
298 pub(super) fn contains(&self, message: &str) -> bool {
299 self.0.iter().any(|failure| failure.contains(message))
300 }
301 pub(super) fn record(&mut self, case: &str, result: Result<(), String>) {
302 if let Err(message) = result {
303 self.0.push(format!("[{case}] {message}"));
304 }
305 }
306
307 pub(super) fn push(&mut self, case: &str, message: impl Into<String>) {
308 self.0.push(format!("[{case}] {}", message.into()));
309 }
310
311 pub(super) fn finish(self, family: &str, cases: usize) {
312 assert!(cases > 0, "conformance family `{family}` ran no cases");
313 assert!(
314 self.0.is_empty(),
315 "conformance family `{family}`: {} failure(s) across {cases} case(s)\n\n{}",
316 self.0.len(),
317 self.0.join("\n\n")
318 );
319 eprintln!("conformance family `{family}`: {cases} case(s) matched");
320 }
321 }
322
323 #[test]
324 fn golden_comparison_rejects_changed_bytes_and_missing_output() {
325 let _lock = lock_test_env();
326 let _update = EnvVarGuard::set(UPDATE_ENV, "0");
327 let dir = tempfile::tempdir().expect("temporary golden");
328 let path = dir.path().join("case.golden.txt");
329 std::fs::write(&path, "expected\n").expect("write golden");
330 assert!(check_golden(&path, "expected\n").is_ok());
331 assert!(
332 check_golden(&path, "different\n")
333 .unwrap_err()
334 .contains("golden drift")
335 );
336 assert!(check_golden(&path, "expected\r\n").is_err());
337 assert!(check_golden(&dir.path().join("missing"), "").is_err());
338 // A CRLF golden must not be silently normalized either.
339 std::fs::write(&path, "expected\r\n").expect("write CRLF golden");
340 assert!(check_golden(&path, "expected\n").is_err());
341
342 // A large snapshot's common prefix must not hide its actual differing
343 // field; the comparison still rejects the entire changed document.
344 let prefix = "x".repeat(700);
345 let expected = jsonl(&[serde_json::json!({"prefix": prefix, "tail": "old"})]);
346 let actual = jsonl(&[serde_json::json!({"prefix": prefix, "tail": "new"})]);
347 std::fs::write(&path, expected).expect("write long JSON golden");
348 let diagnostic = check_golden(&path, &actual).unwrap_err();
349 assert!(diagnostic.contains("\"tail\":\"old\""));
350 assert!(diagnostic.contains("\"tail\":\"new\""));
351 }
352
353 #[test]
354 #[should_panic(expected = "ran no cases")]
355 fn empty_family_cannot_pass() {
356 Failures::default().finish("empty_control", 0);
357 }
358
359 #[test]
360 #[should_panic(expected = "is refused under CI")]
361 fn update_mode_is_refused_under_ci_even_for_matching_bytes() {
362 let _lock = lock_test_env();
363 let _update = EnvVarGuard::set(UPDATE_ENV, "1");
364 let _ci = EnvVarGuard::set("CI", "1");
365 let dir = tempfile::tempdir().expect("temporary golden");
366 let path = dir.path().join("matching.golden.txt");
367 std::fs::write(&path, "matching\n").expect("write golden");
368 let _ = check_golden(&path, "matching\n");
369 }
370
370 lines RUST