Skip to main content

vtcode_core/core/agent/
hypothesis.rs

1//! Hypothesis-loop mismatch classification for the agent runloop.
2//!
3//! desirable loop: hypothesis → observation → mismatch → inspect evidence →
4//! revise hypothesis. This module is the pure, testable core of that loop:
5//! it names the mismatch, but never blocks, retries, or performs I/O. The
6//! binary's failure diagnosis and loop notices call into it to frame
7//! model-facing feedback; the evaluator provides a count-based heuristic.
8//!
9//! Dimension key for [`MismatchEvidence`] (index → field → meaning):
10//!
11//! | field                 | meaning when set                                          |
12//! | --------------------- | --------------------------------------------------------- |
13//! | `exit_code`           | tool result carried this process exit status               |
14//! | `empty_search_no_match` | grep-style exit 1 with no output inside the queried scope |
15//! | `patch_mismatch`      | patch context/deletion lines do not match the current file |
16//! | `verifier_failed`     | a standalone verifier reported a non-zero status           |
17//! | `repeated_evidence`   | query returned only previously seen lines/ranges           |
18
19/// Named mismatch between the agent's hypothesis and its observation.
20///
21/// Priority order in [`classify_mismatch`] is declaration order: patch
22/// mismatch first, repeated evidence last.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum MismatchKind {
25    /// Process reported a non-zero exit status.
26    NonZeroExit,
27    /// grep-style exit 1 with no output: evidence of absence, not a defect.
28    EmptySearch,
29    /// Patch context or deletion lines do not match the current file.
30    PatchMismatch,
31    /// A standalone verifier reported failure.
32    VerifierFailed,
33    /// Query returned only previously seen evidence.
34    RepeatedEvidence,
35}
36
37/// Structured evidence for one mismatch classification.
38///
39/// Prefer this named struct over a bare tuple so the shape is explicit in
40/// the type system. All fields default to unset via [`Default`].
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub struct MismatchEvidence {
43    /// Process exit status carried by the tool result, when present.
44    pub exit_code: Option<i64>,
45    /// grep-style exit 1 with fully visible empty output.
46    pub empty_search_no_match: bool,
47    /// Patch context or deletion lines mismatch the current file.
48    pub patch_mismatch: bool,
49    /// A standalone verifier reported a non-zero status.
50    pub verifier_failed: bool,
51    /// Query returned only previously seen lines or ranges.
52    pub repeated_evidence: bool,
53}
54
55/// Classify mismatch evidence into its highest-priority kind.
56///
57/// Returns `None` when nothing is set (including `exit_code` of `Some(0)`),
58/// so callers keep truly unknown failures short.
59#[must_use]
60pub fn classify_mismatch(evidence: &MismatchEvidence) -> Option<MismatchKind> {
61    if evidence.patch_mismatch {
62        return Some(MismatchKind::PatchMismatch);
63    }
64    if evidence.verifier_failed {
65        return Some(MismatchKind::VerifierFailed);
66    }
67    if evidence.empty_search_no_match {
68        return Some(MismatchKind::EmptySearch);
69    }
70    if evidence.exit_code.is_some_and(|code| code != 0) {
71        return Some(MismatchKind::NonZeroExit);
72    }
73    if evidence.repeated_evidence {
74        return Some(MismatchKind::RepeatedEvidence);
75    }
76    None
77}
78
79/// Model-facing revision guidance for a classified mismatch.
80///
81/// `None` (unknown context) yields the generic framing. Inspection can use
82/// already-visible evidence; fresh reads are needed for stale patch context
83/// or insufficient evidence. This guidance neither grants nor schedules retries.
84#[must_use]
85pub fn revision_guidance(kind: Option<MismatchKind>) -> &'static str {
86    match kind {
87        Some(MismatchKind::EmptySearch) => {
88            "Treat this as evidence of absence in the queried scope; revise the hypothesis to a new scope or question."
89        }
90        Some(MismatchKind::PatchMismatch) => {
91            "Re-read the exact current lines, revise the patch hypothesis, then retry once with exact context."
92        }
93        Some(MismatchKind::VerifierFailed) => {
94            "Compare verifier to request/artifact; revise the fix hypothesis or a faulty generated assertion without weakening criteria. Metadata is not a pass; re-verify."
95        }
96        Some(MismatchKind::RepeatedEvidence) => {
97            "Stop repeating the same query; revise the hypothesis and change scope or approach."
98        }
99        Some(MismatchKind::NonZeroExit) => {
100            "Inspect the bounded evidence, revise the hypothesis, then retry with corrected arguments."
101        }
102        None => "Revise the hypothesis from the bounded evidence before retrying.",
103    }
104}
105
106/// Append revision guidance to a `next_action` or loop notice.
107///
108/// An empty base yields the guidance alone so callers never emit a leading
109/// separator without content.
110#[must_use]
111pub fn append_revision_guidance(base: &str, kind: Option<MismatchKind>) -> String {
112    let base = base.trim_end();
113    if base.is_empty() {
114        return revision_guidance(kind).to_string();
115    }
116    format!("{base} {}", revision_guidance(kind))
117}
118
119#[cfg(test)]
120mod tests {
121    use super::*;
122
123    #[test]
124    fn verifier_revision_preserves_user_criteria_and_requires_executed_evidence() {
125        let guidance = revision_guidance(Some(MismatchKind::VerifierFailed));
126        assert!(guidance.contains("Compare verifier to request/artifact"));
127        assert!(guidance.contains("faulty generated assertion"));
128        assert!(guidance.contains("without weakening criteria"));
129        assert!(guidance.contains("Metadata is not a pass; re-verify"));
130    }
131
132    #[test]
133    fn exit_code_alone_distinguishes_zero_from_nonzero() {
134        let nonzero = MismatchEvidence { exit_code: Some(1), ..Default::default() };
135        assert_eq!(classify_mismatch(&nonzero), Some(MismatchKind::NonZeroExit));
136        let zero = MismatchEvidence { exit_code: Some(0), ..Default::default() };
137        assert_eq!(classify_mismatch(&zero), None);
138        assert_eq!(classify_mismatch(&MismatchEvidence::default()), None);
139    }
140
141    #[test]
142    fn empty_search_outranks_exit_code() {
143        let both = MismatchEvidence {
144            exit_code: Some(1),
145            empty_search_no_match: true,
146            ..Default::default()
147        };
148        assert_eq!(classify_mismatch(&both), Some(MismatchKind::EmptySearch));
149        let exit_only = MismatchEvidence { exit_code: Some(1), ..Default::default() };
150        assert_eq!(classify_mismatch(&exit_only), Some(MismatchKind::NonZeroExit));
151    }
152
153    #[test]
154    fn patch_mismatch_is_top_priority() {
155        let all = MismatchEvidence {
156            exit_code: Some(1),
157            empty_search_no_match: true,
158            patch_mismatch: true,
159            verifier_failed: true,
160            repeated_evidence: true,
161        };
162        assert_eq!(classify_mismatch(&all), Some(MismatchKind::PatchMismatch));
163        let verifier_and_exit = MismatchEvidence {
164            exit_code: Some(2),
165            verifier_failed: true,
166            repeated_evidence: true,
167            ..Default::default()
168        };
169        assert_eq!(classify_mismatch(&verifier_and_exit), Some(MismatchKind::VerifierFailed));
170    }
171
172    #[test]
173    fn repeated_evidence_is_lowest_priority() {
174        let repeated_only = MismatchEvidence { repeated_evidence: true, ..Default::default() };
175        assert_eq!(classify_mismatch(&repeated_only), Some(MismatchKind::RepeatedEvidence));
176        let repeated_and_exit = MismatchEvidence {
177            exit_code: Some(1),
178            repeated_evidence: true,
179            ..Default::default()
180        };
181        assert_eq!(classify_mismatch(&repeated_and_exit), Some(MismatchKind::NonZeroExit));
182    }
183
184    #[test]
185    fn guidance_names_revision_and_scopes_empty_search() {
186        for kind in [
187            Some(MismatchKind::NonZeroExit),
188            Some(MismatchKind::EmptySearch),
189            Some(MismatchKind::PatchMismatch),
190            Some(MismatchKind::VerifierFailed),
191            Some(MismatchKind::RepeatedEvidence),
192            None,
193        ] {
194            let guidance = revision_guidance(kind);
195            assert!(!guidance.is_empty(), "{kind:?} guidance must not be empty");
196            assert!(guidance.contains("hypothesis"), "{kind:?} guidance must name the hypothesis: {guidance}");
197            assert!(
198                guidance.to_ascii_lowercase().contains("revis"),
199                "{kind:?} guidance must name revision: {guidance}"
200            );
201        }
202        let empty = revision_guidance(Some(MismatchKind::EmptySearch));
203        assert!(empty.contains("new scope"), "empty search must redirect scope: {empty}");
204        let generic = revision_guidance(None);
205        assert_ne!(generic, revision_guidance(Some(MismatchKind::NonZeroExit)));
206        for shout in ["MUST", "NEVER", "ALWAYS", "CRITICAL", "IMPORTANT"] {
207            assert!(!generic.contains(shout), "unexpected shouting: {shout}");
208        }
209    }
210
211    #[test]
212    fn append_keeps_base_and_handles_empty_base() {
213        let appended = append_revision_guidance("Retry once.", Some(MismatchKind::NonZeroExit));
214        assert!(appended.starts_with("Retry once."));
215        assert!(appended.contains("hypothesis"));
216        assert!(appended.to_ascii_lowercase().contains("revis"));
217        let bare = append_revision_guidance("   ", None);
218        assert_eq!(bare, revision_guidance(None));
219    }
220}