Skip to main content

vtcode_commons/
verification_signal.rs

1//! Shape-only diagnostics for failed verification commands.
2//!
3//! Mirrors the checkpoint + fingerprint pattern: record *where* a failure
4//! happened and a stable fingerprint used to group repeats, never the output
5//! text itself. Every retained field is bounded and derived from a short
6//! allowlist of well-known verifier markers, so user data appearing anywhere
7//! else in command output cannot leak into prompts or handoffs. The `site` is the
8//! bounded token found *at* the marker position; treat it as untrusted output
9//! text (a localization hint), not as a verified identifier.
10
11use crate::utils::calculate_sha256;
12
13/// Maximum characters retained for a localized site.
14const MAX_SITE_CHARS: usize = 120;
15/// Characters of the hex digest retained as the grouping fingerprint.
16const FINGERPRINT_CHARS: usize = 16;
17/// Maximum window (in bytes) scanned after a marker while looking for a test
18/// name. Sized to hold the longest retained site in the widest UTF-8 encoding
19/// (120 chars x 4 bytes) plus the ` ... FAILED` suffix, so a name that will
20/// be truncated still classifies instead of falling through to `Other`.
21const MARKER_WINDOW_BYTES: usize = 512;
22/// Maximum repeated markers examined in one output.
23const MAX_MARKER_ATTEMPTS: usize = 64;
24
25/// The recognizable category of a verification failure.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
27pub enum VerificationFailureKind {
28    /// A Rust/`std`-style `panicked at` line.
29    Panic,
30    /// An individual test reported `FAILED`.
31    TestFailed,
32    /// A language compiler emitted a structured error.
33    CompileError,
34    /// The verifier reported a timeout.
35    Timeout,
36    /// No allowlisted marker matched. This is the default.
37    #[default]
38    Other,
39}
40
41impl VerificationFailureKind {
42    /// Stable lowercase label used in diagnostics and as fingerprint input.
43    #[must_use]
44    pub const fn as_str(self) -> &'static str {
45        match self {
46            Self::Panic => "panic",
47            Self::TestFailed => "test",
48            Self::CompileError => "compile",
49            Self::Timeout => "timeout",
50            Self::Other => "other",
51        }
52    }
53}
54
55/// Bounded, content-free shape of one failed verification command.
56///
57/// The default is the unrecognized shape (`Other`, no site, no fingerprint).
58#[derive(Debug, Clone, Default, PartialEq, Eq)]
59pub struct VerificationFailureShape {
60    /// Recognized category of the failure.
61    pub kind: VerificationFailureKind,
62    /// Localized `file:line` or test name, when an allowlisted marker supplied one.
63    pub site: Option<String>,
64    /// Stable fingerprint of `(kind, site)`, used to group repeated failures.
65    /// `None` when no allowlisted marker matched: unrecognized failures have
66    /// no identity to deduplicate against.
67    pub fingerprint: Option<String>,
68}
69
70impl VerificationFailureShape {
71    /// One-line, content-free description for prompts and handoffs.
72    ///
73    /// # Ensures
74    ///
75    /// The result contains only the kind label, the bounded site, and a
76    /// fingerprint when one exists. Beyond the site token, it never reproduces
77    /// command output.
78    #[must_use]
79    pub fn describe(&self) -> String {
80        let base = match self.site.as_deref() {
81            Some(site) => format!("{} at {site}", self.kind.as_str()),
82            None => self.kind.as_str().to_string(),
83        };
84        match self.fingerprint.as_deref() {
85            Some(fingerprint) => format!("{base} (fingerprint {fingerprint})"),
86            None => base,
87        }
88    }
89}
90
91/// Anti-thrash coaching appended once the same failure shape has recurred.
92///
93/// Shared by every loop that tracks a fingerprint streak so the wording stays
94/// identical across the interactive runloop and the headless runner. Returns an
95/// empty string for streaks below 2 (a single sighting is evidence, not thrash).
96///
97/// # Requires
98///
99/// None.
100///
101/// # Ensures
102///
103/// The result is empty for `streak < 2`, otherwise a bounded sentence naming
104/// the streak count. It never reproduces verifier output.
105///
106/// # Termination
107///
108/// Straight-line formatting.
109#[must_use]
110pub fn repeated_shape_note(streak: u8) -> String {
111    if streak >= 2 {
112        format!(
113            " This failure shape has repeated {streak} times consecutively; change your approach instead of \
114             retrying the same fix."
115        )
116    } else {
117        String::new()
118    }
119}
120
121/// Extract a shape-only diagnostic from verifier output.
122///
123/// # Requires
124///
125/// None: the function is total over `&str`, including empty and hostile input.
126///
127/// # Ensures
128///
129/// - `site` is at most 120 characters and comes only from an allowlisted marker.
130/// - `fingerprint` is `None` when no allowlisted marker matched, otherwise 16
131///   lowercase hexadecimal characters.
132/// - No field reproduces arbitrary content from `output` beyond the bounded
133///   token at the matched marker position.
134/// - Total: a bounded number of substring scans over `output`.
135///
136/// # Termination
137///
138/// Bounded: at most 64 marker attempts per scan loop over 512-byte windows,
139/// plus a constant number of linear substring scans.
140#[must_use]
141pub fn extract_verification_failure_shape(output: &str) -> VerificationFailureShape {
142    let (kind, site) = classify(output);
143    let fingerprint = fingerprint(kind, site.as_deref());
144    VerificationFailureShape { kind, site, fingerprint }
145}
146
147fn classify(output: &str) -> (VerificationFailureKind, Option<String>) {
148    if let Some(site) = location_after(output, "panicked at ") {
149        return (VerificationFailureKind::Panic, Some(site));
150    }
151    if let Some(name) = failed_test_name(output) {
152        return (VerificationFailureKind::TestFailed, Some(name));
153    }
154    if output.contains("test result: FAILED") {
155        return (VerificationFailureKind::TestFailed, None);
156    }
157    if output.contains("error[E") || output.contains("error: could not compile") {
158        return (VerificationFailureKind::CompileError, location_after(output, "--> "));
159    }
160    let lowered = output.to_ascii_lowercase();
161    if is_timeout(&lowered) {
162        return (VerificationFailureKind::Timeout, None);
163    }
164    // A panic marker without a parseable location still identifies the kind;
165    // it sorts below localized shapes so a named failing test keeps its site.
166    if output.contains("panicked at ") {
167        return (VerificationFailureKind::Panic, None);
168    }
169    (VerificationFailureKind::Other, None)
170}
171
172/// True when the lowered output reports a timeout rather than merely
173/// mentioning one. A bare `timeout` needs failure context so config echoes
174/// like `timeout=30s` do not group unrelated failures under one fingerprint.
175fn is_timeout(lowered: &str) -> bool {
176    if lowered.contains("timed out") {
177        return true;
178    }
179    const FAILURE_CONTEXT: [&str; 7] = ["error", "fail", "exceed", "expire", "killed", "abort", "deadline"];
180    lowered.contains("timeout") && FAILURE_CONTEXT.iter().any(|word| lowered.contains(word))
181}
182
183/// Find an individual failed test name, tolerating JSON-escaped newlines.
184fn failed_test_name(output: &str) -> Option<String> {
185    let mut rest = output;
186    for _ in 0..MAX_MARKER_ATTEMPTS {
187        let Some((_, after)) = rest.split_once("test ") else {
188            break;
189        };
190        // `trim_start` keeps `strip_prefix(name)` aligned when the runner pads
191        // the name with extra whitespace (`test  foo ... FAILED`).
192        let window = bounded_window(after).trim_start();
193        let Some(name) = window.split_whitespace().next() else {
194            rest = after;
195            continue;
196        };
197        // Same rejection set as the `---- <name> stdout ----` fallback below:
198        // quotes and backslashes mark JSON-escaped or spliced text, never a
199        // test name.
200        if !name.is_empty()
201            && !name.contains(['\n', '"', '\\'])
202            && window.strip_prefix(name).is_some_and(|tail| tail.starts_with(" ... FAILED"))
203        {
204            return Some(bound_site(name));
205        }
206        rest = after;
207    }
208
209    // Rust also emits `---- <name> stdout ----` above captured test output;
210    // that header survives when the trailing `FAILED` line was cut from a tail.
211    // `break` above (not `?`) is what keeps this fallback reachable.
212    let mut rest = output;
213    for _ in 0..MAX_MARKER_ATTEMPTS {
214        let Some((_, after)) = rest.split_once("---- ") else {
215            break;
216        };
217        let window = bounded_window(after);
218        if let Some((name, _)) = window.split_once(" stdout ----")
219            && !name.is_empty()
220            && !name.contains(['\n', '"', '\\'])
221        {
222            return Some(bound_site(name));
223        }
224        rest = after;
225    }
226    None
227}
228
229/// Cap a scan window without cutting through a multi-byte character.
230fn bounded_window(text: &str) -> &str {
231    if text.len() <= MARKER_WINDOW_BYTES {
232        return text;
233    }
234    let mut end = MARKER_WINDOW_BYTES;
235    while !text.is_char_boundary(end) {
236        end -= 1;
237    }
238    text.get(..end).unwrap_or(text)
239}
240
241/// Read a bounded `file:line` token immediately after a known marker.
242fn location_after(output: &str, marker: &str) -> Option<String> {
243    let (_, after) = output.split_once(marker)?;
244    let token = after
245        .split(|c: char| c.is_whitespace() || matches!(c, '"' | '\\'))
246        .next()?
247        .trim_end_matches(':');
248    normalize_location(token)
249}
250
251fn normalize_location(token: &str) -> Option<String> {
252    let mut segments = token.rsplitn(3, ':');
253    let first = segments.next()?;
254    let second = segments.next();
255    let third = segments.next();
256    let (line, path) = match (second, third) {
257        (Some(line), Some(path)) if is_number(first) => (line, path),
258        (Some(path), None) => (first, path),
259        _ => return None,
260    };
261    if !is_number(line) {
262        return None;
263    }
264    let file = path.rsplit(['/', '\\']).next().unwrap_or(path);
265    Some(bound_site(&format!("{file}:{line}")))
266}
267
268fn is_number(text: &str) -> bool {
269    !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())
270}
271
272fn bound_site(text: &str) -> String {
273    text.chars().take(MAX_SITE_CHARS).collect()
274}
275
276fn fingerprint(kind: VerificationFailureKind, site: Option<&str>) -> Option<String> {
277    if kind == VerificationFailureKind::Other {
278        return None;
279    }
280    let input = format!("{}|{}", kind.as_str(), site.unwrap_or(""));
281    let digest = calculate_sha256(input.as_bytes());
282    debug_assert!(digest.len() >= FINGERPRINT_CHARS && digest.is_ascii(), "sha256 hex digest invariant violated");
283    // The digest is lowercase ASCII hex, so the prefix is a char boundary.
284    Some(digest.get(..FINGERPRINT_CHARS).unwrap_or_default().to_string())
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290
291    #[test]
292    fn test_failure_localizes_the_individual_test_name() {
293        let shape = extract_verification_failure_shape(
294            "running 3 tests\ntest auth::expired_token ... FAILED\ntest cache::hit ... ok\n",
295        );
296
297        assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
298        assert_eq!(shape.site.as_deref(), Some("auth::expired_token"));
299        assert!(shape.describe().contains("auth::expired_token"), "{}", shape.describe());
300    }
301
302    #[test]
303    fn test_summary_without_an_individual_name_keeps_the_kind_but_no_site() {
304        let shape = extract_verification_failure_shape("test result: FAILED. 1 failed, 2 passed");
305
306        assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
307        assert_eq!(shape.site, None);
308    }
309
310    #[test]
311    fn panic_localizes_the_trailing_file_and_line_not_the_full_path() {
312        let shape = extract_verification_failure_shape(
313            "thread 'main' panicked at /Users/someone/project/crates/foo/src/lib.rs:42:9:\nassertion failed",
314        );
315
316        assert_eq!(shape.kind, VerificationFailureKind::Panic);
317        assert_eq!(shape.site.as_deref(), Some("lib.rs:42"));
318        assert!(!shape.describe().contains("/Users/"), "site must not leak an absolute path");
319    }
320
321    #[test]
322    fn compile_error_uses_the_arrow_location() {
323        let shape = extract_verification_failure_shape("error[E0308]: mismatched types\n  --> src/main.rs:7:5\n");
324
325        assert_eq!(shape.kind, VerificationFailureKind::CompileError);
326        assert_eq!(shape.site.as_deref(), Some("main.rs:7"));
327    }
328
329    #[test]
330    fn timeout_is_recognized_without_a_site() {
331        let shape = extract_verification_failure_shape("Error: operation timed out after 30s");
332
333        assert_eq!(shape.kind, VerificationFailureKind::Timeout);
334        assert_eq!(shape.site, None);
335    }
336
337    #[test]
338    fn json_escaped_output_is_recognized_like_plain_text() {
339        let escaped = r#"{"exit_code":1,"output":"test auth::expired_token ... FAILED\nboom"}"#;
340        let shape = extract_verification_failure_shape(escaped);
341
342        assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
343        assert_eq!(shape.site.as_deref(), Some("auth::expired_token"));
344    }
345
346    #[test]
347    fn equivalent_failures_share_a_fingerprint_but_distinct_sites_do_not() {
348        let first = extract_verification_failure_shape("test auth::expired ... FAILED\nassertion a == b failed");
349        let same_bug = extract_verification_failure_shape("test auth::expired ... FAILED\nleft == right differs");
350        let other_bug = extract_verification_failure_shape("test cache::expired ... FAILED\nassertion a == b failed");
351
352        let first_fp = first.fingerprint.as_deref().expect("fingerprint");
353        assert_eq!(first_fp, same_bug.fingerprint.as_deref().expect("fingerprint"));
354        assert_ne!(first_fp, other_bug.fingerprint.as_deref().expect("fingerprint"));
355        assert_eq!(first_fp.len(), FINGERPRINT_CHARS);
356        assert!(first_fp.bytes().all(|byte| byte.is_ascii_hexdigit()));
357    }
358
359    #[test]
360    fn oversized_test_names_are_bounded_on_both_sides_of_the_limit() {
361        let under_limit = extract_verification_failure_shape(&format!("test {} ... FAILED", "a".repeat(119)));
362        assert_eq!(under_limit.site.as_ref().expect("site").chars().count(), 119);
363
364        let over_limit = extract_verification_failure_shape(&format!("test {} ... FAILED", "b".repeat(200)));
365        assert_eq!(over_limit.site.as_ref().expect("site").chars().count(), MAX_SITE_CHARS);
366        assert_eq!(over_limit.fingerprint.as_deref().expect("fingerprint").len(), FINGERPRINT_CHARS);
367        assert_ne!(under_limit.fingerprint, over_limit.fingerprint);
368    }
369
370    #[test]
371    fn unrecognized_output_has_no_grouping_fingerprint() {
372        let first = extract_verification_failure_shape("something odd happened");
373        let second = extract_verification_failure_shape("a completely different oddity");
374
375        assert_eq!(first.kind, VerificationFailureKind::Other);
376        assert_eq!(first.site, None);
377        assert_eq!(first.fingerprint, None);
378        assert_eq!(second.fingerprint, None);
379        assert!(!first.describe().contains("fingerprint"), "{}", first.describe());
380    }
381
382    #[test]
383    fn captured_output_header_localizes_even_when_the_failed_line_is_cut() {
384        let shape =
385            extract_verification_failure_shape("---- auth::expired_token stdout ----\nassertion failed: left == right");
386
387        assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
388        assert_eq!(shape.site.as_deref(), Some("auth::expired_token"));
389        assert!(shape.fingerprint.is_some());
390    }
391
392    #[test]
393    fn arbitrary_output_content_never_appears_in_the_description() {
394        let secret = "SECRET_USER_TOKEN_XYZ";
395        let shape = extract_verification_failure_shape(&format!("leftover {secret} after the failure"));
396
397        assert!(!shape.describe().contains(secret), "{}", shape.describe());
398        assert_eq!(shape.kind, VerificationFailureKind::Other);
399    }
400
401    #[test]
402    fn panic_without_a_parseable_location_keeps_the_kind_but_no_site() {
403        let shape = extract_verification_failure_shape("thread 'main' panicked at 'assertion failed'");
404
405        assert_eq!(shape.kind, VerificationFailureKind::Panic);
406        assert_eq!(shape.site, None);
407        assert!(shape.fingerprint.is_some(), "kind-only failures still group");
408    }
409
410    #[test]
411    fn timeout_mention_without_failure_context_is_not_a_timeout() {
412        for output in [
413            "setting timeout=30s for cache\nall green",
414            "request timeout: 5s (default)\nerror[E0308]: mismatched types",
415        ] {
416            let shape = extract_verification_failure_shape(output);
417            assert_ne!(shape.kind, VerificationFailureKind::Timeout, "{output}");
418        }
419        // The second input must still classify by its stronger marker.
420        let compile = extract_verification_failure_shape("request timeout: 5s\nerror[E0308]: boom");
421        assert_eq!(compile.kind, VerificationFailureKind::CompileError);
422    }
423
424    #[test]
425    fn timeout_with_failure_context_keeps_the_kind() {
426        let mut fingerprints = Vec::new();
427        for output in [
428            "Error: connection timeout on upstream",
429            "Timeout exceeded after 3 retries",
430        ] {
431            let shape = extract_verification_failure_shape(output);
432            assert_eq!(shape.kind, VerificationFailureKind::Timeout, "{output}");
433            assert_eq!(shape.site, None);
434            fingerprints.push(shape.fingerprint.clone().expect("fingerprint"));
435        }
436        // Siteless kinds group by kind: consecutive timeouts are one streak
437        // even when the underlying cause differs.
438        assert_eq!(fingerprints[0], fingerprints[1]);
439    }
440
441    #[test]
442    fn siteless_panics_share_one_kind_level_fingerprint() {
443        let first = extract_verification_failure_shape("thread 'main' panicked at 'assertion failed'");
444        let second = extract_verification_failure_shape("thread 'worker' panicked at 'index out of bounds'");
445
446        assert_eq!(first.kind, VerificationFailureKind::Panic);
447        assert_eq!(second.kind, VerificationFailureKind::Panic);
448        assert_eq!(first.fingerprint, second.fingerprint);
449        assert_ne!(
450            first.fingerprint,
451            extract_verification_failure_shape("Error: operation timed out").fingerprint,
452            "kind levels must not collide across kinds"
453        );
454    }
455
456    #[test]
457    fn json_escaped_panic_keeps_the_kind_without_a_site() {
458        // Tool results arrive JSON-escaped, so the `src\/lib.rs` backslashes
459        // defeat the location token: the kind must survive anyway.
460        let escaped = r#"{"exit_code":101,"output":"thread 'main' panicked at src\/lib.rs:42:9\nboom"}"#;
461        let shape = extract_verification_failure_shape(escaped);
462
463        assert_eq!(shape.kind, VerificationFailureKind::Panic);
464        assert_eq!(shape.site, None);
465        assert!(shape.fingerprint.is_some());
466    }
467
468    #[test]
469    fn quoted_or_escaped_test_name_is_rejected() {
470        let shape = extract_verification_failure_shape(r#"test injected\"name ... FAILED"#);
471
472        // The token at the marker is spliced text, not a test name: no site,
473        // and no fingerprint built from attacker-influenced bytes.
474        assert_eq!(shape.kind, VerificationFailureKind::Other);
475        assert_eq!(shape.site, None);
476        assert_eq!(shape.fingerprint, None);
477    }
478
479    #[test]
480    fn extra_whitespace_between_test_and_name_still_localizes() {
481        let shape = extract_verification_failure_shape("test  foo ... FAILED");
482
483        assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
484        assert_eq!(shape.site.as_deref(), Some("foo"));
485    }
486
487    #[test]
488    fn multibyte_site_is_bounded_by_chars_not_bytes() {
489        // 200 `é` = 400 bytes: the name alone exceeds the old 256-byte scan
490        // window, so this pins both classification and char-based truncation.
491        let shape = extract_verification_failure_shape(&format!("test {} ... FAILED", "é".repeat(200)));
492
493        assert_eq!(shape.kind, VerificationFailureKind::TestFailed);
494        let site = shape.site.as_deref().expect("site");
495        assert_eq!(site.chars().count(), MAX_SITE_CHARS);
496        assert!(site.is_char_boundary(site.len()));
497    }
498
499    #[test]
500    fn repeated_shape_note_emits_only_from_the_second_sighting() {
501        assert!(repeated_shape_note(0).is_empty());
502        assert!(repeated_shape_note(1).is_empty());
503
504        let note = repeated_shape_note(3);
505        assert!(note.contains("3 times consecutively"), "{note}");
506        assert!(note.contains("change your approach"), "{note}");
507    }
508}