sara-core 0.5.2

Core library for Sara - Requirements Knowledge Graph CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
//! Main validation orchestrator.

use std::collections::HashMap;

use crate::config::ValidationConfig;
use crate::graph::KnowledgeGraph;
use crate::model::Item;
use crate::validation::report::{ValidationReport, ValidationReportBuilder};
use crate::validation::rule::{Severity, ValidationRule};
use crate::validation::rules::{
    BrokenReferencesRule, CyclesRule, DuplicatesRule, MetadataRule, OrphansRule,
    RedundantRelationshipsRule, RelationshipsRule,
};

/// All validation rules.
static RULES: &[&dyn ValidationRule] = &[
    &BrokenReferencesRule,
    &DuplicatesRule,
    &CyclesRule,
    &RelationshipsRule,
    &MetadataRule,
    &RedundantRelationshipsRule,
    &OrphansRule,
];

/// Orchestrates all validation rules.
pub struct Validator {
    /// Configuration for validation behavior.
    config: ValidationConfig,
}

impl Validator {
    /// Creates a new validator with the given configuration.
    pub fn new(config: ValidationConfig) -> Self {
        Self { config }
    }

    /// Creates a validator with default configuration.
    pub fn with_defaults() -> Self {
        Self::new(ValidationConfig::default())
    }

    /// Pre-validates a list of items before adding them to the graph.
    ///
    /// This enables fail-fast validation during parsing/loading. Only rules
    /// that can validate items independently (without graph context) will
    /// produce errors here.
    pub fn pre_validate(&self, items: &[Item]) -> ValidationReport {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        for rule in RULES {
            let issues = rule.pre_validate(items, &self.config);
            let severity = if self.config.strict_mode {
                Severity::Error
            } else {
                rule.severity()
            };
            match severity {
                Severity::Error => errors.extend(issues),
                Severity::Warning => warnings.extend(issues),
            }
        }

        let mut items_by_type = HashMap::new();
        for item in items {
            *items_by_type.entry(item.item_type).or_insert(0) += 1;
        }

        ValidationReportBuilder::new()
            .items_checked(items.len())
            .items_by_type(items_by_type)
            .errors(errors)
            .warnings(warnings)
            .build()
    }

    /// Validates the knowledge graph and returns a report.
    pub fn validate(&self, graph: &KnowledgeGraph) -> ValidationReport {
        let mut errors = Vec::new();
        let mut warnings = Vec::new();

        // Run all rules and categorize by severity
        // In strict mode, all issues become errors
        for rule in RULES {
            let issues = rule.validate(graph, &self.config);
            let severity = if self.config.strict_mode {
                Severity::Error
            } else {
                rule.severity()
            };
            match severity {
                Severity::Error => errors.extend(issues),
                Severity::Warning => warnings.extend(issues),
            }
        }

        ValidationReportBuilder::new()
            .items_checked(graph.item_count())
            .relationships_checked(graph.relationship_count())
            .items_by_type(graph.count_by_type())
            .errors(errors)
            .warnings(warnings)
            .build()
    }
}

impl Default for Validator {
    fn default() -> Self {
        Self::with_defaults()
    }
}

/// Convenience function to validate a graph.
///
/// When `strict` is true, all issues (including orphans) are treated as errors.
pub fn validate(graph: &KnowledgeGraph, strict: bool) -> ValidationReport {
    let config = ValidationConfig {
        strict_mode: strict,
        ..Default::default()
    };
    Validator::new(config).validate(graph)
}

/// Convenience function to pre-validate items before adding them to the graph.
///
/// When `strict` is true, all issues are treated as errors.
/// If the report contains errors, the items should not be added to the graph.
pub fn pre_validate(items: &[Item], strict: bool) -> ValidationReport {
    let config = ValidationConfig {
        strict_mode: strict,
        ..Default::default()
    };
    Validator::new(config).pre_validate(items)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::ValidationError;
    use crate::graph::KnowledgeGraphBuilder;
    use crate::model::{
        ItemAttributes, ItemBuilder, ItemId, ItemType, SourceLocation, UpstreamRefs,
    };
    use crate::test_utils::{create_test_item, create_test_item_with_upstream};
    use std::path::PathBuf;

    #[test]
    fn test_valid_graph() {
        let graph = KnowledgeGraphBuilder::new()
            .add_item(create_test_item("SOL-001", ItemType::Solution))
            .add_item(create_test_item_with_upstream(
                "UC-001",
                ItemType::UseCase,
                UpstreamRefs {
                    refines: vec![ItemId::new_unchecked("SOL-001")],
                    ..Default::default()
                },
            ))
            .build()
            .unwrap();

        let report = validate(&graph, false);
        assert!(report.is_valid(), "Valid graph should pass validation");
        assert_eq!(report.error_count(), 0);
    }

    #[test]
    fn test_broken_reference() {
        let graph = KnowledgeGraphBuilder::new()
            .add_item(create_test_item_with_upstream(
                "UC-001",
                ItemType::UseCase,
                UpstreamRefs {
                    refines: vec![ItemId::new_unchecked("SOL-MISSING")],
                    ..Default::default()
                },
            ))
            .build()
            .unwrap();

        let report = validate(&graph, false);
        assert!(!report.is_valid());
        assert!(report.error_count() > 0);
    }

    #[test]
    fn test_orphan_warning() {
        let graph = KnowledgeGraphBuilder::new()
            .add_item(create_test_item("UC-001", ItemType::UseCase))
            .build()
            .unwrap();

        // Non-strict mode: orphan is a warning
        let report = validate(&graph, false);
        assert!(
            report.is_valid(),
            "Orphan should be warning in non-strict mode"
        );
        assert_eq!(report.warning_count(), 1);
    }

    #[test]
    fn test_orphan_error_strict() {
        let graph = KnowledgeGraphBuilder::new()
            .add_item(create_test_item("UC-001", ItemType::UseCase))
            .build()
            .unwrap();

        // Strict mode: orphan is an error
        let report = validate(&graph, true);
        assert!(!report.is_valid(), "Orphan should be error in strict mode");
        assert_eq!(report.error_count(), 1);
    }

    #[test]
    fn test_cycle_detection() {
        // Create a cycle
        let scen1 = create_test_item_with_upstream(
            "SCEN-001",
            ItemType::Scenario,
            UpstreamRefs {
                refines: vec![ItemId::new_unchecked("SCEN-002")],
                ..Default::default()
            },
        );
        let scen2 = create_test_item_with_upstream(
            "SCEN-002",
            ItemType::Scenario,
            UpstreamRefs {
                refines: vec![ItemId::new_unchecked("SCEN-001")],
                ..Default::default()
            },
        );

        let graph = KnowledgeGraphBuilder::new()
            .add_item(scen1)
            .add_item(scen2)
            .build()
            .unwrap();

        let report = validate(&graph, false);
        assert!(!report.is_valid(), "Cycle should be detected");
    }

    #[test]
    fn test_invalid_relationship() {
        // Scenario trying to refine Solution directly (invalid)
        let graph = KnowledgeGraphBuilder::new()
            .add_item(create_test_item("SOL-001", ItemType::Solution))
            .add_item(create_test_item_with_upstream(
                "SCEN-001",
                ItemType::Scenario,
                UpstreamRefs {
                    refines: vec![ItemId::new_unchecked("SOL-001")],
                    ..Default::default()
                },
            ))
            .build()
            .unwrap();

        let report = validate(&graph, false);
        assert!(
            !report.is_valid(),
            "Invalid relationship should be detected"
        );
    }

    #[test]
    fn test_pre_validate_valid_items() {
        let source = SourceLocation::new(PathBuf::from("/repo"), "SYSREQ-001.md");
        let item = ItemBuilder::new()
            .id(ItemId::new_unchecked("SYSREQ-001"))
            .item_type(ItemType::SystemRequirement)
            .name("Test Requirement")
            .source(source)
            .attributes(ItemAttributes::SystemRequirement {
                specification: "The system SHALL respond within 100ms".to_string(),
                depends_on: Vec::new(),
            })
            .build()
            .unwrap();

        let report = pre_validate(&[item], false);
        assert!(
            report.is_valid(),
            "Valid item should have no pre-validation errors"
        );
        assert_eq!(
            report.warning_count(),
            0,
            "Valid item should have no pre-validation warnings"
        );
    }

    #[test]
    fn test_pre_validate_invalid_specification() {
        let source = SourceLocation::new(PathBuf::from("/repo"), "SYSREQ-001.md");
        let item = ItemBuilder::new()
            .id(ItemId::new_unchecked("SYSREQ-001"))
            .item_type(ItemType::SystemRequirement)
            .name("Test Requirement")
            .source(source)
            .attributes(ItemAttributes::SystemRequirement {
                specification: "The system responds within 100ms".to_string(), // Missing RFC2119 keyword
                depends_on: Vec::new(),
            })
            .build()
            .unwrap();

        let report = pre_validate(&[item], false);
        assert_eq!(
            report.error_count(),
            1,
            "Should detect missing RFC2119 keyword"
        );
        let errors = report.errors();
        assert!(matches!(
            errors[0],
            ValidationError::InvalidMetadata { reason, .. } if reason.contains("RFC2119")
        ));
    }

    #[test]
    fn test_pre_validate_empty_specification() {
        let source = SourceLocation::new(PathBuf::from("/repo"), "SYSREQ-001.md");
        let item = ItemBuilder::new()
            .id(ItemId::new_unchecked("SYSREQ-001"))
            .item_type(ItemType::SystemRequirement)
            .name("Test Requirement")
            .source(source)
            .attributes(ItemAttributes::SystemRequirement {
                specification: String::new(),
                depends_on: Vec::new(),
            })
            .build()
            .unwrap();

        let report = pre_validate(&[item], false);
        assert_eq!(report.error_count(), 1, "Should detect empty specification");
        let errors = report.errors();
        assert!(matches!(
            errors[0],
            ValidationError::InvalidMetadata { reason, .. } if reason.contains("non-empty")
        ));
    }

    #[test]
    fn test_pre_validate_solution_no_errors() {
        // Solution type doesn't require specification - should pass pre-validation
        let source = SourceLocation::new(PathBuf::from("/repo"), "SOL-001.md");
        let item = ItemBuilder::new()
            .id(ItemId::new_unchecked("SOL-001"))
            .item_type(ItemType::Solution)
            .name("Test Solution")
            .source(source)
            .attributes(ItemAttributes::for_type(ItemType::Solution))
            .build()
            .unwrap();

        let report = pre_validate(&[item], false);
        assert!(report.is_valid(), "Solution should pass pre-validation");
        assert_eq!(report.warning_count(), 0);
    }

    #[test]
    fn test_pre_validate_multiple_items() {
        let items = vec![
            ItemBuilder::new()
                .id(ItemId::new_unchecked("SYSREQ-001"))
                .item_type(ItemType::SystemRequirement)
                .name("Valid Requirement")
                .source(SourceLocation::new(PathBuf::from("/repo"), "SYSREQ-001.md"))
                .attributes(ItemAttributes::SystemRequirement {
                    specification: "The system SHALL respond".to_string(),
                    depends_on: Vec::new(),
                })
                .build()
                .unwrap(),
            ItemBuilder::new()
                .id(ItemId::new_unchecked("SYSREQ-002"))
                .item_type(ItemType::SystemRequirement)
                .name("Invalid Requirement")
                .source(SourceLocation::new(PathBuf::from("/repo"), "SYSREQ-002.md"))
                .attributes(ItemAttributes::SystemRequirement {
                    specification: "Missing keyword".to_string(), // Invalid
                    depends_on: Vec::new(),
                })
                .build()
                .unwrap(),
            ItemBuilder::new()
                .id(ItemId::new_unchecked("SOL-001"))
                .item_type(ItemType::Solution)
                .name("Solution")
                .source(SourceLocation::new(PathBuf::from("/repo"), "SOL-001.md"))
                .attributes(ItemAttributes::for_type(ItemType::Solution))
                .build()
                .unwrap(),
        ];

        let report = pre_validate(&items, false);
        assert_eq!(report.error_count(), 1, "Should detect one invalid item");
        assert_eq!(report.warning_count(), 0);
    }
}