//! Diagnostics: stable codes, deterministic ordering, human rendering. //! //! A diagnostic always names a stable `knowledge.*` code, a severity, an //! optional root-relative path and an optional exact byte span. Diagnostics do //! not print source text and never contain machine absolute paths. use crate::model::Span; use serde::{Deserialize, Serialize}; use std::fmt; /// Stable diagnostic codes. Adding a code is an interface change. pub mod code { // Input and scope. pub const INVALID_ROOT: &str = "knowledge.invalid_root"; pub const SCOPE_ESCAPE: &str = "knowledge.scope_escape"; pub const SYMLINK_SKIPPED: &str = "knowledge.symlink_skipped"; pub const EXCLUDED_PATH: &str = "knowledge.excluded_path"; pub const BUDGET_EXCEEDED: &str = "knowledge.budget_exceeded"; pub const INVALID_UTF8: &str = "knowledge.invalid_utf8"; pub const IO: &str = "knowledge.io"; pub const SOURCE_CHANGED: &str = "knowledge.source_changed"; // Core CLI integration. pub const NOT_LAUNCHED_BY_MARQDO: &str = "knowledge.not_launched_by_marqdo"; pub const CORE_CLI_MISSING: &str = "knowledge.core_cli_missing"; pub const CORE_CLI_FAILED: &str = "knowledge.core_cli_failed"; pub const CORE_CLI_TIMEOUT: &str = "knowledge.core_cli_timeout"; pub const ANALYSIS_MISSING: &str = "knowledge.analysis_missing"; pub const ANALYSIS_INVALID: &str = "knowledge.analysis_invalid"; pub const ANALYSIS_UNSUPPORTED: &str = "knowledge.analysis_unsupported"; pub const ANALYSIS_CONTEXT_CONFLICT: &str = "knowledge.analysis_context_conflict"; // Documents. pub const MARKDOWN_INVALID: &str = "knowledge.markdown_invalid"; pub const MARQDO_INVALID: &str = "knowledge.marqdo_invalid"; pub const OKF_INVALID: &str = "knowledge.okf_invalid"; pub const OKF_UNVERIFIED: &str = "knowledge.okf_unverified"; pub const UNKNOWN_FRONT_MATTER: &str = "knowledge.unknown_front_matter"; // Graph and references. pub const REFERENCE_MISSING: &str = "knowledge.reference_missing"; pub const REFERENCE_AMBIGUOUS: &str = "knowledge.reference_ambiguous"; pub const REFERENCE_OUT_OF_SCOPE: &str = "knowledge.reference_out_of_scope"; pub const REFERENCE_INVALID: &str = "knowledge.reference_invalid"; pub const REFERENCE_EXTERNAL: &str = "knowledge.reference_external"; pub const REFERENCE_NOT_LOADED: &str = "knowledge.reference_not_loaded"; pub const IDENTITY_AMBIGUOUS: &str = "knowledge.identity_ambiguous"; pub const INTERFACE_CONFLICT: &str = "knowledge.interface_conflict"; // Storage and freshness. pub const DATABASE_MISSING: &str = "knowledge.database_missing"; pub const DATABASE_OLD_SCHEMA: &str = "knowledge.database_old_schema"; pub const DATABASE_NOT_OURS: &str = "knowledge.database_not_ours"; pub const DATABASE_CORRUPT: &str = "knowledge.database_corrupt"; pub const DATABASE_STALE: &str = "knowledge.database_stale"; pub const SNAPSHOT_STALE: &str = "knowledge.snapshot_stale"; pub const REBUILD_REQUIRED: &str = "knowledge.rebuild_required"; // Query. pub const QUERY_INVALID: &str = "knowledge.query_invalid"; pub const QUERY_NO_RESULTS: &str = "knowledge.query_no_results"; pub const QUERY_UNSUPPORTED: &str = "knowledge.query_unsupported"; pub const SLICE_SEED_AMBIGUOUS: &str = "knowledge.slice_seed_ambiguous"; pub const SLICE_SEED_MISSING: &str = "knowledge.slice_seed_missing"; pub const BUDGET: &str = "knowledge.budget"; // Embeddings. pub const EMBEDDING_DISABLED: &str = "knowledge.embedding_disabled"; pub const EMBEDDING_CONFIG_MISMATCH: &str = "knowledge.embedding_config_mismatch"; pub const EMBEDDING_REMOTE_NOT_ALLOWED: &str = "knowledge.embedding_remote_not_allowed"; pub const EMBEDDING_TRANSPORT: &str = "knowledge.embedding_transport"; pub const EMBEDDING_INVALID_RESPONSE: &str = "knowledge.embedding_invalid_response"; pub const EMBEDDING_UNAVAILABLE: &str = "knowledge.embedding_unavailable"; // Usage. pub const USAGE: &str = "knowledge.usage"; pub const NOT_IMPLEMENTED: &str = "knowledge.not_implemented"; pub const INTERNAL: &str = "knowledge.internal"; pub const COMPILATION_FAILED: &str = "knowledge.compilation_failed"; } #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Severity { Error, Warning, } impl Severity { pub fn as_str(self) -> &'static str { match self { Severity::Error => "error", Severity::Warning => "warning", } } } /// One deterministic diagnostic. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Diagnostic { pub code: String, pub severity: Severity, pub path: Option, pub span: Option, pub message: String, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub hints: Vec, } impl Diagnostic { pub fn error(code: &str, message: impl Into) -> Self { Self { code: code.to_string(), severity: Severity::Error, path: None, span: None, message: message.into(), hints: Vec::new(), } } pub fn warning(code: &str, message: impl Into) -> Self { Self { code: code.to_string(), severity: Severity::Warning, path: None, span: None, message: message.into(), hints: Vec::new(), } } pub fn with_path(mut self, path: impl Into) -> Self { self.path = Some(path.into()); self } pub fn with_span(mut self, span: Span) -> Self { self.span = Some(span); self } pub fn with_hint(mut self, hint: impl Into) -> Self { self.hints.push(hint.into()); self } pub fn is_error(&self) -> bool { self.severity == Severity::Error } } impl fmt::Display for Diagnostic { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{} [{}]", self.severity.as_str(), self.code)?; if let Some(path) = &self.path { write!(f, " {path}")?; if let Some(span) = self.span { write!(f, ":{span}")?; } } write!(f, ": {}", self.message)?; for hint in &self.hints { write!(f, "\n hint: {hint}")?; } Ok(()) } } /// A deterministic diagnostic collection. #[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)] #[serde(transparent)] pub struct DiagnosticSet { items: Vec, } impl DiagnosticSet { pub fn new() -> Self { Self::default() } pub fn push(&mut self, diagnostic: Diagnostic) { self.items.push(diagnostic); } pub fn extend(&mut self, other: impl IntoIterator) { self.items.extend(other); } pub fn merge(&mut self, mut other: DiagnosticSet) { self.items.append(&mut other.items); } pub fn is_empty(&self) -> bool { self.items.is_empty() } pub fn len(&self) -> usize { self.items.len() } pub fn has_errors(&self) -> bool { self.items.iter().any(Diagnostic::is_error) } pub fn error_count(&self) -> usize { self.items.iter().filter(|d| d.is_error()).count() } pub fn warning_count(&self) -> usize { self.items.iter().filter(|d| !d.is_error()).count() } pub fn iter(&self) -> impl Iterator { self.items.iter() } pub fn into_vec(self) -> Vec { self.items } pub fn as_slice(&self) -> &[Diagnostic] { &self.items } /// Sort by path, span start, code, then message for stable output and /// stable logical digests. pub fn sorted(&mut self) { self.items.sort_by(|a, b| { a.path .cmp(&b.path) .then(a.span.map(|s| s.start).cmp(&b.span.map(|s| s.start))) .then(a.span.map(|s| s.end).cmp(&b.span.map(|s| s.end))) .then(a.code.cmp(&b.code)) .then(a.message.cmp(&b.message)) }); self.items.dedup(); } } impl IntoIterator for DiagnosticSet { type Item = Diagnostic; type IntoIter = std::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.items.into_iter() } } #[cfg(test)] mod tests { use super::*; #[test] fn diagnostics_sort_deterministically() { let mut set = DiagnosticSet::new(); set.push( Diagnostic::error(code::IO, "b") .with_path("a.md") .with_span(Span::new(5, 8)), ); set.push( Diagnostic::error(code::IO, "a") .with_path("a.md") .with_span(Span::new(1, 2)), ); set.push(Diagnostic::warning(code::OKF_UNVERIFIED, "w").with_path("b.md")); set.sorted(); let paths: Vec<_> = set.iter().map(|d| d.path.as_deref().unwrap()).collect(); assert_eq!(paths, vec!["a.md", "a.md", "b.md"]); assert_eq!(set.error_count(), 2); assert_eq!(set.warning_count(), 1); assert!(set.has_errors()); } #[test] fn diagnostic_display_has_no_source_text() { let d = Diagnostic::error(code::REFERENCE_MISSING, "missing target") .with_path("a.md") .with_span(Span::new(1, 3)); let text = d.to_string(); assert!(text.contains("knowledge.reference_missing")); assert!(text.contains("a.md:1..3")); } }