1use 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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
15pub struct CompatibilityProduct {
16 pub name: String,
18 pub version: String,
20}
21
22#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
24pub struct CompatibilityRustApi {
25 pub id: String,
27 pub package: String,
29 pub version: String,
31}
32
33#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35pub struct CompatibilityConformance {
36 #[serde(rename = "bundleApi")]
38 pub bundle_api: String,
39 #[serde(rename = "reportApi")]
41 pub report_api: String,
42 pub suite: String,
44 #[serde(rename = "caseCount")]
46 pub case_count: usize,
47 #[serde(rename = "contractDigest")]
49 pub contract_digest: String,
50}
51
52#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
54pub struct CompatibilityResponse {
55 #[serde(rename = "apiVersion")]
57 pub api_version: String,
58 pub product: CompatibilityProduct,
60 pub formats: Vec<String>,
62 #[serde(rename = "rustApi")]
64 pub rust_api: CompatibilityRustApi,
65 #[serde(rename = "machineApis")]
67 pub machine_apis: Vec<String>,
68 pub conformance: CompatibilityConformance,
70}
71
72impl CompatibilityResponse {
73 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
113pub struct ParseResponse {
114 #[serde(rename = "apiVersion")]
116 pub api_version: String,
117 pub frontmatter: Value,
119 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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
135pub struct CollectedNorm {
136 pub path: String,
138 pub frontmatter: Value,
140 pub body: String,
142}
143
144impl CollectedNorm {
145 #[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#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
158pub struct CollectResponse {
159 #[serde(rename = "apiVersion")]
161 pub api_version: String,
162 pub root: String,
164 pub target: String,
166 pub norms: Vec<CollectedNorm>,
168}
169
170impl CollectResponse {
171 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
185pub struct Diagnostic {
186 pub code: String,
188 pub message: String,
190 #[serde(skip_serializing_if = "Option::is_none")]
192 pub field: Option<String>,
193 #[serde(skip_serializing_if = "Option::is_none")]
195 pub suggestion: Option<String>,
196}
197
198impl Diagnostic {
199 #[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 #[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 #[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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
227#[serde(rename_all = "lowercase")]
228pub enum ValidationStatus {
229 Ok,
231 Warning,
233 Error,
235}
236
237#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
239pub struct ValidationResult {
240 pub path: String,
242 pub status: ValidationStatus,
244 pub errors: Vec<Diagnostic>,
246 pub warnings: Vec<Diagnostic>,
248}
249
250impl ValidationResult {
251 #[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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
288pub struct ValidationSummary {
289 pub files: usize,
291 pub errors: usize,
293 pub warnings: usize,
295}
296
297#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
299pub struct ValidateResponse {
300 #[serde(rename = "apiVersion")]
302 pub api_version: String,
303 pub root: String,
305 pub results: Vec<ValidationResult>,
307 pub summary: ValidationSummary,
309}
310
311impl ValidateResponse {
312 #[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#[derive(Clone, Copy, Debug, Deserialize, Eq, PartialEq, Serialize)]
332#[serde(rename_all = "lowercase")]
333pub enum InitAction {
334 Created,
336 Overwritten,
338}
339
340#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
342pub struct InitResponse {
343 #[serde(rename = "apiVersion")]
345 pub api_version: String,
346 pub profile: String,
348 pub path: String,
350 pub action: InitAction,
352}
353
354impl InitResponse {
355 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
369pub struct ErrorResponse {
370 #[serde(rename = "apiVersion")]
372 pub api_version: String,
373 pub command: String,
375 pub error: ErrorDetail,
377}
378
379impl ErrorResponse {
380 #[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#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
393pub struct ErrorDetail {
394 pub code: String,
396 pub message: String,
398 #[serde(skip_serializing_if = "Option::is_none")]
400 pub path: Option<String>,
401 #[serde(skip_serializing_if = "Option::is_none")]
403 pub field: Option<String>,
404}
405
406impl ErrorDetail {
407 #[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 #[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 #[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}