Skip to main content

vibe/
error.rs

1//! Stable diagnostic codes (vibescript-core.md §9).
2
3use crate::span::Span;
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6pub enum DiagCode {
7    /// Parse / lex
8    E001,
9    /// Type
10    E100,
11    /// Effect
12    E200,
13    /// Capability
14    E300,
15    /// Budget / unbounded loop
16    E400,
17    /// Policy
18    E500,
19    /// Evaluation
20    E600,
21    /// Deontic phase violation (R2)
22    E700,
23    /// Assignment to immutable binding (T10)
24    E701,
25    /// Clock unavailable on this host (T18)
26    E702,
27    /// Disclosure denied — a credentialed refusal (R10).
28    /// The agent/host refused to disclose content because the requester
29    /// lacks the required capability, consent, or authority. This is not
30    /// a "file not found" error — it is a first-class rights enforcement
31    /// value.
32    E800,
33}
34
35impl DiagCode {
36    /// `str` form.
37    pub fn as_str(self) -> &'static str {
38        match self {
39            DiagCode::E001 => "E001",
40            DiagCode::E100 => "E100",
41            DiagCode::E200 => "E200",
42            DiagCode::E300 => "E300",
43            DiagCode::E400 => "E400",
44            DiagCode::E500 => "E500",
45            DiagCode::E600 => "E600",
46            DiagCode::E700 => "E700",
47            DiagCode::E701 => "E701",
48            DiagCode::E702 => "E702",
49            DiagCode::E800 => "E800",
50        }
51    }
52}
53
54#[derive(Debug, Clone, PartialEq)]
55pub struct Diagnostic {
56    pub code: DiagCode,
57    pub span: Span,
58    pub message: String,
59    /// Safe rewrite hint. MUST NOT grant new authority (core §9).
60    pub suggested_fix: Option<String>,
61    /// Evidential (μ, λ) annotation: degrees of positive belief and refutation (G9).
62    pub evidential: Option<(f32, f32)>,
63}
64
65impl Diagnostic {
66    /// Creates a new `Diagnostic`.
67    pub fn new(code: DiagCode, span: Span, message: impl Into<String>) -> Self {
68        let message = message.into();
69        let suggested_fix = infer_fix(code, &message);
70        Self {
71            code,
72            span,
73            message,
74            suggested_fix,
75            evidential: None,
76        }
77    }
78
79    /// Builder — sets fix.
80    pub fn with_fix(mut self, fix: impl Into<String>) -> Self {
81        self.suggested_fix = Some(fix.into());
82        self
83    }
84
85    /// Create a disclosure-denied diagnostic (R10).
86    pub fn disclosure_denied(span: Span, capability: &str, reason: &str) -> Self {
87        Diagnostic::new(
88            DiagCode::E800,
89            span,
90            format!(
91                "disclosure denied: capability '{}' — {}",
92                capability, reason
93            ),
94        )
95    }
96
97    /// Set the evidential (μ, λ) annotation: degrees of positive belief and refutation.
98    pub fn with_evidential(mut self, mu: f32, lambda: f32) -> Self {
99        self.evidential = Some((mu, lambda));
100        self
101    }
102
103    /// Civics surface code (UE-062).
104    ///
105    /// Vibe keeps internal `E300` (capability / lease). Civics docs and UI map
106    /// lease failures to **E0403**. Other codes pass through as their Vibe token.
107    pub fn civics_code(&self) -> &'static str {
108        match self.code {
109            DiagCode::E300 => "E0403",
110            other => other.as_str(),
111        }
112    }
113
114    /// Object fields shared by a lone diagnostic and `DiagnoseReport.errors[]`.
115    /// No surrounding braces; no trailing comma.
116    pub(crate) fn json_body(&self) -> String {
117        let mut s = String::new();
118        push_kv(&mut s, "error_code", self.code.as_str());
119        push_kv(&mut s, "civics_code", self.civics_code());
120        s.push_str(&format!(
121            "\"span\":[{},{}],",
122            self.span.start, self.span.end
123        ));
124        push_kv(&mut s, "message", &self.message);
125        match &self.suggested_fix {
126            Some(fix) => push_kv(&mut s, "suggested_fix", fix),
127            None => s.push_str("\"suggested_fix\":null,"),
128        }
129        match self.evidential {
130            Some((mu, lambda)) => s.push_str(&format!("\"evidential\":[{},{}],", mu, lambda)),
131            None => s.push_str("\"evidential\":null,"),
132        }
133        s.push_str("\"shacl_violations\":[]");
134        s
135    }
136
137    /// Agent-facing JSON (no serde). Always includes `valid: false`.
138    pub fn to_json(&self) -> String {
139        let mut s = String::from("{\"valid\":false,");
140        s.push_str(&self.json_body());
141        s.push('}');
142        s
143    }
144}
145
146fn infer_fix(code: DiagCode, message: &str) -> Option<String> {
147    let m = message.to_ascii_lowercase();
148    if m.contains("<<[") || m.contains("raw quin") {
149        return Some(
150            "use quin.statement(subject, predicate, object, context) — <<[ overlay is illegal"
151                .into(),
152        );
153    }
154    if m.contains("without space") || (m.contains("relational") && m.contains('<')) {
155        return Some("put spaces around < > <= >=".into());
156    }
157    if m.contains("unclosed") && m.contains("triple") {
158        return Some("close the term with )>> or >>".into());
159    }
160    if m.contains("unclosed block comment") {
161        return Some("close the comment with */".into());
162    }
163    if code == DiagCode::E200 && m.contains("pure cell") {
164        return Some("move the External call into an effect fn; cells stay Pure".into());
165    }
166    if code == DiagCode::E300 {
167        if m.contains("lexicon") {
168            return Some("held / not yet — open lexicon pack".into());
169        }
170        if m.contains("graph.write") {
171            return Some("add requires [ capability(\"graph.write\") ];".into());
172        }
173        return Some("add `using Family;` or requires [ capability(\"id\") ];".into());
174    }
175    if m.contains("take") && (m.contains("query") || m.contains("unbounded")) {
176        return Some("add take: N to graph.query".into());
177    }
178    if code == DiagCode::E400 {
179        return Some("add budget(steps: N) or a loop bound".into());
180    }
181    if code == DiagCode::E800 {
182        return Some("request the required capability or consent from the principal".into());
183    }
184    None
185}
186
187fn push_kv(out: &mut String, key: &str, value: &str) {
188    out.push('"');
189    out.push_str(key);
190    out.push_str("\":\"");
191    for c in value.chars() {
192        match c {
193            '"' => out.push_str("\\\""),
194            '\\' => out.push_str("\\\\"),
195            '\n' => out.push_str("\\n"),
196            '\r' => out.push_str("\\r"),
197            '\t' => out.push_str("\\t"),
198            c => out.push(c),
199        }
200    }
201    out.push_str("\",");
202}
203
204impl std::fmt::Display for Diagnostic {
205    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
206        write!(
207            f,
208            "{}@{}..{}: {}",
209            self.code.as_str(),
210            self.span.start,
211            self.span.end,
212            self.message
213        )
214    }
215}
216
217impl std::error::Error for Diagnostic {}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn disclosure_denied_creates_e800() {
225        let diag = Diagnostic::disclosure_denied(
226            Span::point(12),
227            "graph.read.classified",
228            "principal consent token missing",
229        );
230        assert_eq!(diag.code, DiagCode::E800);
231        assert_eq!(diag.code.as_str(), "E800");
232        assert!(diag.message.contains("graph.read.classified"));
233        assert!(diag.message.contains("principal consent token missing"));
234    }
235
236    #[test]
237    fn e300_maps_to_civics_e0403() {
238        let diag = Diagnostic::new(DiagCode::E300, Span::point(0), "lease required");
239        assert_eq!(diag.civics_code(), "E0403");
240        assert_eq!(diag.code.as_str(), "E300");
241    }
242
243    #[test]
244    fn disclosure_denied_has_suggested_fix() {
245        let diag = Diagnostic::disclosure_denied(
246            Span::point(0),
247            "sensor.biometric",
248            "unauthorized requester",
249        );
250        assert!(diag.suggested_fix.is_some());
251        assert!(diag
252            .suggested_fix
253            .as_deref()
254            .unwrap()
255            .contains("request the required capability or consent"));
256    }
257}