Skip to main content

vibe/
diagnose.rs

1//! Agent diagnostic loop — parse + check, JSON out. No disk. No execute.
2
3use crate::check::{check_cell, check_program};
4#[allow(unused_imports)]
5pub use crate::check::fabric_guard::FabricSuggestedFix;
6use crate::error::Diagnostic;
7use crate::parse::{parse_cell, parse_program};
8
9/// Result of [`diagnose`].
10#[derive(Debug, Clone, PartialEq)]
11pub struct DiagnoseReport {
12    pub valid: bool,
13    pub kind: &'static str,
14    pub error: Option<Diagnostic>,
15    /// All diagnostics collected for this source (parse/check). The first
16    /// entry is the same as [`Self::error`] when present.
17    pub errors: Vec<Diagnostic>,
18}
19
20impl DiagnoseReport {
21    /// Converts to json.
22    pub fn to_json(&self) -> String {
23        if let Some(err) = &self.error {
24            format!(
25                "{{\"valid\":false,\"kind\":\"{}\",{},\"errors\":{}}}",
26                self.kind,
27                err.json_body(),
28                errors_json(&self.errors)
29            )
30        } else {
31            format!(
32                "{{\"valid\":true,\"kind\":\"{}\",\"error_code\":null,\"span\":null,\"message\":null,\"suggested_fix\":null,\"evidential\":null,\"shacl_violations\":[],\"errors\":[]}}",
33                self.kind
34            )
35        }
36    }
37}
38
39fn errors_json(errors: &[Diagnostic]) -> String {
40    let mut s = String::from("[");
41    for (i, error) in errors.iter().enumerate() {
42        if i > 0 {
43            s.push(',');
44        }
45        s.push('{');
46        s.push_str(&error.json_body());
47        s.push('}');
48    }
49    s.push(']');
50    s
51}
52
53/// Helper to detect if a diagnostic represents a contradiction or semantic conflict
54/// (e.g. conflicting types, conflicting graph assertions, forbidden effect in pure cell).
55pub fn is_contradiction(diag: &Diagnostic) -> bool {
56    match diag.code {
57        crate::error::DiagCode::E100
58        | crate::error::DiagCode::E200
59        | crate::error::DiagCode::E700 => true,
60        _ => {
61            let m = diag.message.to_ascii_lowercase();
62            m.contains("conflict") || m.contains("contradiction") || m.contains("mismatch")
63        }
64    }
65}
66
67/// Parse and type/effect-check. Cells start with `=`. Does not evaluate.
68/// When a contradiction/conflict is detected, attaches evidential annotations (μ = 1.0, λ = 0.0).
69pub fn diagnose(src: &str) -> DiagnoseReport {
70    let trimmed = src.trim_start_matches('\u{feff}').trim_start();
71    let mut report = if trimmed.starts_with('=') {
72        match parse_cell(src).and_then(|e| check_cell(&e).map(|_| e)) {
73            Ok(_) => DiagnoseReport {
74                valid: true,
75                kind: "cell",
76                error: None,
77                errors: Vec::new(),
78            },
79            Err(error) => DiagnoseReport {
80                valid: false,
81                kind: "cell",
82                errors: vec![error.clone()],
83                error: Some(error),
84            },
85        }
86    } else {
87        match parse_program(src).and_then(|p| check_program(&p).map(|_| p)) {
88            Ok(_) => DiagnoseReport {
89                valid: true,
90                kind: "module",
91                error: None,
92                errors: Vec::new(),
93            },
94            Err(error) => {
95                let extra = match parse_program(src) {
96                    Ok(p) => {
97                        let (_, mut all) = crate::check::check_program_all(&p);
98                        if all.is_empty() {
99                            all.push(error.clone());
100                        }
101                        all
102                    }
103                    Err(_) => collect_module_errors(src, &error),
104                };
105                DiagnoseReport {
106                    valid: false,
107                    kind: "module",
108                    errors: extra,
109                    error: Some(error),
110                }
111            }
112        }
113    };
114
115    if let Some(err) = report.error.as_mut() {
116        if is_contradiction(err) && err.evidential.is_none() {
117            err.evidential = Some((1.0, 0.0));
118        }
119    }
120
121    report
122}
123
124fn collect_module_errors(src: &str, first: &Diagnostic) -> Vec<Diagnostic> {
125    let Ok(program) = parse_program(src) else {
126        return vec![first.clone()];
127    };
128    let (_, mut all) = crate::check::check_program_all(&program);
129    if all.is_empty() {
130        all.push(first.clone());
131    }
132    all
133}
134
135#[cfg(test)]
136mod tests {
137    use super::*;
138    use crate::DiagCode;
139
140    #[test]
141    fn overlay_has_safe_fix() {
142        let r = diagnose("fn bad() { return <<[ s p o g prov ]>>; }");
143        assert!(!r.valid);
144        assert!(r.to_json().contains("suggested_fix"));
145        let err = r.error.as_ref().unwrap();
146        assert_eq!(err.code, DiagCode::E001);
147        assert!(err
148            .suggested_fix
149            .as_deref()
150            .unwrap()
151            .contains("quin.statement"));
152    }
153
154    #[test]
155    fn good_cell_is_valid() {
156        let r = diagnose("= math.max(0, 1)");
157        assert!(r.valid);
158        assert_eq!(r.kind, "cell");
159        assert!(r.to_json().contains("\"valid\":true"));
160    }
161
162    #[test]
163    fn contradiction_diagnostic_carries_evidential() {
164        // E200 effect contradiction: Pure cell performing External effect
165        let r = diagnose("= pulse.publish(\"t\", 1)");
166        assert!(!r.valid);
167        let err = r.error.as_ref().unwrap();
168        assert!(
169            err.evidential.is_some(),
170            "Contradiction diagnostic must carry evidential annotation"
171        );
172        let (mu, lambda) = err.evidential.unwrap();
173        assert_eq!(mu, 1.0);
174        assert_eq!(lambda, 0.0);
175    }
176
177    #[test]
178    fn syntax_error_does_not_carry_evidential() {
179        // E001 parse error: unclosed parenthesis
180        let r = diagnose("= math.max(1, ");
181        assert!(!r.valid);
182        let err = r.error.as_ref().unwrap();
183        assert_eq!(err.code, DiagCode::E001);
184        assert!(
185            err.evidential.is_none(),
186            "Syntax error must not carry evidential annotation"
187        );
188    }
189
190    #[test]
191    fn diagnostic_with_evidential_builder() {
192        let diag = Diagnostic::new(DiagCode::E100, crate::Span::point(0), "type conflict")
193            .with_evidential(0.85, 0.15);
194        assert_eq!(diag.evidential, Some((0.85, 0.15)));
195        assert!(diag.to_json().contains("\"evidential\":[0.85,0.15]"));
196    }
197
198    #[test]
199    fn diagnose_collects_multiple_module_errors() {
200        let r = diagnose(
201            r#"
202            fn a() { return HID.poll(); }
203            fn b() { return HID.poll(); }
204            fn c() { return HID.poll(); }
205            "#,
206        );
207        assert!(!r.valid);
208        assert!(
209            r.errors.len() >= 3,
210            "diagnose must collect per-item errors, got {}",
211            r.errors.len()
212        );
213        let json = r.to_json();
214        assert!(
215            json.contains("\"errors\":["),
216            "failure JSON must list errors[]"
217        );
218        assert!(json.contains("\"kind\":\"module\""));
219        assert!(json.contains("\"valid\":false"));
220        assert!(
221            json.matches("\"error_code\":").count() >= 4,
222            "primary diagnostic plus errors[] entries, got {json}"
223        );
224    }
225
226    #[test]
227    fn lexicon_missing_pack_helper_matches_held_json_shape() {
228        let src = include_str!("../fixtures/lexicon/missing_pack.vibe");
229        let expected = include_str!("../fixtures/lexicon/missing_pack.diagnose.json");
230        let r = crate::diagnose_lexicon_pin(src, false);
231        let json = r.to_json();
232        assert!(!r.valid);
233        assert_eq!(r.kind, "module");
234        let err = r.error.as_ref().unwrap();
235        assert_eq!(err.code, DiagCode::E300);
236        assert_eq!(err.suggested_fix.as_deref(), Some(crate::HELD_OPEN_PACK));
237        assert!(json.contains("\"error_code\":\"E300\""));
238        assert!(json.contains("held / not yet"));
239        assert!(json.contains("open lexicon pack"));
240        assert!(json.contains("\"errors\":["));
241        assert!(!json.to_ascii_lowercase().contains("broken"));
242        for needle in [
243            "\"valid\": false",
244            "\"kind\": \"module\"",
245            "\"error_code\": \"E300\"",
246            "held / not yet — open lexicon pack",
247        ] {
248            assert!(
249                expected.contains(needle),
250                "fixture DiagnoseReport JSON must document {needle}"
251            );
252        }
253        // parse+check of the workshop file stays valid (no disk / no invoke)
254        let parse_r = diagnose(src);
255        assert!(
256            parse_r.valid,
257            "diagnose() must not invoke lexicon_manifest: {}",
258            parse_r.to_json()
259        );
260    }
261
262    #[test]
263    fn lexicon_pin_ok_records_en_core() {
264        let src = include_str!("../fixtures/lexicon/pin_ok.vibe");
265        let pin = crate::parse_lexicon_pin_from_source(src).expect("pin");
266        assert_eq!(pin.as_pin_str(), crate::EXAMPLE_PIN);
267        assert_eq!(pin.pack_id, "en-core");
268        assert_eq!(pin.pack_semver, "0.1.0");
269        let hook = crate::diagnose_lexicon_pin(src, true);
270        assert!(hook.valid);
271        let r = diagnose(src);
272        assert!(r.valid, "pin_ok diagnose: {}", r.to_json());
273        assert_eq!(crate::LANGUAGE_VERSION, "vibe-0.1");
274        assert_eq!(crate::HOST_VERSION, "vibe-host-0.1");
275    }
276
277    #[test]
278    fn lexicon_alias_row_round_trip_in_suggested_fix() {
279        let src = include_str!("../fixtures/lexicon/alias_rows.json");
280        let rows = crate::parse_alias_rows_json(src);
281        assert_eq!(rows.len(), 3);
282        assert_eq!(rows[0].from, "arrive");
283        assert_eq!(rows[0].to, "concept:arrive");
284        assert_eq!(rows[0].framing, crate::LexiconFraming::LivingShacl);
285        assert_eq!(rows[1].framing, crate::LexiconFraming::Mixed);
286        assert_eq!(rows[2].framing, crate::LexiconFraming::ArtifactOwl);
287        let report = crate::alias_migrate_report(crate::Span::point(0), &rows);
288        let fix = report
289            .error
290            .as_ref()
291            .unwrap()
292            .suggested_fix
293            .as_deref()
294            .unwrap();
295        let back = crate::parse_alias_rows_json(fix);
296        assert_eq!(back, rows);
297        assert!(fix.contains("\"from\":\"arrive\""));
298        assert!(fix.contains("\"to\":\"concept:arrive\""));
299        assert!(fix.contains("living-SHACL"));
300        let json = report.to_json();
301        assert!(json.contains("suggested_fix"));
302        assert!(json.contains("living-SHACL"));
303    }
304
305    #[test]
306    fn lexicon_living_upgrade_never_rewritten_as_artifact() {
307        let src = include_str!("../fixtures/lexicon/upgrade_living.json");
308        let before = crate::parse_alias_rows_json(src);
309        let living: Vec<_> = before
310            .iter()
311            .filter(|r| r.framing == crate::LexiconFraming::LivingShacl)
312            .cloned()
313            .collect();
314        assert!(!living.is_empty());
315        let requested = vec![crate::LexiconFraming::ArtifactOwl; before.len()];
316        let after = crate::apply_upgrade_map(&before, &requested);
317        assert!(!crate::living_rewritten_as_artifact(&before, &after));
318        for row in &after {
319            if living.iter().any(|l| l.from == row.from) {
320                assert_eq!(
321                    row.framing,
322                    crate::LexiconFraming::LivingShacl,
323                    "{} must stay living-SHACL",
324                    row.from
325                );
326            }
327        }
328    }
329}