Skip to main content

vtcode_commons/
diagnostics.rs

1//! Sanitize the canonical payload before persistence, logging, and display.
2pub use vtcode_exec_events::{Diagnostic, DiagnosticAction, DiagnosticSeverity};
3
4use crate::ui_protocol::CommunicationStyle;
5
6/// Apply the existing secret redaction to every externally supplied field.
7/// Call before emitting a `ThreadEvent`, not merely when drawing its UI.
8pub fn redact_diagnostic(diagnostic: &Diagnostic) -> Diagnostic {
9    use crate::sanitizer::redact_secrets;
10    let mut redacted = diagnostic.clone();
11    redacted.code = redact_secrets(redacted.code);
12    redacted.summary = redact_secrets(redacted.summary);
13    redacted.agent_details = redact_secrets(redacted.agent_details);
14    redacted.correlation_id = redact_secrets(redacted.correlation_id);
15    for action in &mut redacted.actions {
16        action.id = redact_secrets(std::mem::take(&mut action.id));
17        action.label = redact_secrets(std::mem::take(&mut action.label));
18    }
19    redacted
20}
21
22/// Adapt legacy styled messages without dropping evidence after the summary.
23/// Correlation identity belongs to the producer; this adapter does not authorize actions.
24pub fn legacy_diagnostic(severity: DiagnosticSeverity, text: &str, correlation_id: String) -> Diagnostic {
25    // Styled renderer lines carry ANSI color: strip it so durable fields stay
26    // plain and escape bytes do not push a short summary over the length cap.
27    let text = crate::sanitizer::redact_secrets(crate::ansi::strip_ansi_codes(text).into_owned());
28    let mut lines = text.trim().splitn(2, '\n');
29    let first = lines.next().unwrap_or_default();
30    let (summary, details) = if first.len() <= 180 {
31        (first.to_owned(), lines.next().unwrap_or_default().to_owned())
32    } else {
33        let summary = match severity {
34            DiagnosticSeverity::Info => "Additional information is available. Expand Details for the full message.",
35            DiagnosticSeverity::Warning => "A warning needs attention. Expand Details for the full message.",
36            DiagnosticSeverity::Error => "An error needs attention. Expand Details for the full message.",
37        };
38        (summary.to_owned(), text.trim().to_owned())
39    };
40    let code = match severity {
41        DiagnosticSeverity::Info => "runtime.info",
42        DiagnosticSeverity::Warning => "runtime.warning",
43        DiagnosticSeverity::Error => "runtime.error",
44    };
45    Diagnostic {
46        severity,
47        code: code.into(),
48        summary,
49        agent_details: details,
50        correlation_id,
51        actions: Vec::new(),
52    }
53}
54
55/// Early-startup/headless diagnostic boundary before a thread event sink exists.
56/// Formatting and redaction finish before stderr is touched.
57pub fn stderr(arguments: std::fmt::Arguments<'_>) {
58    let text = arguments.to_string();
59    let lower = text.to_ascii_lowercase();
60    let severity = if lower.contains("warn") || lower.contains("cancel") {
61        DiagnosticSeverity::Warning
62    } else {
63        DiagnosticSeverity::Error
64    };
65    let diagnostic = legacy_diagnostic(severity, &text, "startup".into());
66    stderr_diagnostic(&diagnostic);
67}
68
69/// Render a canonical diagnostic before any terminal UI is available.
70pub fn stderr_diagnostic(diagnostic: &Diagnostic) {
71    eprintln!("{}", redact_diagnostic(diagnostic).text());
72}
73
74/// Session-local observer shared by clones of one inline handle.
75pub type DiagnosticSink = std::sync::Arc<dyn Fn(&Diagnostic) -> anyhow::Result<()> + Send + Sync>;
76
77#[derive(Clone, Default)]
78pub struct DiagnosticObserver(std::sync::Arc<std::sync::RwLock<DiagnosticObserverState>>);
79
80#[derive(Default)]
81struct DiagnosticObserverState {
82    sink: Option<DiagnosticSink>,
83    recent: std::collections::VecDeque<Diagnostic>,
84}
85
86impl std::fmt::Debug for DiagnosticObserver {
87    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
88        formatter.write_str("DiagnosticObserver")
89    }
90}
91
92impl DiagnosticObserver {
93    pub fn set_sink(&self, sink: DiagnosticSink) -> anyhow::Result<()> {
94        let mut observer = self
95            .0
96            .write()
97            .map_err(|error| anyhow::anyhow!("diagnostic observer lock poisoned: {error}"))?;
98        observer.sink = Some(sink);
99        observer.recent.clear();
100        Ok(())
101    }
102
103    fn notify(&self, diagnostic: &Diagnostic) -> anyhow::Result<()> {
104        let sink = {
105            let observer = self
106                .0
107                .read()
108                .map_err(|error| anyhow::anyhow!("diagnostic observer lock poisoned: {error}"))?;
109            if observer.recent.iter().any(|previous| previous == diagnostic) {
110                return Ok(());
111            }
112            observer.sink.clone()
113        };
114        let Some(sink) = sink else {
115            return Ok(());
116        };
117        sink(diagnostic)?;
118        let mut observer = self
119            .0
120            .write()
121            .map_err(|error| anyhow::anyhow!("diagnostic observer lock poisoned: {error}"))?;
122        observer
123            .recent
124            .retain(|previous| previous.correlation_id != diagnostic.correlation_id);
125        if observer.recent.len() == 128 {
126            let _ = observer.recent.pop_front();
127        }
128        observer.recent.push_back(diagnostic.clone());
129        Ok(())
130    }
131
132    /// Void UI APIs report observer failures visibly and through sanitized telemetry.
133    pub fn prepare(&self, diagnostic: &Diagnostic) -> Diagnostic {
134        let mut diagnostic = redact_diagnostic(diagnostic);
135        let result = self.notify(&diagnostic);
136        if let Err(error) = result {
137            let message = crate::sanitizer::sanitize_provider_diagnostic(error.to_string());
138            tracing::warn!(error = %message, "canonical diagnostic persistence failed");
139            if !diagnostic.agent_details.is_empty() {
140                diagnostic.agent_details.push_str("\n\n");
141            }
142            diagnostic
143                .agent_details
144                .push_str("Diagnostic persistence failed; this message may not be saved.\n");
145            diagnostic.agent_details.push_str(&message);
146        }
147        diagnostic
148    }
149}
150
151/// Legacy calls represent separate incidents. Producers updating one incident
152/// supply an explicit correlation identity through `Diagnostic` instead.
153pub fn legacy_ui_diagnostic(severity: DiagnosticSeverity, text: &str) -> Diagnostic {
154    legacy_diagnostic(severity, text, format!("legacy-{:032x}", rand::random::<u128>()))
155}
156
157/// Diagnostic codes that carry routine agent-internal failure evidence: the
158/// agent loop consumes them, but they need no main-transcript row under the
159/// default style. Everything else fails open to visible.
160const ROUTINE_SILENT_CODES: &[&str] = &[
161    // Agent-internal tool failure (preflight/validation/retry); the owning
162    // tool row keeps its failed state and Review keeps the evidence.
163    "tool.execution_failed",
164    // Transient provider retry progress; the spinner already covers it.
165    "provider.retrying",
166    // A recovered retry is good news, not an incident.
167    "provider.retry_succeeded",
168];
169
170/// Diagnostic code prefixes owned by the runtime itself: persisted evidence
171/// for audits (`vtcode session-store lifecycle-check`, trajectory review), not
172/// user-facing incidents.
173const INTERNAL_CODE_PREFIXES: &[&str] = &["lifecycle."];
174
175fn is_routine_silent(code: &str) -> bool {
176    ROUTINE_SILENT_CODES.contains(&code) || INTERNAL_CODE_PREFIXES.iter().any(|prefix| code.starts_with(prefix))
177}
178
179/// Whether a diagnostic earns a main-transcript row under `style`.
180///
181/// Contract: persistence is never gated by this — callers persist the
182/// canonical event first and consult this only at paint time. Unknown codes
183/// fail open to visible; only the classified routine codes above (plus
184/// `tool.command_failed` under `Quiet`) go silent.
185/// `tool.policy_denied`, `tool.cancelled`, `provider.retry_stopped`, billing,
186/// planning, MCP, and `runtime.*` incidents stay visible in every style.
187#[must_use]
188pub fn diagnostic_is_user_visible(style: CommunicationStyle, code: &str) -> bool {
189    match style.resolve() {
190        CommunicationStyle::Verbose => true,
191        CommunicationStyle::Balanced => !is_routine_silent(code),
192        CommunicationStyle::Quiet => code != "tool.command_failed" && !is_routine_silent(code),
193        // `resolve` maps `Unknown` to `Balanced`; this arm is unreachable but
194        // keeps the decision total if the mapping ever changes.
195        CommunicationStyle::Unknown => !is_routine_silent(code),
196    }
197}
198
199#[cfg(test)]
200mod tests {
201    use super::*;
202    /// Lifecycle violations are audit evidence, not user incidents: persisted
203    /// always, painted only under the verbose style.
204    #[test]
205    fn lifecycle_diagnostics_stay_out_of_the_default_transcript() {
206        for code in ["lifecycle.open_item_at_terminal", "lifecycle.duplicate_item_completed"] {
207            assert!(!diagnostic_is_user_visible(CommunicationStyle::Balanced, code), "{code}");
208            assert!(!diagnostic_is_user_visible(CommunicationStyle::Quiet, code), "{code}");
209            assert!(diagnostic_is_user_visible(CommunicationStyle::Verbose, code), "{code}");
210        }
211        // Boundary: a code that merely contains the word stays visible.
212        assert!(diagnostic_is_user_visible(CommunicationStyle::Balanced, "runtime.lifecycle.failed"));
213        assert!(diagnostic_is_user_visible(CommunicationStyle::Balanced, "tool.policy_denied"));
214    }
215
216    #[test]
217    fn legacy_diagnostics_persist_plain_text_without_ansi_styling() {
218        // Session 20261119T075728Z: a styled provider 404 reached the event
219        // log with escape bytes and only the generic summary.
220        let styled = "LLM request failed: \u{1b}[2m\u{1b}[36mMerge Gateway\u{1b}[0m \u{1b}[31mHTTP 404 Not Found: model_not_found\u{1b}[0m";
221        let diagnostic = legacy_diagnostic(DiagnosticSeverity::Error, styled, "c".into());
222        assert_eq!(diagnostic.summary, "LLM request failed: Merge Gateway HTTP 404 Not Found: model_not_found");
223        assert!(!diagnostic.agent_details.contains('\u{1b}'));
224    }
225    #[test]
226    fn repeated_legacy_failures_are_distinct_incidents_but_explicit_incidents_deduplicate() {
227        let observer = DiagnosticObserver::default();
228        let captured = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
229        let output = captured.clone();
230        observer
231            .set_sink(std::sync::Arc::new(move |diagnostic| {
232                output.lock().unwrap().push(diagnostic.clone());
233                Ok(())
234            }))
235            .unwrap();
236        let mut ids = Vec::new();
237        for _ in 0..2 {
238            let diagnostic = legacy_ui_diagnostic(DiagnosticSeverity::Warning, "Clipboard unavailable");
239            ids.push(observer.prepare(&diagnostic).correlation_id);
240        }
241        assert_ne!(ids[0], ids[1], "a repeated command failure is a new incident");
242        let explicit = legacy_diagnostic(DiagnosticSeverity::Warning, "Retrying", "request-1".into());
243        assert_eq!(observer.prepare(&explicit), explicit);
244        assert_eq!(observer.prepare(&explicit), explicit);
245        assert_eq!(captured.lock().unwrap().len(), 3);
246    }
247    #[test]
248    fn diagnostic_redacts_summary_details_and_actions() {
249        let diagnostic = Diagnostic {
250            severity: DiagnosticSeverity::Error,
251            code: "provider.failure".into(),
252            summary: "Authorization: Bearer secret-summary-value".into(),
253            agent_details: "password=secret-detail-value".into(),
254            correlation_id: "request-2".into(),
255            actions: vec![DiagnosticAction {
256                id: "retry".into(),
257                label: "api_key=secret-action-value".into(),
258            }],
259        };
260        let text = serde_json::to_string(&redact_diagnostic(&diagnostic)).unwrap();
261        for secret in ["secret-summary-value", "secret-detail-value", "secret-action-value"] {
262            assert!(!text.contains(secret), "leaked {secret}");
263        }
264        assert!(text.contains("provider.failure"));
265        assert!(text.contains("request-2"));
266    }
267    #[test]
268    fn communication_style_visibility_silences_only_routine_codes() {
269        use crate::ui_protocol::CommunicationStyle;
270        // Asymmetric matrix: every style sees both a silent and a visible code
271        // except Verbose, which is the deliberate show-everything escape hatch.
272        for (style, code, visible) in [
273            (CommunicationStyle::Balanced, "tool.execution_failed", false),
274            (CommunicationStyle::Balanced, "provider.retrying", false),
275            (CommunicationStyle::Balanced, "provider.retry_succeeded", false),
276            (CommunicationStyle::Balanced, "tool.command_failed", true),
277            (CommunicationStyle::Balanced, "tool.policy_denied", true),
278            (CommunicationStyle::Balanced, "tool.cancelled", true),
279            (CommunicationStyle::Balanced, "provider.retry_stopped", true),
280            (CommunicationStyle::Balanced, "provider.stream_billing_advisory", true),
281            (CommunicationStyle::Balanced, "planning.awaiting_input", true),
282            (CommunicationStyle::Balanced, "mcp.catalog_failed", true),
283            (CommunicationStyle::Balanced, "runtime.error", true),
284            (CommunicationStyle::Quiet, "tool.execution_failed", false),
285            (CommunicationStyle::Quiet, "tool.command_failed", false),
286            (CommunicationStyle::Quiet, "tool.policy_denied", true),
287            (CommunicationStyle::Quiet, "provider.retry_stopped", true),
288            (CommunicationStyle::Verbose, "tool.execution_failed", true),
289            (CommunicationStyle::Verbose, "provider.retrying", true),
290            (CommunicationStyle::Verbose, "tool.command_failed", true),
291            // Fail-open: an unknown future code is visible everywhere.
292            (CommunicationStyle::Balanced, "tool.something_new", true),
293            (CommunicationStyle::Quiet, "tool.something_new", true),
294            // An unknown future style degrades to Balanced, never to silence.
295            (CommunicationStyle::Unknown, "tool.execution_failed", false),
296            (CommunicationStyle::Unknown, "tool.command_failed", true),
297        ] {
298            assert_eq!(
299                diagnostic_is_user_visible(style, code),
300                visible,
301                "{style:?} must treat {code} as visible={visible}"
302            );
303        }
304    }
305
306    #[test]
307    fn communication_style_parse_round_trips_and_falls_back_to_unknown() {
308        use crate::ui_protocol::CommunicationStyle;
309        for (text, expected) in [
310            ("balanced", CommunicationStyle::Balanced),
311            ("  Quiet ", CommunicationStyle::Quiet),
312            ("VERBOSE", CommunicationStyle::Verbose),
313            ("", CommunicationStyle::Unknown),
314            ("terse", CommunicationStyle::Unknown),
315        ] {
316            assert_eq!(CommunicationStyle::parse(text), expected, "parse({text:?})");
317        }
318        assert_eq!(CommunicationStyle::Unknown.resolve(), CommunicationStyle::Balanced);
319        assert_eq!(CommunicationStyle::default(), CommunicationStyle::Balanced);
320        assert_eq!(
321            serde_json::from_value::<CommunicationStyle>(serde_json::json!("verbose")).unwrap(),
322            CommunicationStyle::Verbose
323        );
324        assert_eq!(
325            serde_json::from_value::<CommunicationStyle>(serde_json::json!("future-style")).unwrap(),
326            CommunicationStyle::Unknown
327        );
328    }
329
330    #[test]
331    fn diagnostic_long_message_preserves_complete_command_and_short_message_body() {
332        let command =
333            format!("Run `/a/very/long/path/{} --exact` to recover.\nExpected: exit zero.", "segment/".repeat(40));
334        let diagnostic = legacy_diagnostic(DiagnosticSeverity::Error, &command, "incident-7".into());
335        assert_eq!(diagnostic.summary, "An error needs attention. Expand Details for the full message.");
336        assert_eq!(diagnostic.agent_details, command);
337        let short =
338            legacy_diagnostic(DiagnosticSeverity::Warning, "Retry needs input.\nAttempts: 3", "incident-8".into());
339        assert_eq!(short.summary, "Retry needs input.");
340        assert_eq!(short.agent_details, "Attempts: 3");
341    }
342}