use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
A1_CLI_CASE_COUNT, A1_CLI_SUITE_ID, COLLECT_API_VERSION, COMPATIBILITY_API_VERSION,
CONFORMANCE_API_VERSION, CONTRACT_BUNDLE_API_VERSION, ERROR_API_VERSION, FORMAT_ID,
INIT_API_VERSION, PARSE_API_VERSION, ParsedNorm, RUST_API_VERSION, SCAN_API_VERSION,
VALIDATE_API_VERSION, crate_version,
};
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CompatibilityProduct {
pub name: String,
pub version: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CompatibilityRustApi {
pub id: String,
pub package: String,
pub version: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CompatibilityConformance {
#[serde(rename = "bundleApi")]
pub bundle_api: String,
#[serde(rename = "reportApi")]
pub report_api: String,
pub suite: String,
#[serde(rename = "caseCount")]
pub case_count: usize,
#[serde(rename = "contractDigest")]
pub contract_digest: String,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct CompatibilityResponse {
#[serde(rename = "apiVersion")]
pub api_version: String,
pub product: CompatibilityProduct,
pub formats: Vec<String>,
#[serde(rename = "rustApi")]
pub rust_api: CompatibilityRustApi,
#[serde(rename = "machineApis")]
pub machine_apis: Vec<String>,
pub conformance: CompatibilityConformance,
}
impl CompatibilityResponse {
#[must_use]
pub fn current(contract_digest: impl Into<String>) -> Self {
Self {
api_version: COMPATIBILITY_API_VERSION.to_owned(),
product: CompatibilityProduct {
name: "norm-spec".to_owned(),
version: crate_version().to_owned(),
},
formats: vec![FORMAT_ID.to_owned()],
rust_api: CompatibilityRustApi {
id: RUST_API_VERSION.to_owned(),
package: "norm-spec".to_owned(),
version: crate_version().to_owned(),
},
machine_apis: [
COLLECT_API_VERSION,
COMPATIBILITY_API_VERSION,
ERROR_API_VERSION,
INIT_API_VERSION,
PARSE_API_VERSION,
SCAN_API_VERSION,
VALIDATE_API_VERSION,
]
.into_iter()
.map(str::to_owned)
.collect(),
conformance: CompatibilityConformance {
bundle_api: CONTRACT_BUNDLE_API_VERSION.to_owned(),
report_api: CONFORMANCE_API_VERSION.to_owned(),
suite: A1_CLI_SUITE_ID.to_owned(),
case_count: A1_CLI_CASE_COUNT,
contract_digest: contract_digest.into(),
},
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct ParseResponse {
#[serde(rename = "apiVersion")]
pub api_version: String,
pub frontmatter: Value,
pub body: String,
}
impl From<ParsedNorm> for ParseResponse {
fn from(parsed: ParsedNorm) -> Self {
Self {
api_version: PARSE_API_VERSION.to_owned(),
frontmatter: parsed.frontmatter,
body: parsed.body,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CollectedNorm {
pub path: String,
pub frontmatter: Value,
pub body: String,
}
impl CollectedNorm {
#[must_use]
pub fn new(path: impl Into<String>, parsed: ParsedNorm) -> Self {
Self {
path: path.into(),
frontmatter: parsed.frontmatter,
body: parsed.body,
}
}
}
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
pub struct CollectResponse {
#[serde(rename = "apiVersion")]
pub api_version: String,
pub root: String,
pub target: String,
pub norms: Vec<CollectedNorm>,
}
impl CollectResponse {
#[must_use]
pub fn new(target: impl Into<String>, norms: Vec<CollectedNorm>) -> Self {
Self {
api_version: COLLECT_API_VERSION.to_owned(),
root: ".".to_owned(),
target: target.into(),
norms,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct Diagnostic {
pub code: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub suggestion: Option<String>,
}
impl Diagnostic {
#[must_use]
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
field: None,
suggestion: None,
}
}
#[must_use]
pub fn with_field(mut self, field: impl Into<String>) -> Self {
self.field = Some(field.into());
self
}
#[must_use]
pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
self.suggestion = Some(suggestion.into());
self
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum ValidationStatus {
Ok,
Warning,
Error,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ValidationResult {
pub path: String,
pub status: ValidationStatus,
pub errors: Vec<Diagnostic>,
pub warnings: Vec<Diagnostic>,
}
impl ValidationResult {
#[must_use]
pub fn new(
path: impl Into<String>,
mut errors: Vec<Diagnostic>,
mut warnings: Vec<Diagnostic>,
) -> Self {
errors.sort_by(diagnostic_order);
warnings.sort_by(diagnostic_order);
let status = if errors.is_empty() {
if warnings.is_empty() {
ValidationStatus::Ok
} else {
ValidationStatus::Warning
}
} else {
ValidationStatus::Error
};
Self {
path: path.into(),
status,
errors,
warnings,
}
}
}
fn diagnostic_order(left: &Diagnostic, right: &Diagnostic) -> std::cmp::Ordering {
left.field
.cmp(&right.field)
.then_with(|| left.code.cmp(&right.code))
.then_with(|| left.suggestion.cmp(&right.suggestion))
.then_with(|| left.message.cmp(&right.message))
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ValidationSummary {
pub files: usize,
pub errors: usize,
pub warnings: usize,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ValidateResponse {
#[serde(rename = "apiVersion")]
pub api_version: String,
pub root: String,
pub results: Vec<ValidationResult>,
pub summary: ValidationSummary,
}
impl ValidateResponse {
#[must_use]
pub fn new(mut results: Vec<ValidationResult>) -> Self {
results.sort_by(|left, right| left.path.cmp(&right.path));
let summary = ValidationSummary {
files: results.len(),
errors: results.iter().map(|result| result.errors.len()).sum(),
warnings: results.iter().map(|result| result.warnings.len()).sum(),
};
Self {
api_version: VALIDATE_API_VERSION.to_owned(),
root: ".".to_owned(),
results,
summary,
}
}
}
#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum InitAction {
Created,
Overwritten,
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct InitResponse {
#[serde(rename = "apiVersion")]
pub api_version: String,
pub profile: String,
pub path: String,
pub action: InitAction,
}
impl InitResponse {
#[must_use]
pub fn new(profile: impl Into<String>, path: impl Into<String>, action: InitAction) -> Self {
Self {
api_version: INIT_API_VERSION.to_owned(),
profile: profile.into(),
path: path.into(),
action,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ErrorResponse {
#[serde(rename = "apiVersion")]
pub api_version: String,
pub command: String,
pub error: ErrorDetail,
}
impl ErrorResponse {
#[must_use]
pub fn new(command: impl Into<String>, error: ErrorDetail) -> Self {
Self {
api_version: ERROR_API_VERSION.to_owned(),
command: command.into(),
error,
}
}
}
#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
pub struct ErrorDetail {
pub code: String,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub field: Option<String>,
}
impl ErrorDetail {
#[must_use]
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
path: None,
field: None,
}
}
#[must_use]
pub fn with_path(mut self, path: impl Into<String>) -> Self {
self.path = Some(path.into());
self
}
#[must_use]
pub fn with_field(mut self, field: impl Into<String>) -> Self {
self.field = Some(field.into());
self
}
}
#[cfg(test)]
mod tests {
use serde::Serialize;
use serde_json::json;
use super::{
CollectResponse, CollectedNorm, CompatibilityResponse, Diagnostic, ErrorDetail,
ErrorResponse, InitAction, InitResponse, ParseResponse, ValidateResponse, ValidationResult,
ValidationStatus,
};
use crate::ParsedNorm;
fn json_value(value: impl Serialize) -> serde_json::Value {
match serde_json::to_value(value) {
Ok(value) => value,
Err(error) => panic!("failed to serialize test response: {error}"),
}
}
#[test]
fn compatibility_response_exposes_exact_sorted_identifiers() {
let response = CompatibilityResponse::current("sha256:example");
assert_eq!(
json_value(response),
json!({
"apiVersion": "norm-spec/compatibility/v1",
"product": {
"name": "norm-spec",
"version": env!("CARGO_PKG_VERSION")
},
"formats": ["norm-spec/a1"],
"rustApi": {
"id": "norm-spec/rust-api/v1",
"package": "norm-spec",
"version": env!("CARGO_PKG_VERSION")
},
"machineApis": [
"norm-spec/collect/v1",
"norm-spec/compatibility/v1",
"norm-spec/error/v1",
"norm-spec/init/v1",
"norm-spec/parse/v1",
"norm-spec/scan/v1",
"norm-spec/validate/v1"
],
"conformance": {
"bundleApi": "norm-spec/contract-bundle/v1",
"reportApi": "norm-spec/conformance/v1",
"suite": "norm-spec/a1-cli/v1",
"caseCount": 82,
"contractDigest": "sha256:example"
}
})
);
}
#[test]
fn parse_response_uses_versioned_camel_case_envelope() {
let response = ParseResponse::from(ParsedNorm {
frontmatter: json!({"metadata": {}}),
body: String::new(),
});
assert_eq!(
json_value(response),
json!({
"apiVersion": "norm-spec/parse/v1",
"frontmatter": {"metadata": {}},
"body": ""
})
);
}
#[test]
fn error_response_omits_absent_optional_context() {
let response = ErrorResponse::new(
"parse",
ErrorDetail::new("norm/parse/empty", "empty").with_path(".norm"),
);
assert_eq!(
json_value(response),
json!({
"apiVersion": "norm-spec/error/v1",
"command": "parse",
"error": {
"code": "norm/parse/empty",
"message": "empty",
"path": ".norm"
}
})
);
}
#[test]
fn collect_response_preserves_specificity_order() {
let response = CollectResponse::new(
"docs/module",
vec![
CollectedNorm::new(
"docs/module/.norm",
ParsedNorm {
frontmatter: json!({"metadata": {"layer": "module"}}),
body: "# Module".to_owned(),
},
),
CollectedNorm::new(
".norm",
ParsedNorm {
frontmatter: json!({"metadata": {"layer": "root"}}),
body: "# Root".to_owned(),
},
),
],
);
assert_eq!(
json_value(response),
json!({
"apiVersion": "norm-spec/collect/v1",
"root": ".",
"target": "docs/module",
"norms": [
{
"path": "docs/module/.norm",
"frontmatter": {"metadata": {"layer": "module"}},
"body": "# Module"
},
{
"path": ".norm",
"frontmatter": {"metadata": {"layer": "root"}},
"body": "# Root"
}
]
})
);
}
#[test]
fn validate_response_orders_paths_diagnostics_and_counts_findings() {
let response = ValidateResponse::new(vec![
ValidationResult::new(
"docs/.norm",
Vec::new(),
vec![
Diagnostic::new("norm/profile/z", "z").with_field("template"),
Diagnostic::new("norm/profile/a", "a").with_field("agent_rules"),
],
),
ValidationResult::new(
".norm",
vec![Diagnostic::new(
"norm/schema/version-format",
"invalid version",
)],
Vec::new(),
),
]);
assert_eq!(response.results[0].path, ".norm");
assert_eq!(response.results[0].status, ValidationStatus::Error);
assert_eq!(response.results[1].status, ValidationStatus::Warning);
assert_eq!(
response.results[1].warnings[0].field.as_deref(),
Some("agent_rules")
);
assert_eq!(response.summary.files, 2);
assert_eq!(response.summary.errors, 1);
assert_eq!(response.summary.warnings, 2);
assert_eq!(json_value(response)["apiVersion"], "norm-spec/validate/v1");
}
#[test]
fn init_response_uses_the_versioned_action_contract() {
assert_eq!(
json_value(InitResponse::new(
"module",
".norm",
InitAction::Overwritten,
)),
json!({
"apiVersion": "norm-spec/init/v1",
"profile": "module",
"path": ".norm",
"action": "overwritten"
})
);
}
}