Skip to main content

norm_spec_core/
protocol.rs

1//! Versioned machine response models.
2
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5
6use crate::{
7    A1_CLI_CASE_COUNT, A1_CLI_SUITE_ID, COLLECT_API_VERSION, COMPATIBILITY_API_VERSION,
8    CONFORMANCE_API_VERSION, CONTRACT_BUNDLE_API_VERSION, ERROR_API_VERSION, FORMAT_ID,
9    INIT_API_VERSION, PARSE_API_VERSION, ParsedNorm, RUST_API_VERSION, SCAN_API_VERSION,
10    VALIDATE_API_VERSION, crate_version,
11};
12
13/// Exact product identity reported by compatibility discovery.
14#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
15pub struct CompatibilityProduct {
16    /// Stable product name.
17    pub name: String,
18    /// Exact compiled product version.
19    pub version: String,
20}
21
22/// Public Rust consumer-surface identity.
23#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
24pub struct CompatibilityRustApi {
25    /// Versioned Rust API identifier.
26    pub id: String,
27    /// Cargo package that provides the surface.
28    pub package: String,
29    /// Exact compiled package version.
30    pub version: String,
31}
32
33/// Frozen conformance surface reported by a candidate.
34#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35pub struct CompatibilityConformance {
36    /// Versioned contract-bundle format.
37    #[serde(rename = "bundleApi")]
38    pub bundle_api: String,
39    /// Versioned conformance-report protocol.
40    #[serde(rename = "reportApi")]
41    pub report_api: String,
42    /// Frozen suite identifier.
43    pub suite: String,
44    /// Number of executable cases in the suite.
45    #[serde(rename = "caseCount")]
46    pub case_count: usize,
47    /// SHA-256 identity of the exact contract bundle.
48    #[serde(rename = "contractDigest")]
49    pub contract_digest: String,
50}
51
52/// Machine-readable compatibility discovery response.
53#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
54pub struct CompatibilityResponse {
55    /// Version of the compatibility response protocol.
56    #[serde(rename = "apiVersion")]
57    pub api_version: String,
58    /// Exact product identity.
59    pub product: CompatibilityProduct,
60    /// Accepted format identifiers in lexical order.
61    pub formats: Vec<String>,
62    /// Public high-level Rust API identity.
63    #[serde(rename = "rustApi")]
64    pub rust_api: CompatibilityRustApi,
65    /// Supported machine API identifiers in lexical order.
66    #[serde(rename = "machineApis")]
67    pub machine_apis: Vec<String>,
68    /// Frozen conformance surface.
69    pub conformance: CompatibilityConformance,
70}
71
72impl CompatibilityResponse {
73    /// Construct discovery for the compiled product and an exact contract digest.
74    #[must_use]
75    pub fn current(contract_digest: impl Into<String>) -> Self {
76        Self {
77            api_version: COMPATIBILITY_API_VERSION.to_owned(),
78            product: CompatibilityProduct {
79                name: "norm-spec".to_owned(),
80                version: crate_version().to_owned(),
81            },
82            formats: vec![FORMAT_ID.to_owned()],
83            rust_api: CompatibilityRustApi {
84                id: RUST_API_VERSION.to_owned(),
85                package: "norm-spec".to_owned(),
86                version: crate_version().to_owned(),
87            },
88            machine_apis: [
89                COLLECT_API_VERSION,
90                COMPATIBILITY_API_VERSION,
91                ERROR_API_VERSION,
92                INIT_API_VERSION,
93                PARSE_API_VERSION,
94                SCAN_API_VERSION,
95                VALIDATE_API_VERSION,
96            ]
97            .into_iter()
98            .map(str::to_owned)
99            .collect(),
100            conformance: CompatibilityConformance {
101                bundle_api: CONTRACT_BUNDLE_API_VERSION.to_owned(),
102                report_api: CONFORMANCE_API_VERSION.to_owned(),
103                suite: A1_CLI_SUITE_ID.to_owned(),
104                case_count: A1_CLI_CASE_COUNT,
105                contract_digest: contract_digest.into(),
106            },
107        }
108    }
109}
110
111/// Successful `parse` machine response.
112#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
113pub struct ParseResponse {
114    /// Version of the parse response protocol.
115    #[serde(rename = "apiVersion")]
116    pub api_version: String,
117    /// Parsed YAML frontmatter.
118    pub frontmatter: Value,
119    /// Trimmed Markdown body.
120    pub body: String,
121}
122
123impl From<ParsedNorm> for ParseResponse {
124    fn from(parsed: ParsedNorm) -> Self {
125        Self {
126            api_version: PARSE_API_VERSION.to_owned(),
127            frontmatter: parsed.frontmatter,
128            body: parsed.body,
129        }
130    }
131}
132
133/// One parsed convention file in a `collect` response.
134#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
135pub struct CollectedNorm {
136    /// Convention-file path relative to the collection root.
137    pub path: String,
138    /// Parsed YAML frontmatter.
139    pub frontmatter: Value,
140    /// Trimmed Markdown body.
141    pub body: String,
142}
143
144impl CollectedNorm {
145    /// Construct a collected convention from its portable path and parsed data.
146    #[must_use]
147    pub fn new(path: impl Into<String>, parsed: ParsedNorm) -> Self {
148        Self {
149            path: path.into(),
150            frontmatter: parsed.frontmatter,
151            body: parsed.body,
152        }
153    }
154}
155
156/// Successful `collect` machine response.
157#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
158pub struct CollectResponse {
159    /// Version of the collect response protocol.
160    #[serde(rename = "apiVersion")]
161    pub api_version: String,
162    /// Root marker for all paths in the response.
163    pub root: String,
164    /// Requested target path relative to the root.
165    pub target: String,
166    /// Parsed conventions ordered from most-specific to least-specific.
167    pub norms: Vec<CollectedNorm>,
168}
169
170impl CollectResponse {
171    /// Construct a versioned collection response.
172    #[must_use]
173    pub fn new(target: impl Into<String>, norms: Vec<CollectedNorm>) -> Self {
174        Self {
175            api_version: COLLECT_API_VERSION.to_owned(),
176            root: ".".to_owned(),
177            target: target.into(),
178            norms,
179        }
180    }
181}
182
183/// Stable diagnostic emitted by schema, profile, or semantic validation.
184#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
185pub struct Diagnostic {
186    /// Stable machine-readable diagnostic code.
187    pub code: String,
188    /// Human-readable detail; not intended for machine matching.
189    pub message: String,
190    /// Dot-and-index path to the affected frontmatter field, when available.
191    #[serde(skip_serializing_if = "Option::is_none")]
192    pub field: Option<String>,
193    /// Machine-actionable correction hint, when available.
194    #[serde(skip_serializing_if = "Option::is_none")]
195    pub suggestion: Option<String>,
196}
197
198impl Diagnostic {
199    /// Construct a diagnostic with no field or suggestion.
200    #[must_use]
201    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
202        Self {
203            code: code.into(),
204            message: message.into(),
205            field: None,
206            suggestion: None,
207        }
208    }
209
210    /// Attach an affected field path.
211    #[must_use]
212    pub fn with_field(mut self, field: impl Into<String>) -> Self {
213        self.field = Some(field.into());
214        self
215    }
216
217    /// Attach a machine-actionable correction hint.
218    #[must_use]
219    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
220        self.suggestion = Some(suggestion.into());
221        self
222    }
223}
224
225/// Overall classification of one validated `.norm` file.
226#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
227#[serde(rename_all = "lowercase")]
228pub enum ValidationStatus {
229    /// No errors or warnings were emitted.
230    Ok,
231    /// Warnings were emitted without errors.
232    Warning,
233    /// At least one error was emitted.
234    Error,
235}
236
237/// Validation outcome for one root-relative `.norm` path.
238#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
239pub struct ValidationResult {
240    /// Root-relative convention-file path.
241    pub path: String,
242    /// Highest diagnostic severity for this file.
243    pub status: ValidationStatus,
244    /// Deterministically ordered hard validation failures.
245    pub errors: Vec<Diagnostic>,
246    /// Deterministically ordered non-fatal validation findings.
247    pub warnings: Vec<Diagnostic>,
248}
249
250impl ValidationResult {
251    /// Construct and deterministically order a per-file validation result.
252    #[must_use]
253    pub fn new(
254        path: impl Into<String>,
255        mut errors: Vec<Diagnostic>,
256        mut warnings: Vec<Diagnostic>,
257    ) -> Self {
258        errors.sort_by(diagnostic_order);
259        warnings.sort_by(diagnostic_order);
260        let status = if errors.is_empty() {
261            if warnings.is_empty() {
262                ValidationStatus::Ok
263            } else {
264                ValidationStatus::Warning
265            }
266        } else {
267            ValidationStatus::Error
268        };
269        Self {
270            path: path.into(),
271            status,
272            errors,
273            warnings,
274        }
275    }
276}
277
278fn diagnostic_order(left: &Diagnostic, right: &Diagnostic) -> std::cmp::Ordering {
279    left.field
280        .cmp(&right.field)
281        .then_with(|| left.code.cmp(&right.code))
282        .then_with(|| left.suggestion.cmp(&right.suggestion))
283        .then_with(|| left.message.cmp(&right.message))
284}
285
286/// Aggregate counts for a validation response.
287#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
288pub struct ValidationSummary {
289    /// Number of convention files evaluated.
290    pub files: usize,
291    /// Total number of hard validation diagnostics.
292    pub errors: usize,
293    /// Total number of warning diagnostics.
294    pub warnings: usize,
295}
296
297/// Versioned machine response for a completed `validate` evaluation.
298#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
299pub struct ValidateResponse {
300    /// Version of the validation response protocol.
301    #[serde(rename = "apiVersion")]
302    pub api_version: String,
303    /// Root marker for all paths in the response.
304    pub root: String,
305    /// Deterministically ordered per-file results.
306    pub results: Vec<ValidationResult>,
307    /// Aggregate file and diagnostic counts.
308    pub summary: ValidationSummary,
309}
310
311impl ValidateResponse {
312    /// Construct a validation response ordered by portable path.
313    #[must_use]
314    pub fn new(mut results: Vec<ValidationResult>) -> Self {
315        results.sort_by(|left, right| left.path.cmp(&right.path));
316        let summary = ValidationSummary {
317            files: results.len(),
318            errors: results.iter().map(|result| result.errors.len()).sum(),
319            warnings: results.iter().map(|result| result.warnings.len()).sum(),
320        };
321        Self {
322            api_version: VALIDATE_API_VERSION.to_owned(),
323            root: ".".to_owned(),
324            results,
325            summary,
326        }
327    }
328}
329
330/// Filesystem action completed by `norm init`.
331#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
332#[serde(rename_all = "lowercase")]
333pub enum InitAction {
334    /// A new convention file was created.
335    Created,
336    /// An existing convention file was replaced under explicit force.
337    Overwritten,
338}
339
340/// Versioned machine response for a completed `init` operation.
341#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
342pub struct InitResponse {
343    /// Version of the init response protocol.
344    #[serde(rename = "apiVersion")]
345    pub api_version: String,
346    /// Name of the embedded profile template that was written.
347    pub profile: String,
348    /// Output path relative to the current working directory when contained.
349    pub path: String,
350    /// Whether the output was created or explicitly overwritten.
351    pub action: InitAction,
352}
353
354impl InitResponse {
355    /// Construct a versioned init response.
356    #[must_use]
357    pub fn new(profile: impl Into<String>, path: impl Into<String>, action: InitAction) -> Self {
358        Self {
359            api_version: INIT_API_VERSION.to_owned(),
360            profile: profile.into(),
361            path: path.into(),
362            action,
363        }
364    }
365}
366
367/// Versioned machine response for a handled command failure.
368#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
369pub struct ErrorResponse {
370    /// Version of the common error protocol.
371    #[serde(rename = "apiVersion")]
372    pub api_version: String,
373    /// Command that handled the failure.
374    pub command: String,
375    /// Stable error detail.
376    pub error: ErrorDetail,
377}
378
379impl ErrorResponse {
380    /// Construct a handled error response for a command.
381    #[must_use]
382    pub fn new(command: impl Into<String>, error: ErrorDetail) -> Self {
383        Self {
384            api_version: ERROR_API_VERSION.to_owned(),
385            command: command.into(),
386            error,
387        }
388    }
389}
390
391/// Stable machine-readable error detail.
392#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
393pub struct ErrorDetail {
394    /// Stable error code.
395    pub code: String,
396    /// Human-readable diagnostic; not intended for machine matching.
397    pub message: String,
398    /// Portable path associated with the error, when applicable.
399    #[serde(skip_serializing_if = "Option::is_none")]
400    pub path: Option<String>,
401    /// CLI field associated with the error, when applicable.
402    #[serde(skip_serializing_if = "Option::is_none")]
403    pub field: Option<String>,
404}
405
406impl ErrorDetail {
407    /// Construct an error with no path or field context.
408    #[must_use]
409    pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
410        Self {
411            code: code.into(),
412            message: message.into(),
413            path: None,
414            field: None,
415        }
416    }
417
418    /// Attach a portable path to the error.
419    #[must_use]
420    pub fn with_path(mut self, path: impl Into<String>) -> Self {
421        self.path = Some(path.into());
422        self
423    }
424
425    /// Attach a CLI field name to the error.
426    #[must_use]
427    pub fn with_field(mut self, field: impl Into<String>) -> Self {
428        self.field = Some(field.into());
429        self
430    }
431}
432
433#[cfg(test)]
434mod tests {
435    use serde::Serialize;
436    use serde_json::json;
437
438    use super::{
439        CollectResponse, CollectedNorm, CompatibilityResponse, Diagnostic, ErrorDetail,
440        ErrorResponse, InitAction, InitResponse, ParseResponse, ValidateResponse, ValidationResult,
441        ValidationStatus,
442    };
443    use crate::ParsedNorm;
444
445    fn json_value(value: impl Serialize) -> serde_json::Value {
446        match serde_json::to_value(value) {
447            Ok(value) => value,
448            Err(error) => panic!("failed to serialize test response: {error}"),
449        }
450    }
451
452    #[test]
453    fn compatibility_response_exposes_exact_sorted_identifiers() {
454        let response = CompatibilityResponse::current("sha256:example");
455        assert_eq!(
456            json_value(response),
457            json!({
458                "apiVersion": "norm-spec/compatibility/v1",
459                "product": {
460                    "name": "norm-spec",
461                    "version": env!("CARGO_PKG_VERSION")
462                },
463                "formats": ["norm-spec/a1"],
464                "rustApi": {
465                    "id": "norm-spec/rust-api/v1",
466                    "package": "norm-spec",
467                    "version": env!("CARGO_PKG_VERSION")
468                },
469                "machineApis": [
470                    "norm-spec/collect/v1",
471                    "norm-spec/compatibility/v1",
472                    "norm-spec/error/v1",
473                    "norm-spec/init/v1",
474                    "norm-spec/parse/v1",
475                    "norm-spec/scan/v1",
476                    "norm-spec/validate/v1"
477                ],
478                "conformance": {
479                    "bundleApi": "norm-spec/contract-bundle/v1",
480                    "reportApi": "norm-spec/conformance/v1",
481                    "suite": "norm-spec/a1-cli/v1",
482                    "caseCount": 82,
483                    "contractDigest": "sha256:example"
484                }
485            })
486        );
487    }
488
489    #[test]
490    fn parse_response_uses_versioned_camel_case_envelope() {
491        let response = ParseResponse::from(ParsedNorm {
492            frontmatter: json!({"metadata": {}}),
493            body: String::new(),
494        });
495        assert_eq!(
496            json_value(response),
497            json!({
498                "apiVersion": "norm-spec/parse/v1",
499                "frontmatter": {"metadata": {}},
500                "body": ""
501            })
502        );
503    }
504
505    #[test]
506    fn error_response_omits_absent_optional_context() {
507        let response = ErrorResponse::new(
508            "parse",
509            ErrorDetail::new("norm/parse/empty", "empty").with_path(".norm"),
510        );
511        assert_eq!(
512            json_value(response),
513            json!({
514                "apiVersion": "norm-spec/error/v1",
515                "command": "parse",
516                "error": {
517                    "code": "norm/parse/empty",
518                    "message": "empty",
519                    "path": ".norm"
520                }
521            })
522        );
523    }
524
525    #[test]
526    fn collect_response_preserves_specificity_order() {
527        let response = CollectResponse::new(
528            "docs/module",
529            vec![
530                CollectedNorm::new(
531                    "docs/module/.norm",
532                    ParsedNorm {
533                        frontmatter: json!({"metadata": {"layer": "module"}}),
534                        body: "# Module".to_owned(),
535                    },
536                ),
537                CollectedNorm::new(
538                    ".norm",
539                    ParsedNorm {
540                        frontmatter: json!({"metadata": {"layer": "root"}}),
541                        body: "# Root".to_owned(),
542                    },
543                ),
544            ],
545        );
546        assert_eq!(
547            json_value(response),
548            json!({
549                "apiVersion": "norm-spec/collect/v1",
550                "root": ".",
551                "target": "docs/module",
552                "norms": [
553                    {
554                        "path": "docs/module/.norm",
555                        "frontmatter": {"metadata": {"layer": "module"}},
556                        "body": "# Module"
557                    },
558                    {
559                        "path": ".norm",
560                        "frontmatter": {"metadata": {"layer": "root"}},
561                        "body": "# Root"
562                    }
563                ]
564            })
565        );
566    }
567
568    #[test]
569    fn validate_response_orders_paths_diagnostics_and_counts_findings() {
570        let response = ValidateResponse::new(vec![
571            ValidationResult::new(
572                "docs/.norm",
573                Vec::new(),
574                vec![
575                    Diagnostic::new("norm/profile/z", "z").with_field("template"),
576                    Diagnostic::new("norm/profile/a", "a").with_field("agent_rules"),
577                ],
578            ),
579            ValidationResult::new(
580                ".norm",
581                vec![Diagnostic::new(
582                    "norm/schema/version-format",
583                    "invalid version",
584                )],
585                Vec::new(),
586            ),
587        ]);
588        assert_eq!(response.results[0].path, ".norm");
589        assert_eq!(response.results[0].status, ValidationStatus::Error);
590        assert_eq!(response.results[1].status, ValidationStatus::Warning);
591        assert_eq!(
592            response.results[1].warnings[0].field.as_deref(),
593            Some("agent_rules")
594        );
595        assert_eq!(response.summary.files, 2);
596        assert_eq!(response.summary.errors, 1);
597        assert_eq!(response.summary.warnings, 2);
598        assert_eq!(json_value(response)["apiVersion"], "norm-spec/validate/v1");
599    }
600
601    #[test]
602    fn init_response_uses_the_versioned_action_contract() {
603        assert_eq!(
604            json_value(InitResponse::new(
605                "module",
606                ".norm",
607                InitAction::Overwritten,
608            )),
609            json!({
610                "apiVersion": "norm-spec/init/v1",
611                "profile": "module",
612                "path": ".norm",
613                "action": "overwritten"
614            })
615        );
616    }
617}