Skip to main content

norm_spec_core/
semantics.rs

1//! Cross-field semantics and explicit reference-resolution boundaries.
2
3use std::collections::BTreeSet;
4
5use serde_json::Value;
6
7use crate::{
8    Diagnostic, SchemaBundle, SchemaCompileError, ValidationDiagnostics, ValidationOptions,
9    validate_structure,
10};
11
12/// Filesystem observation for one local reference target.
13#[derive(Clone, Copy, Debug, Eq, PartialEq)]
14pub enum ReferenceStatus {
15    /// The target exists inside the project root.
16    Exists,
17    /// The target remains inside the root but does not exist.
18    Missing,
19    /// The target resolves outside the project root.
20    OutsideRoot,
21}
22
23/// Explicit reference-resolution boundary implemented by filesystem adapters.
24pub trait ReferenceResolver {
25    /// Inspect one local target relative to the current `.norm` file.
26    fn resolve(&self, target: &str) -> ReferenceStatus;
27}
28
29/// Validate schema, profile, lifecycle, SSOT, and reference semantics.
30///
31/// # Errors
32///
33/// Returns [`SchemaCompileError`] when the selected root or profile schema is
34/// invalid or cannot resolve its references from the supplied bundle.
35pub fn validate_frontmatter(
36    frontmatter: &Value,
37    schemas: &SchemaBundle,
38    options: ValidationOptions<'_>,
39    references: &dyn ReferenceResolver,
40) -> Result<ValidationDiagnostics, SchemaCompileError> {
41    let mut diagnostics = validate_structure(frontmatter, schemas, options)?;
42    validate_lifecycle(frontmatter, &mut diagnostics);
43    validate_single_sources(frontmatter, &mut diagnostics);
44    validate_references(frontmatter, references, &mut diagnostics);
45    Ok(diagnostics)
46}
47
48fn validate_lifecycle(frontmatter: &Value, diagnostics: &mut ValidationDiagnostics) {
49    let Some(lifecycle) = frontmatter
50        .get("agent_rules")
51        .and_then(|rules| rules.get("document_lifecycle"))
52    else {
53        return;
54    };
55    if lifecycle.is_array() {
56        diagnostics.warnings.push(
57            Diagnostic::new(
58                "norm/semantic/lifecycle-legacy",
59                "The document lifecycle uses the legacy string-list form.",
60            )
61            .with_field("agent_rules.document_lifecycle"),
62        );
63        return;
64    }
65    let Some(lifecycle) = lifecycle.as_object() else {
66        return;
67    };
68    let states = lifecycle
69        .get("states")
70        .and_then(Value::as_array)
71        .into_iter()
72        .flatten()
73        .filter_map(|state| state.get("id").and_then(Value::as_str))
74        .collect::<Vec<_>>();
75    let state_set = states.iter().copied().collect::<BTreeSet<_>>();
76    if states.len() != state_set.len() {
77        push_lifecycle_error(diagnostics, "Lifecycle state identifiers must be unique.");
78    }
79    if let Some(initial) = lifecycle.get("initial").and_then(Value::as_str)
80        && !state_set.contains(initial)
81    {
82        push_lifecycle_error(diagnostics, "The initial lifecycle state is not declared.");
83    }
84    let terminals = string_items(lifecycle.get("terminal")).collect::<BTreeSet<_>>();
85    for terminal in &terminals {
86        if !state_set.contains(terminal) {
87            push_lifecycle_error(diagnostics, "A terminal lifecycle state is not declared.");
88        }
89    }
90    let mut transitions = BTreeSet::new();
91    for transition in lifecycle
92        .get("transitions")
93        .and_then(Value::as_array)
94        .into_iter()
95        .flatten()
96        .filter_map(Value::as_object)
97    {
98        let source = transition.get("from").and_then(Value::as_str);
99        let target = transition.get("to").and_then(Value::as_str);
100        if source.is_some_and(|source| !state_set.contains(source)) {
101            push_lifecycle_error(
102                diagnostics,
103                "A lifecycle transition source is not declared.",
104            );
105        }
106        if target.is_some_and(|target| !state_set.contains(target)) {
107            push_lifecycle_error(
108                diagnostics,
109                "A lifecycle transition target is not declared.",
110            );
111        }
112        if let (Some(source), Some(target)) = (source, target) {
113            if !transitions.insert((source, target)) {
114                push_lifecycle_error(diagnostics, "Lifecycle transitions must be unique.");
115            }
116            if terminals.contains(source) {
117                push_lifecycle_error(
118                    diagnostics,
119                    "A terminal lifecycle state cannot have an outgoing transition.",
120                );
121            }
122        }
123    }
124}
125
126fn push_lifecycle_error(diagnostics: &mut ValidationDiagnostics, message: &str) {
127    diagnostics.errors.push(
128        Diagnostic::new("norm/semantic/lifecycle", message)
129            .with_field("agent_rules.document_lifecycle"),
130    );
131}
132
133fn validate_single_sources(frontmatter: &Value, diagnostics: &mut ValidationDiagnostics) {
134    let domains = frontmatter
135        .get("template")
136        .and_then(|template| template.get("single_source_of_truth"))
137        .and_then(Value::as_array)
138        .into_iter()
139        .flatten()
140        .filter_map(|item| item.get("for").and_then(Value::as_str));
141    let mut seen = BTreeSet::new();
142    let mut duplicates = BTreeSet::new();
143    for domain in domains {
144        if !seen.insert(domain) {
145            duplicates.insert(domain);
146        }
147    }
148    for domain in duplicates {
149        diagnostics.errors.push(
150            Diagnostic::new(
151                "norm/semantic/ssot-duplicate",
152                format!("The single-source domain is declared more than once: {domain}"),
153            )
154            .with_field("template.single_source_of_truth"),
155        );
156    }
157}
158
159fn validate_references(
160    frontmatter: &Value,
161    resolver: &dyn ReferenceResolver,
162    diagnostics: &mut ValidationDiagnostics,
163) {
164    let policy = frontmatter
165        .get("agent_rules")
166        .and_then(|rules| rules.get("reference_policy"))
167        .and_then(Value::as_object);
168    let must_exist = policy
169        .and_then(|policy| policy.get("target_must_exist"))
170        .and_then(Value::as_bool)
171        .unwrap_or(false);
172    let allow_external = policy
173        .and_then(|policy| policy.get("allow_external"))
174        .and_then(Value::as_bool)
175        .unwrap_or(false);
176    let require_description = policy
177        .and_then(|policy| policy.get("require_description"))
178        .and_then(Value::as_bool)
179        .unwrap_or(false);
180
181    for collection in ["cross_references", "strong_references"] {
182        let mut seen = BTreeSet::new();
183        for (index, reference) in frontmatter
184            .get(collection)
185            .and_then(Value::as_array)
186            .into_iter()
187            .flatten()
188            .enumerate()
189        {
190            let Some(reference) = reference.as_object() else {
191                continue;
192            };
193            let Some(target) = reference.get("target").and_then(Value::as_str) else {
194                continue;
195            };
196            let target_field = format!("{collection}[{index}].target");
197            let identity = (
198                reference.get("type").and_then(Value::as_str).unwrap_or(""),
199                target,
200            );
201            if !seen.insert(identity) {
202                diagnostics.errors.push(
203                    Diagnostic::new(
204                        "norm/reference/duplicate",
205                        format!("The typed reference target is duplicated: {target}"),
206                    )
207                    .with_field(&target_field),
208                );
209            }
210            if require_description
211                && reference
212                    .get("description")
213                    .and_then(Value::as_str)
214                    .is_none_or(str::is_empty)
215            {
216                diagnostics.errors.push(
217                    Diagnostic::new(
218                        "norm/reference/description-required",
219                        format!("The reference requires a description: {target}"),
220                    )
221                    .with_field(format!("{collection}[{index}].description")),
222                );
223            }
224            let external = target.contains("://");
225            if external && !allow_external {
226                diagnostics.errors.push(
227                    Diagnostic::new(
228                        "norm/reference/external-not-allowed",
229                        format!("External references are not allowed: {target}"),
230                    )
231                    .with_field(&target_field),
232                );
233                continue;
234            }
235            if must_exist && !external {
236                match resolver.resolve(target) {
237                    ReferenceStatus::Exists => {}
238                    ReferenceStatus::Missing => diagnostics.errors.push(
239                        Diagnostic::new(
240                            "norm/reference/not-found",
241                            format!("The reference target does not exist: {target}"),
242                        )
243                        .with_field(&target_field),
244                    ),
245                    ReferenceStatus::OutsideRoot => diagnostics.errors.push(
246                        Diagnostic::new(
247                            "norm/reference/outside-root",
248                            format!("The reference target resolves outside the root: {target}"),
249                        )
250                        .with_field(&target_field),
251                    ),
252                }
253            }
254        }
255    }
256}
257
258fn string_items(value: Option<&Value>) -> impl Iterator<Item = &str> {
259    value
260        .and_then(Value::as_array)
261        .into_iter()
262        .flatten()
263        .filter_map(Value::as_str)
264}
265
266#[cfg(test)]
267mod tests {
268    use serde_json::json;
269
270    use super::{ReferenceResolver, ReferenceStatus, validate_frontmatter};
271    use crate::{ValidationOptions, test_support::schemas};
272
273    struct Resolver {
274        status: ReferenceStatus,
275    }
276
277    impl ReferenceResolver for Resolver {
278        fn resolve(&self, _target: &str) -> ReferenceStatus {
279            self.status
280        }
281    }
282
283    fn valid() -> serde_json::Value {
284        json!({"metadata": {"layer": "example", "scope": "./", "version": "1.0"}})
285    }
286
287    #[test]
288    fn lifecycle_and_single_source_invariants_are_checked() {
289        let mut frontmatter = valid();
290        frontmatter["agent_rules"] = json!({
291            "document_lifecycle": {
292                "state_field": "state",
293                "states": [{"id": "draft"}, {"id": "draft"}],
294                "initial": "missing",
295                "terminal": ["missing"],
296                "transitions": [
297                    {"from": "draft", "to": "missing"},
298                    {"from": "draft", "to": "missing"}
299                ]
300            }
301        });
302        frontmatter["template"] = json!({
303            "single_source_of_truth": [
304                {"source": "a", "for": "architecture"},
305                {"source": "b", "for": "architecture"}
306            ]
307        });
308        let diagnostics = validate_frontmatter(
309            &frontmatter,
310            &schemas(),
311            ValidationOptions::default(),
312            &Resolver {
313                status: ReferenceStatus::Exists,
314            },
315        )
316        .unwrap_or_else(|error| panic!("schemas should compile: {error}"));
317        assert!(
318            diagnostics
319                .errors
320                .iter()
321                .any(|diagnostic| diagnostic.code == "norm/semantic/lifecycle")
322        );
323        assert!(
324            diagnostics
325                .errors
326                .iter()
327                .any(|diagnostic| diagnostic.code == "norm/semantic/ssot-duplicate")
328        );
329    }
330
331    #[test]
332    fn reference_policy_uses_explicit_resolution_observations() {
333        let mut frontmatter = valid();
334        frontmatter["agent_rules"] = json!({
335            "reference_policy": {
336                "target_must_exist": true,
337                "allow_external": false,
338                "require_description": true
339            }
340        });
341        frontmatter["strong_references"] = json!([
342            {"type": "source", "target": "missing.md", "sync": "manual", "validation": "strict"},
343            {"type": "source", "target": "missing.md", "sync": "manual", "validation": "strict"},
344            {"type": "source", "target": "https://example.invalid", "sync": "manual", "validation": "strict", "description": "external"}
345        ]);
346        let diagnostics = validate_frontmatter(
347            &frontmatter,
348            &schemas(),
349            ValidationOptions::default(),
350            &Resolver {
351                status: ReferenceStatus::Missing,
352            },
353        )
354        .unwrap_or_else(|error| panic!("schemas should compile: {error}"));
355        for code in [
356            "norm/reference/not-found",
357            "norm/reference/duplicate",
358            "norm/reference/description-required",
359            "norm/reference/external-not-allowed",
360        ] {
361            assert!(
362                diagnostics
363                    .errors
364                    .iter()
365                    .any(|diagnostic| diagnostic.code == code),
366                "missing reference diagnostic {code}"
367            );
368        }
369    }
370}