sara-core 0.3.0

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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! Edit service implementation.

use std::fs;
use std::path::PathBuf;

use crate::error::EditError;
use crate::graph::KnowledgeGraph;
use crate::model::{FieldChange, FieldName, Item, ItemType, TraceabilityLinks};
use crate::parser::update_frontmatter;
use crate::query::lookup_item_or_suggest;

use super::{EditOptions, EditedValues};

/// Result of a successful edit operation.
#[derive(Debug)]
pub struct EditResult {
    /// The item ID that was edited.
    pub item_id: String,
    /// The file path that was modified.
    pub file_path: PathBuf,
    /// The changes that were applied.
    pub changes: Vec<FieldChange>,
}

impl EditResult {
    /// Returns true if any changes were made.
    pub fn has_changes(&self) -> bool {
        !self.changes.is_empty()
    }

    /// Returns the number of changes.
    pub fn change_count(&self) -> usize {
        self.changes.len()
    }
}

/// Context for the item being edited.
#[derive(Debug, Clone)]
pub struct ItemContext {
    /// The item ID.
    pub id: String,
    /// The item type.
    pub item_type: ItemType,
    /// The current name.
    pub name: String,
    /// The current description.
    pub description: Option<String>,
    /// The current specification.
    pub specification: Option<String>,
    /// The current platform.
    pub platform: Option<String>,
    /// The current traceability links.
    pub traceability: TraceabilityLinks,
    /// The file path.
    pub file_path: PathBuf,
}

impl ItemContext {
    /// Creates a context from an Item.
    pub fn from_item(item: &Item) -> Self {
        Self {
            id: item.id.as_str().to_string(),
            item_type: item.item_type,
            name: item.name.clone(),
            description: item.description.clone(),
            specification: item.attributes.specification.clone(),
            platform: item.attributes.platform.clone(),
            traceability: TraceabilityLinks::from_upstream(&item.upstream),
            file_path: item.source.full_path(),
        }
    }
}

/// Service for editing requirement items.
#[derive(Debug, Default)]
pub struct EditService;

impl EditService {
    /// Creates a new edit service.
    pub fn new() -> Self {
        Self
    }

    /// Looks up an item by ID with fuzzy suggestions on failure.
    pub fn lookup_item<'a>(
        &self,
        graph: &'a KnowledgeGraph,
        item_id: &str,
    ) -> Result<&'a Item, EditError> {
        lookup_item_or_suggest(graph, item_id)
    }

    /// Gets the context for an item.
    pub fn get_item_context(&self, item: &Item) -> ItemContext {
        ItemContext::from_item(item)
    }

    /// Validates edit options against the item type.
    pub fn validate_options(
        &self,
        opts: &EditOptions,
        item_type: ItemType,
    ) -> Result<(), EditError> {
        if opts.specification.is_some() && !item_type.requires_specification() {
            return Err(EditError::IoError(format!(
                "--specification is only valid for requirement types, not {}",
                item_type.display_name()
            )));
        }

        if opts.platform.is_some() && item_type != ItemType::SystemArchitecture {
            return Err(EditError::IoError(
                "--platform is only valid for System Architecture items".to_string(),
            ));
        }

        Ok(())
    }

    /// Merges edit options with current item values.
    pub fn merge_values(&self, opts: &EditOptions, current: &ItemContext) -> EditedValues {
        EditedValues {
            name: opts.name.clone().unwrap_or_else(|| current.name.clone()),
            description: opts
                .description
                .clone()
                .or_else(|| current.description.clone()),
            specification: opts
                .specification
                .clone()
                .or_else(|| current.specification.clone()),
            platform: opts.platform.clone().or_else(|| current.platform.clone()),
            traceability: TraceabilityLinks {
                refines: opts
                    .refines
                    .clone()
                    .unwrap_or_else(|| current.traceability.refines.clone()),
                derives_from: opts
                    .derives_from
                    .clone()
                    .unwrap_or_else(|| current.traceability.derives_from.clone()),
                satisfies: opts
                    .satisfies
                    .clone()
                    .unwrap_or_else(|| current.traceability.satisfies.clone()),
            },
        }
    }

    /// Builds a change summary comparing old and new values.
    pub fn build_change_summary(&self, old: &ItemContext, new: &EditedValues) -> Vec<FieldChange> {
        let mut changes = Vec::new();

        changes.push(FieldChange::new(FieldName::Name, &old.name, &new.name));
        changes.push(FieldChange::new(
            FieldName::Description,
            old.description.as_deref().unwrap_or("(none)"),
            new.description.as_deref().unwrap_or("(none)"),
        ));

        // Traceability changes
        self.add_traceability_change(
            &mut changes,
            FieldName::Refines,
            &old.traceability.refines,
            &new.traceability.refines,
        );
        self.add_traceability_change(
            &mut changes,
            FieldName::DerivesFrom,
            &old.traceability.derives_from,
            &new.traceability.derives_from,
        );
        self.add_traceability_change(
            &mut changes,
            FieldName::Satisfies,
            &old.traceability.satisfies,
            &new.traceability.satisfies,
        );

        // Type-specific
        if old.specification.is_some() || new.specification.is_some() {
            changes.push(FieldChange::new(
                FieldName::Specification,
                old.specification.as_deref().unwrap_or("(none)"),
                new.specification.as_deref().unwrap_or("(none)"),
            ));
        }

        if old.platform.is_some() || new.platform.is_some() {
            changes.push(FieldChange::new(
                FieldName::Platform,
                old.platform.as_deref().unwrap_or("(none)"),
                new.platform.as_deref().unwrap_or("(none)"),
            ));
        }

        changes
    }

    /// Adds a traceability field change if values differ.
    fn add_traceability_change(
        &self,
        changes: &mut Vec<FieldChange>,
        field: FieldName,
        old: &[String],
        new: &[String],
    ) {
        if old.is_empty() && new.is_empty() {
            return;
        }

        let old_str = if old.is_empty() {
            "(none)".to_string()
        } else {
            old.join(", ")
        };
        let new_str = if new.is_empty() {
            "(none)".to_string()
        } else {
            new.join(", ")
        };

        changes.push(FieldChange::new(field, &old_str, &new_str));
    }

    /// Applies changes to the file.
    pub fn apply_changes(
        &self,
        item_id: &str,
        item_type: ItemType,
        new_values: &EditedValues,
        file_path: &PathBuf,
    ) -> Result<(), EditError> {
        let content =
            fs::read_to_string(file_path).map_err(|e| EditError::IoError(e.to_string()))?;
        let new_yaml = self.build_frontmatter_yaml(item_id, item_type, new_values);
        let updated_content = update_frontmatter(&content, &new_yaml);
        fs::write(file_path, updated_content).map_err(|e| EditError::IoError(e.to_string()))?;
        Ok(())
    }

    /// Builds YAML frontmatter string from edit values.
    pub fn build_frontmatter_yaml(
        &self,
        item_id: &str,
        item_type: ItemType,
        values: &EditedValues,
    ) -> String {
        let mut yaml = format!(
            "{}: \"{}\"\n{}: {}\n{}: \"{}\"\n",
            FieldName::Id.as_str(),
            item_id,
            FieldName::Type.as_str(),
            item_type.as_str(),
            FieldName::Name.as_str(),
            values.name.replace('"', "\\\"")
        );

        if let Some(ref desc) = values.description {
            yaml += &format!(
                "{}: \"{}\"\n",
                FieldName::Description.as_str(),
                desc.replace('"', "\\\"")
            );
        }

        self.append_traceability_yaml(
            &mut yaml,
            FieldName::Refines.as_str(),
            &values.traceability.refines,
        );
        self.append_traceability_yaml(
            &mut yaml,
            FieldName::DerivesFrom.as_str(),
            &values.traceability.derives_from,
        );
        self.append_traceability_yaml(
            &mut yaml,
            FieldName::Satisfies.as_str(),
            &values.traceability.satisfies,
        );

        if let Some(ref spec) = values.specification {
            yaml += &format!(
                "{}: \"{}\"\n",
                FieldName::Specification.as_str(),
                spec.replace('"', "\\\"")
            );
        }

        if let Some(ref plat) = values.platform {
            yaml += &format!(
                "{}: \"{}\"\n",
                FieldName::Platform.as_str(),
                plat.replace('"', "\\\"")
            );
        }

        yaml
    }

    /// Appends a traceability list to YAML if non-empty.
    fn append_traceability_yaml(&self, yaml: &mut String, field: &str, ids: &[String]) {
        if ids.is_empty() {
            return;
        }

        *yaml += &format!("{}:\n", field);
        for id in ids {
            *yaml += &format!("  - \"{}\"\n", id);
        }
    }

    /// Performs a non-interactive edit operation.
    pub fn edit(
        &self,
        graph: &KnowledgeGraph,
        opts: &EditOptions,
    ) -> Result<EditResult, EditError> {
        // Look up the item
        let item = self.lookup_item(graph, &opts.item_id)?;
        let item_ctx = self.get_item_context(item);

        // Validate options
        self.validate_options(opts, item_ctx.item_type)?;

        // Merge values
        let new_values = self.merge_values(opts, &item_ctx);

        // Build change summary
        let changes: Vec<FieldChange> = self
            .build_change_summary(&item_ctx, &new_values)
            .into_iter()
            .filter(|c| c.is_changed())
            .collect();

        // Apply changes
        self.apply_changes(
            &item_ctx.id,
            item_ctx.item_type,
            &new_values,
            &item_ctx.file_path,
        )?;

        Ok(EditResult {
            item_id: item_ctx.id,
            file_path: item_ctx.file_path,
            changes,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::{ItemBuilder, ItemId, SourceLocation};

    fn create_test_item(id: &str, item_type: ItemType, name: &str) -> Item {
        let source = SourceLocation::new(PathBuf::from("/repo"), format!("{}.md", id));
        let mut builder = ItemBuilder::new()
            .id(ItemId::new_unchecked(id))
            .item_type(item_type)
            .name(name)
            .source(source);

        if item_type.requires_specification() {
            builder = builder.specification("Test specification");
        }

        builder.build().unwrap()
    }

    #[test]
    fn test_edit_options_has_updates() {
        let opts = EditOptions::new("SOL-001");
        assert!(!opts.has_updates());

        let opts_with_name = EditOptions::new("SOL-001").with_name("New Name");
        assert!(opts_with_name.has_updates());
    }

    #[test]
    fn test_item_context_from_item() {
        let item = create_test_item("SOL-001", ItemType::Solution, "Test Solution");
        let ctx = ItemContext::from_item(&item);

        assert_eq!(ctx.id, "SOL-001");
        assert_eq!(ctx.name, "Test Solution");
        assert_eq!(ctx.item_type, ItemType::Solution);
    }

    #[test]
    fn test_validate_options_specification() {
        let service = EditService::new();

        // Valid: specification on requirement type
        let opts = EditOptions::new("SYSREQ-001").with_specification("new spec");
        assert!(
            service
                .validate_options(&opts, ItemType::SystemRequirement)
                .is_ok()
        );

        // Invalid: specification on solution type
        let opts = EditOptions::new("SOL-001").with_specification("new spec");
        assert!(service.validate_options(&opts, ItemType::Solution).is_err());
    }

    #[test]
    fn test_validate_options_platform() {
        let service = EditService::new();

        // Valid: platform on system architecture
        let opts = EditOptions::new("SYSARCH-001").with_platform("AWS");
        assert!(
            service
                .validate_options(&opts, ItemType::SystemArchitecture)
                .is_ok()
        );

        // Invalid: platform on solution
        let opts = EditOptions::new("SOL-001").with_platform("AWS");
        assert!(service.validate_options(&opts, ItemType::Solution).is_err());
    }

    #[test]
    fn test_merge_values() {
        let service = EditService::new();

        let current = ItemContext {
            id: "SOL-001".to_string(),
            item_type: ItemType::Solution,
            name: "Old Name".to_string(),
            description: Some("Old Description".to_string()),
            specification: None,
            platform: None,
            traceability: TraceabilityLinks::default(),
            file_path: PathBuf::from("/test.md"),
        };

        let opts = EditOptions::new("SOL-001").with_name("New Name");

        let merged = service.merge_values(&opts, &current);

        assert_eq!(merged.name, "New Name");
        assert_eq!(merged.description, Some("Old Description".to_string()));
    }

    #[test]
    fn test_build_change_summary() {
        let service = EditService::new();

        let old = ItemContext {
            id: "SOL-001".to_string(),
            item_type: ItemType::Solution,
            name: "Old Name".to_string(),
            description: None,
            specification: None,
            platform: None,
            traceability: TraceabilityLinks::default(),
            file_path: PathBuf::from("/test.md"),
        };

        let new = EditedValues::new("New Name");

        let changes = service.build_change_summary(&old, &new);

        let name_change = changes.iter().find(|c| c.field == FieldName::Name).unwrap();
        assert!(name_change.is_changed());
        assert_eq!(name_change.old_value, "Old Name");
        assert_eq!(name_change.new_value, "New Name");
    }

    #[test]
    fn test_build_frontmatter_yaml() {
        let service = EditService::new();

        let values = EditedValues::new("Test Solution")
            .with_description(Some("A test solution".to_string()));

        let yaml = service.build_frontmatter_yaml("SOL-001", ItemType::Solution, &values);

        assert!(yaml.contains("id: \"SOL-001\""));
        assert!(yaml.contains("type: solution"));
        assert!(yaml.contains("name: \"Test Solution\""));
        assert!(yaml.contains("description: \"A test solution\""));
    }
}