| 1 | //! Shared, host-bound test support for the FEAT-029 `debug::diagnostics` slice. |
| 2 | //! |
| 3 | //! This module lives at the `commands` root — outside `codewhale-commands` — so the public-surface and |
| 4 | //! host-regression suites share one harness and one normalisation contract |
| 5 | //! instead of drifting copies. |
| 6 | //! |
| 7 | //! The fixtures under `fixtures/diagnostics/` are reviewed command captures. |
| 8 | //! Context fixtures reflect an App with no installed Engine instruction receipt. |
| 9 | //! Only clock fields and owned temporary paths are normalised. Context |
| 10 | //! expectations account for the host's platform/shell in the environment block |
| 11 | //! and its token subtotal. |
| 12 | |
| 13 | use std::path::{Path, PathBuf}; |
| 14 | use std::sync::OnceLock; |
| 15 | |
| 16 | use regex::Regex; |
| 17 | use tempfile::TempDir; |
| 18 | |
| 19 | use crate::tui::app::{App, TuiOptions}; |
| 20 | use codewhale_config::ProviderKind; |
| 21 | |
| 22 | /// The shared home seal, re-exported so the diagnostics suites keep one import |
| 23 | /// path. Take it first in any test whose output depends on the user's state |
| 24 | /// (global instructions, installed skills, persisted settings), before building |
| 25 | /// a [`DiagnosticsHarness`]: it holds the process-wide environment lock, which |
| 26 | /// the harness's settings loader re-enters. |
| 27 | pub(crate) use crate::test_support::SealedHome; |
| 28 | |
| 29 | /// Host-isolated fixture for the diagnostics command surface. |
| 30 | /// |
| 31 | /// The hermetic test-home wrapper isolates persisted settings. The owned |
| 32 | /// workspace and skills directories keep `/context` away from project data. |
| 33 | /// Do not hold either test-state mutex while constructing `App`: its settings |
| 34 | /// loader takes that mutex internally and the lock is not reentrant. |
| 35 | pub(crate) struct DiagnosticsHarness { |
| 36 | pub(crate) app: App, |
| 37 | pub(crate) workspace: PathBuf, |
| 38 | pub(crate) skills: PathBuf, |
| 39 | _temp: TempDir, |
| 40 | } |
| 41 | |
| 42 | impl DiagnosticsHarness { |
| 43 | pub(crate) fn new() -> Self { |
| 44 | let temp = TempDir::new().expect("diagnostics tempdir"); |
| 45 | |
| 46 | let workspace = temp.path().join("workspace"); |
| 47 | std::fs::create_dir_all(&workspace).expect("workspace dir"); |
| 48 | let skills = temp.path().join("skills"); |
| 49 | std::fs::create_dir_all(&skills).expect("skills dir"); |
| 50 | |
| 51 | let options = TuiOptions { |
| 52 | model: "deepseek-v4-pro".to_string(), |
| 53 | workspace: workspace.clone(), |
| 54 | skills_dir: skills.clone(), |
| 55 | memory_path: temp.path().join("memory.md"), |
| 56 | mcp_config_path: temp.path().join("mcp.json"), |
| 57 | use_memory: false, |
| 58 | ..crate::tui::test_support::test_tui_options(temp.path()) |
| 59 | }; |
| 60 | let mut app = crate::tui::test_support::test_app_with_options(options); |
| 61 | app.api_provider = ProviderKind::Deepseek; |
| 62 | |
| 63 | Self { |
| 64 | app, |
| 65 | workspace, |
| 66 | skills, |
| 67 | _temp: temp, |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /// Apply the documented volatile-field normalisation for this harness. |
| 72 | pub(crate) fn normalize(&self, raw: &str) -> String { |
| 73 | normalize_generated_at(&normalize_harness_paths( |
| 74 | raw, |
| 75 | &self.workspace, |
| 76 | &self.skills, |
| 77 | &self._temp.path().join("memory.md"), |
| 78 | )) |
| 79 | } |
| 80 | } |
| 81 | |
| 82 | /// Read a frozen baseline fixture shipped with the slice. |
| 83 | pub(crate) fn fixture(name: &str) -> String { |
| 84 | let path = Path::new(env!("CARGO_MANIFEST_DIR")) |
| 85 | .join("src/commands/fixtures/diagnostics") |
| 86 | .join(name); |
| 87 | std::fs::read_to_string(&path).unwrap_or_else(|error| { |
| 88 | panic!( |
| 89 | "baseline fixture {} must be present and readable: {error}", |
| 90 | path.display() |
| 91 | ) |
| 92 | }) |
| 93 | } |
| 94 | |
| 95 | /// Assert the captured command output is byte-identical to its frozen baseline. |
| 96 | /// |
| 97 | /// Fixture files retain a stable `command: /...` provenance header captured by |
| 98 | /// the temporary baseline tool. The test identity and fixture name select that |
| 99 | /// command; the actual runtime value starts with `is_error`, so compare the |
| 100 | /// entire captured `CommandResult` body without manufacturing a header at run |
| 101 | /// time. |
| 102 | #[track_caller] |
| 103 | pub(crate) fn assert_fixture(name: &str, actual: &str) { |
| 104 | let expected = fixture(name); |
| 105 | let expected = if name.starts_with("context_") { |
| 106 | context_fixture_for_host( |
| 107 | &expected, |
| 108 | std::env::consts::OS, |
| 109 | codewhale_sandbox::shell_dispatcher::global_dispatcher() |
| 110 | .kind() |
| 111 | .binary(), |
| 112 | ) |
| 113 | } else { |
| 114 | expected |
| 115 | }; |
| 116 | let (_, expected) = expected |
| 117 | .split_once('\n') |
| 118 | .unwrap_or_else(|| panic!("baseline fixture {name} is missing its provenance header")); |
| 119 | assert_eq!( |
| 120 | expected, actual, |
| 121 | "baseline parity drift in {name}; captured output changed" |
| 122 | ); |
| 123 | } |
| 124 | |
| 125 | /// Keep its text frozen independently of the production prompt renderer, but |
| 126 | /// substitute real host facts: Windows/pwsh.exe contributes 22, for example. |
| 127 | /// Never derive expectations from the report being tested or erase its counts. |
| 128 | fn context_fixture_for_host(expected: &str, platform: &str, shell: &str) -> String { |
| 129 | let environment = |
| 130 | format!("## Environment\n\n- lang: en\n- platform: {platform}\n- shell: {shell}"); |
| 131 | let tokens = environment.chars().count().div_ceil(3); |
| 132 | let text_total = expected.lines().find_map(|line| { |
| 133 | line.strip_prefix("Source-entry total: ") |
| 134 | .and_then(|rest| rest.strip_suffix(" tokens")) |
| 135 | .and_then(|value| value.parse::<usize>().ok()) |
| 136 | }); |
| 137 | let json_total = expected.lines().find_map(|line| { |
| 138 | line.trim() |
| 139 | .strip_prefix("\"total_estimated_tokens\": ") |
| 140 | .and_then(|rest| rest.trim_end_matches(',').parse::<usize>().ok()) |
| 141 | }); |
| 142 | static ENVIRONMENT_COUNT: OnceLock<Regex> = OnceLock::new(); |
| 143 | let environment_count = ENVIRONMENT_COUNT.get_or_init(|| { |
| 144 | Regex::new(r#"("source_kind": "environment_block",[^{}]*?"estimated_tokens": )21,"#) |
| 145 | .expect("environment entry token count regex") |
| 146 | }); |
| 147 | let mut adjusted = environment_count |
| 148 | .replace_all(expected, format!("${{1}}{tokens},")) |
| 149 | .replace( |
| 150 | "EnvironmentBlock: Runtime environment [<workspace>] - 21 tokens", |
| 151 | &format!("EnvironmentBlock: Runtime environment [<workspace>] - {tokens} tokens"), |
| 152 | ) |
| 153 | .replace( |
| 154 | "Runtime environment (21)", |
| 155 | &format!("Runtime environment ({tokens})"), |
| 156 | ); |
| 157 | if let Some(total) = text_total { |
| 158 | adjusted = adjusted.replace( |
| 159 | &format!("Source-entry total: {total} tokens"), |
| 160 | &format!("Source-entry total: {} tokens", total - 21 + tokens), |
| 161 | ); |
| 162 | } |
| 163 | if let Some(total) = json_total { |
| 164 | adjusted = adjusted.replace( |
| 165 | &format!("\"total_estimated_tokens\": {total},"), |
| 166 | &format!("\"total_estimated_tokens\": {},", total - 21 + tokens), |
| 167 | ); |
| 168 | } |
| 169 | adjusted |
| 170 | } |
| 171 | /// Replace the RFC-3339 `generated_at` report stamp so two captures of the same |
| 172 | /// source state compare byte-for-byte. |
| 173 | /// |
| 174 | /// `PromptSourceMap` / `PromptContext` stamp `Utc::now()` at construction; it is |
| 175 | /// the only wall-clock field on the diagnostics command surface. Production |
| 176 | /// timestamp semantics stay untouched — tests normalise the comparison, not the |
| 177 | /// adapter. |
| 178 | pub(crate) fn normalize_generated_at(raw: &str) -> String { |
| 179 | fn regex() -> &'static Regex { |
| 180 | static RE: OnceLock<Regex> = OnceLock::new(); |
| 181 | RE.get_or_init(|| Regex::new(r#""generated_at":\s*"[^"]*""#).expect("generated_at regex")) |
| 182 | } |
| 183 | regex() |
| 184 | .replace_all(raw, "\"generated_at\": \"<timestamp>\"") |
| 185 | .into_owned() |
| 186 | } |
| 187 | |
| 188 | /// Replace the host-owned workspace/skills directory paths with stable |
| 189 | /// placeholders so the fixture does not embed a per-run temporary path. |
| 190 | pub(crate) fn normalize_harness_paths( |
| 191 | raw: &str, |
| 192 | workspace: &Path, |
| 193 | skills: &Path, |
| 194 | memory: &Path, |
| 195 | ) -> String { |
| 196 | fn replace_path(raw: &str, path: &str, placeholder: &str) -> String { |
| 197 | let json = serde_json::to_string(path).expect("serialize fixture path"); |
| 198 | raw.replace(&json[1..json.len() - 1], placeholder) |
| 199 | .replace(path, placeholder) |
| 200 | } |
| 201 | let workspace = workspace.display().to_string(); |
| 202 | let mut normalized = raw.to_string(); |
| 203 | // Path::join adds a native separator before this slash-containing suffix. |
| 204 | // Replace the whole owned path first, including JSON-escaped Windows paths. |
| 205 | for separator in ['/', '\\'] { |
| 206 | normalized = replace_path( |
| 207 | &normalized, |
| 208 | &format!("{workspace}{separator}.codewhale/handoff.md"), |
| 209 | "<workspace>/.codewhale/handoff.md", |
| 210 | ); |
| 211 | } |
| 212 | for (path, placeholder) in [ |
| 213 | (workspace, "<workspace>"), |
| 214 | (skills.display().to_string(), "<skills>"), |
| 215 | (memory.display().to_string(), "<memory>"), |
| 216 | ] { |
| 217 | normalized = replace_path(&normalized, &path, placeholder); |
| 218 | } |
| 219 | normalized |
| 220 | } |
| 221 | |
| 222 | /// Replace the trailing per-turn age cell in `/cache` history rows so a slow |
| 223 | /// runner cannot turn `0s` into `1s` and fail an otherwise identical capture. |
| 224 | /// |
| 225 | /// `humanize_age` renders `{secs}s` or `{mins}m {secs:02}s`; only that final |
| 226 | /// token on a telemetry row is volatile. |
| 227 | pub(crate) fn normalize_cache_ages(raw: &str) -> String { |
| 228 | fn regex() -> &'static Regex { |
| 229 | static RE: OnceLock<Regex> = OnceLock::new(); |
| 230 | RE.get_or_init(|| Regex::new(r"(?m)(\d+m \d{2}s|\d+s)$").expect("cache-age regex")) |
| 231 | } |
| 232 | regex().replace_all(raw, "<age>").into_owned() |
| 233 | } |
| 234 | |
| 235 | /// The normalisers must replace *only* the documented volatile fields. A |
| 236 | /// normaliser that over-matched would turn the golden comparison into a |
| 237 | /// tautology, so pin its exact behaviour and prove an unrelated byte change |
| 238 | /// still fails equality. |
| 239 | #[test] |
| 240 | fn normalisers_replace_only_documented_volatile_fields() { |
| 241 | let raw = concat!( |
| 242 | "{\n", |
| 243 | " \"budget_used_percent\": 0.0048,\n", |
| 244 | " \"generated_at\": \"2026-09-23T19:02:15Z\",\n", |
| 245 | " \"note\": \"stable\"\n", |
| 246 | "}\n", |
| 247 | ); |
| 248 | let normalized = normalize_generated_at(raw); |
| 249 | assert!( |
| 250 | normalized.contains("\"generated_at\": \"<timestamp>\""), |
| 251 | "{normalized}" |
| 252 | ); |
| 253 | assert!(!normalized.contains("2026-09-23T19:02:15Z"), "{normalized}"); |
| 254 | // Every other byte survives exactly. |
| 255 | assert!( |
| 256 | normalized.contains("\"budget_used_percent\": 0.0048"), |
| 257 | "{normalized}" |
| 258 | ); |
| 259 | assert!(normalized.contains("\"note\": \"stable\""), "{normalized}"); |
| 260 | |
| 261 | // An unrelated byte change is not normalised away: it must still differ. |
| 262 | let mutated = raw.replace("\"stable\"", "\"drifted\""); |
| 263 | assert_ne!( |
| 264 | normalize_generated_at(raw), |
| 265 | normalize_generated_at(&mutated), |
| 266 | "a non-clock change must still fail the golden comparison" |
| 267 | ); |
| 268 | |
| 269 | // Path normalisation is exact-substring and cannot swallow unrelated text. |
| 270 | let paths = normalize_harness_paths( |
| 271 | "pack [/tmp/abc/workspace] skills [/tmp/abc/skills] memory [/tmp/abc/memory.md]", |
| 272 | Path::new("/tmp/abc/workspace"), |
| 273 | Path::new("/tmp/abc/skills"), |
| 274 | Path::new("/tmp/abc/memory.md"), |
| 275 | ); |
| 276 | assert_eq!( |
| 277 | paths, |
| 278 | "pack [<workspace>] skills [<skills>] memory [<memory>]" |
| 279 | ); |
| 280 | |
| 281 | // The age normaliser touches only the trailing age cell. |
| 282 | let rows = " 1 deepseek/x 4000 200 3000 1000 — — 75.0% — 0s\n\ |
| 283 | footer: sum_write: 0\n"; |
| 284 | let aged = normalize_cache_ages(rows); |
| 285 | assert!(aged.contains("75.0% — <age>\n"), "{aged}"); |
| 286 | assert!(aged.contains("footer: sum_write: 0"), "{aged}"); |
| 287 | } |
| 288 | |
| 289 | #[test] |
| 290 | fn context_expectations_preserve_counts_for_each_host() { |
| 291 | let captures = [ |
| 292 | "Source-entry total: @total@ tokens\n- EnvironmentBlock: Runtime environment [<workspace>] - @env@ tokens\n- Other: fixture - 21 tokens", |
| 293 | "Top sources: Other (21), Runtime environment (@env@)", |
| 294 | r#"{ |
| 295 | "entries": [ |
| 296 | {"source_kind": "other", "estimated_tokens": 21, "label": "Other"}, |
| 297 | {"source_kind": "environment_block", "estimated_tokens": @env@, "label": "Runtime environment"} |
| 298 | ], |
| 299 | "total_estimated_tokens": @total@, |
| 300 | "other": 121 |
| 301 | }"#, |
| 302 | ]; |
| 303 | for capture in captures { |
| 304 | let baseline = capture.replace("@env@", "21").replace("@total@", "121"); |
| 305 | for (platform, shell, environment, total) in [ |
| 306 | ("linux", "/bin/bash", "21", "121"), |
| 307 | ("windows", "pwsh.exe", "22", "122"), |
| 308 | ("linux", "sh", "19", "119"), |
| 309 | ] { |
| 310 | let expected = capture |
| 311 | .replace("@env@", environment) |
| 312 | .replace("@total@", total); |
| 313 | assert_eq!( |
| 314 | context_fixture_for_host(&baseline, platform, shell), |
| 315 | expected |
| 316 | ); |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | #[test] |
| 322 | fn windows_paths_normalize_in_text_and_json_without_changing_other_data() { |
| 323 | let workspace = Path::new(r"C:\Users\runner\Temp\fixture\workspace"); |
| 324 | let skills = Path::new(r"C:\Users\runner\Temp\fixture\skills"); |
| 325 | let memory = Path::new(r"C:\Users\runner\Temp\fixture\memory.md"); |
| 326 | let handoff = format!("{}\\.codewhale/handoff.md", workspace.display()); |
| 327 | let raw = format!( |
| 328 | "handoff [{handoff}]\n{{\"handoff\":{},\"skills\":{},\"memory\":{},\"tokens\":22,\"other\":\"C:\\\\unrelated\"}}", |
| 329 | serde_json::to_string(&handoff).unwrap(), |
| 330 | serde_json::to_string(&skills.display().to_string()).unwrap(), |
| 331 | serde_json::to_string(&memory.display().to_string()).unwrap(), |
| 332 | ); |
| 333 | assert_eq!( |
| 334 | normalize_harness_paths(&raw, workspace, skills, memory), |
| 335 | "handoff [<workspace>/.codewhale/handoff.md]\n{\"handoff\":\"<workspace>/.codewhale/handoff.md\",\"skills\":\"<skills>\",\"memory\":\"<memory>\",\"tokens\":22,\"other\":\"C:\\\\unrelated\"}" |
| 336 | ); |
| 337 | } |
| 338 |