mars-schema 0.41.3

Pure schema reader and editor for Mars agent packages
Documentation
//! Stable diagnostics returned by schema operations.

use serde::{Deserialize, Serialize};

use crate::item::DefinitionKind;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Severity {
    Error,
    Warning,
    Info,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PathSegment {
    Key(String),
    Index(usize),
}

/// Byte offsets into the file text. Only fence and YAML-syntax errors may carry one
/// (`serde_yaml` has no spans; divergence V3), and no reader sets it yet. Every other
/// diagnostic is located by `path`, which consumers map to a range with their own parser.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct ByteRange {
    pub start: usize,
    pub end: usize,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SchemaDiagnostic {
    pub code: String,
    pub severity: Severity,
    pub path: Vec<PathSegment>,
    pub message: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range: Option<ByteRange>,
    /// What the package declares does not reach the installed files (a dropped restriction, a
    /// hook Mars cannot convert). Whoever owns the item, the installer's agents behave
    /// differently from what the package says.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub lost: bool,
}

impl SchemaDiagnostic {
    pub fn new(
        code: impl Into<String>,
        severity: Severity,
        path: Vec<PathSegment>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            code: code.into(),
            severity,
            path,
            message: message.into(),
            range: None,
            lost: false,
        }
    }

    /// Mark this as a loss of declared behaviour: see [`Self::lost`].
    pub fn losing(mut self) -> Self {
        self.lost = true;
        self
    }

    pub fn is_error(&self) -> bool {
        self.severity == Severity::Error
    }

    pub fn message(&self) -> &str {
        &self.message
    }
}

/// What an Agent or skill reader reports for a key it has no field for: `field.retired` when
/// Mars moved off it, else `field.unknown`. Either way the key stays in the authored file and
/// reaches no native file.
pub(crate) fn unrecognized_field(kind: DefinitionKind, key: &str) -> SchemaDiagnostic {
    let scope = match kind {
        DefinitionKind::Agent => crate::retired::Scope::Agent,
        DefinitionKind::Skill => crate::retired::Scope::Skill,
    };
    crate::retired::diagnostic(scope, key, key_path(key))
        .unwrap_or_else(|| unknown_field(key_path(key), "", key))
}

/// The page that says how to fix a key Mars no longer reads, and where the docs for a
/// `[package]` that predates schema 1 live.
pub(crate) const DOCS: &str = "https://github.com/haowjy/mars-agents/blob/main/docs/config";

/// A key a reader has no field for. Nothing is lost by ignoring it and it may be intended
/// (a typo, or a key from a newer Mars), so it is `Info`: `validate`, `check` and `--verbose`
/// show it. `table` is as in [`unknown_key_message`].
pub fn unknown_field(path: Vec<PathSegment>, table: &str, key: &str) -> SchemaDiagnostic {
    SchemaDiagnostic::new(
        "field.unknown",
        Severity::Info,
        path,
        unknown_key_message(table, key),
    )
}

/// The one warning for a key that a project, package or user config file carries and this Mars
/// does not read. `table` is the dotted table the key sits in, empty at the top of the file.
/// The key stays in the file: an older Mars cannot tell a typo from a key a newer one reads.
pub fn unknown_key_message(table: &str, key: &str) -> String {
    let table = if table.is_empty() {
        String::new()
    } else {
        format!("[{table}] ")
    };
    format!(
        "{table}unknown key `{key}` is not read by Mars v{} (a typo, or a key from a newer Mars); it stays in the file",
        crate::VERSION
    )
}

/// A bad value for a field the item kind defines (`kind` is the noun in the message).
pub(crate) fn push_invalid(
    kind: &str,
    diags: &mut Vec<SchemaDiagnostic>,
    path: Vec<PathSegment>,
    value: impl Into<String>,
    allowed: &'static str,
) {
    let value = value.into();
    let severity = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "harness-overrides")
    {
        Severity::Warning
    } else {
        Severity::Error
    };
    let display_field = if matches!(path.first(), Some(PathSegment::Key(key)) if key == "model-policies")
    {
        path.iter()
            .map(|segment| match segment {
                PathSegment::Key(key) => key.clone(),
                PathSegment::Index(index) => format!("[{}]", index),
            })
            .fold(String::new(), |mut display, segment| {
                if !display.is_empty() && !segment.starts_with('[') {
                    display.push('.');
                }
                display.push_str(&segment);
                display
            })
    } else {
        display_path(&path)
    };
    diags.push(SchemaDiagnostic::new(
        "field.value",
        severity,
        path,
        format!("{kind} field `{display_field}` has invalid value `{value}`; allowed: {allowed}"),
    ));
}

pub(crate) fn key_path(field: impl Into<String>) -> Vec<PathSegment> {
    vec![PathSegment::Key(field.into())]
}

pub(crate) fn child_path(parent: impl Into<String>, child: impl Into<String>) -> Vec<PathSegment> {
    vec![
        PathSegment::Key(parent.into()),
        PathSegment::Key(child.into()),
    ]
}

pub fn display_path(path: &[PathSegment]) -> String {
    let mut display = String::new();
    for segment in path {
        match segment {
            PathSegment::Key(key) => {
                if !display.is_empty() {
                    display.push('.');
                }
                display.push_str(key);
            }
            PathSegment::Index(index) => {
                use std::fmt::Write;
                let _ = write!(display, "[{index}]");
            }
        }
    }
    display
}

pub(crate) fn frontmatter_error(error: &crate::frontmatter::FrontmatterError) -> SchemaDiagnostic {
    let code = match error {
        crate::frontmatter::FrontmatterError::TooLarge(_) => "frontmatter.too-large",
        crate::frontmatter::FrontmatterError::TooDeep => "frontmatter.too-deep",
        crate::frontmatter::FrontmatterError::Unclosed => "frontmatter.unclosed",
        crate::frontmatter::FrontmatterError::Anchor => "yaml.anchor",
        crate::frontmatter::FrontmatterError::DocumentEnd => "yaml.document-end",
        crate::frontmatter::FrontmatterError::UnsupportedSyntax(_) => "yaml.unsupported-syntax",
        crate::frontmatter::FrontmatterError::NotAMapping => "frontmatter.not-mapping",
        crate::frontmatter::FrontmatterError::MalformedYaml(inner) => {
            let message = inner.to_string();
            if message.contains("duplicate entry") || message.contains("duplicate key") {
                "yaml.duplicate-key"
            } else {
                "yaml.invalid"
            }
        }
    };
    SchemaDiagnostic::new(code, Severity::Error, Vec::new(), error.to_string())
}

/// An Agent whose first line is not exactly `---`, read where the file is schema 1.
pub(crate) fn frontmatter_missing() -> SchemaDiagnostic {
    SchemaDiagnostic::new(
        "frontmatter.missing",
        Severity::Error,
        Vec::new(),
        "an Agent's frontmatter must open with a first line that is exactly `---`; without it every field takes its default",
    )
}