sara-core 0.6.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
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
//! Edit service for modifying existing document metadata.
//!
//! Provides functionality for editing requirement items (FR-054 through FR-066).

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

use crate::error::SaraError;
use crate::generator::{self, OutputFormat};
use crate::graph::KnowledgeGraph;
use crate::model::{
    FieldChange, FieldName, Item, ItemBuilder, ItemId, ItemType, RelationshipType, SourceLocation,
    TraceabilityLinks,
};
use crate::parser::update_frontmatter;
use crate::query::lookup_item_or_suggest;

/// Options for editing an item.
#[derive(Debug, Clone, Default)]
pub struct EditOptions {
    /// The item ID to edit.
    pub item_id: String,
    /// New name (if provided).
    pub name: Option<String>,
    /// New description (if provided).
    pub description: Option<String>,
    /// New refines references (if provided).
    pub refines: Option<Vec<String>>,
    /// New derives_from references (if provided).
    pub derives_from: Option<Vec<String>>,
    /// New satisfies references (if provided).
    pub satisfies: Option<Vec<String>>,
    /// New depends_on references (if provided).
    pub depends_on: Option<Vec<String>>,
    /// New justifies references (if provided, for ADRs).
    pub justifies: Option<Vec<String>>,
    /// New specification (if provided).
    pub specification: Option<String>,
    /// New platform (if provided).
    pub platform: Option<String>,
}

impl EditOptions {
    /// Creates new edit options for the given item ID.
    pub fn new(item_id: impl Into<String>) -> Self {
        Self {
            item_id: item_id.into(),
            ..Default::default()
        }
    }

    /// Sets the name.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the name if provided.
    pub fn maybe_name(mut self, name: Option<String>) -> Self {
        self.name = name;
        self
    }

    /// Sets the description.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets the description if provided.
    pub fn maybe_description(mut self, description: Option<String>) -> Self {
        self.description = description;
        self
    }

    /// Sets the refines references.
    pub fn with_refines(mut self, refines: Vec<String>) -> Self {
        self.refines = Some(refines);
        self
    }

    /// Sets the refines references if provided.
    pub fn maybe_refines(mut self, refines: Option<Vec<String>>) -> Self {
        self.refines = refines;
        self
    }

    /// Sets the derives_from references.
    pub fn with_derives_from(mut self, derives_from: Vec<String>) -> Self {
        self.derives_from = Some(derives_from);
        self
    }

    /// Sets the derives_from references if provided.
    pub fn maybe_derives_from(mut self, derives_from: Option<Vec<String>>) -> Self {
        self.derives_from = derives_from;
        self
    }

    /// Sets the satisfies references.
    pub fn with_satisfies(mut self, satisfies: Vec<String>) -> Self {
        self.satisfies = Some(satisfies);
        self
    }

    /// Sets the satisfies references if provided.
    pub fn maybe_satisfies(mut self, satisfies: Option<Vec<String>>) -> Self {
        self.satisfies = satisfies;
        self
    }

    /// Sets the depends_on references.
    pub fn with_depends_on(mut self, depends_on: Vec<String>) -> Self {
        self.depends_on = Some(depends_on);
        self
    }

    /// Sets the depends_on references if provided.
    pub fn maybe_depends_on(mut self, depends_on: Option<Vec<String>>) -> Self {
        self.depends_on = depends_on;
        self
    }

    /// Sets the justifies references.
    pub fn with_justifies(mut self, justifies: Vec<String>) -> Self {
        self.justifies = Some(justifies);
        self
    }

    /// Sets the justifies references if provided.
    pub fn maybe_justifies(mut self, justifies: Option<Vec<String>>) -> Self {
        self.justifies = justifies;
        self
    }

    /// Sets the specification.
    pub fn with_specification(mut self, specification: impl Into<String>) -> Self {
        self.specification = Some(specification.into());
        self
    }

    /// Sets the specification if provided.
    pub fn maybe_specification(mut self, specification: Option<String>) -> Self {
        self.specification = specification;
        self
    }

    /// Sets the platform.
    pub fn with_platform(mut self, platform: impl Into<String>) -> Self {
        self.platform = Some(platform.into());
        self
    }

    /// Sets the platform if provided.
    pub fn maybe_platform(mut self, platform: Option<String>) -> Self {
        self.platform = platform;
        self
    }

    /// Returns true if any modification was requested.
    pub fn has_updates(&self) -> bool {
        self.name.is_some()
            || self.description.is_some()
            || self.refines.is_some()
            || self.derives_from.is_some()
            || self.satisfies.is_some()
            || self.depends_on.is_some()
            || self.justifies.is_some()
            || self.specification.is_some()
            || self.platform.is_some()
    }
}

/// Values to apply during editing.
#[derive(Debug, Clone)]
pub struct EditedValues {
    /// The name.
    pub name: String,
    /// Optional description.
    pub description: Option<String>,
    /// Optional specification.
    pub specification: Option<String>,
    /// Optional platform.
    pub platform: Option<String>,
    /// Traceability links.
    pub traceability: TraceabilityLinks,
}

impl EditedValues {
    /// Creates new edited values.
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: None,
            specification: None,
            platform: None,
            traceability: TraceabilityLinks::default(),
        }
    }

    /// Sets the description.
    pub fn with_description(mut self, description: Option<String>) -> Self {
        self.description = description;
        self
    }

    /// Sets the specification.
    pub fn with_specification(mut self, specification: Option<String>) -> Self {
        self.specification = specification;
        self
    }

    /// Sets the platform.
    pub fn with_platform(mut self, platform: Option<String>) -> Self {
        self.platform = platform;
        self
    }

    /// Sets the traceability links.
    pub fn with_traceability(mut self, traceability: TraceabilityLinks) -> Self {
        self.traceability = traceability;
        self
    }
}

/// 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().map(ToOwned::to_owned),
            platform: item.attributes.platform().map(ToOwned::to_owned),
            traceability: TraceabilityLinks::from_item(item),
            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, SaraError> {
        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<(), SaraError> {
        if opts.specification.is_some() && !item_type.requires_specification() {
            return Err(SaraError::EditFailed(format!(
                "--specification is only valid for requirement types, not {}",
                item_type.display_name()
            )));
        }

        if opts.platform.is_some() && item_type != ItemType::SystemArchitecture {
            return Err(SaraError::EditFailed(
                "--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()),
                depends_on: opts
                    .depends_on
                    .clone()
                    .unwrap_or_else(|| current.traceability.depends_on.clone()),
                justifies: opts
                    .justifies
                    .clone()
                    .unwrap_or_else(|| current.traceability.justifies.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<(), SaraError> {
        let content =
            fs::read_to_string(file_path).map_err(|e| SaraError::EditFailed(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| SaraError::EditFailed(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 item = self.build_item_from_values(item_id, item_type, values);
        generator::generate_metadata(&item, OutputFormat::Markdown)
    }

    /// Builds a temporary `Item` from edit values for frontmatter generation.
    fn build_item_from_values(
        &self,
        item_id: &str,
        item_type: ItemType,
        values: &EditedValues,
    ) -> Item {
        let source = SourceLocation {
            repository: PathBuf::new(),
            file_path: PathBuf::from("edit.md"),
            git_ref: None,
        };

        let mut builder = ItemBuilder::new()
            .id(ItemId::new_unchecked(item_id))
            .item_type(item_type)
            .name(&values.name)
            .source(source);

        if let Some(ref desc) = values.description {
            builder = builder.description(desc);
        }

        // Build relationships from traceability links
        let mut rels =
            super::ids_to_relationships(&values.traceability.refines, RelationshipType::Refines);
        rels.extend(super::ids_to_relationships(
            &values.traceability.derives_from,
            RelationshipType::DerivesFrom,
        ));
        rels.extend(super::ids_to_relationships(
            &values.traceability.satisfies,
            RelationshipType::Satisfies,
        ));
        rels.extend(super::ids_to_relationships(
            &values.traceability.justifies,
            RelationshipType::Justifies,
        ));
        builder = builder.relationships(rels);

        // Type-specific attributes
        if let Some(ref spec) = values.specification {
            builder = builder.specification(spec);
        }
        if let Some(ref plat) = values.platform {
            builder = builder.platform(plat);
        }
        for id in &values.traceability.depends_on {
            builder = builder.depends_on(ItemId::new_unchecked(id));
        }

        // ADR types need status and deciders to build successfully.
        // For edits, provide defaults since those fields are not
        // part of EditedValues (they are preserved from the original).
        if item_type == ItemType::ArchitectureDecisionRecord {
            builder = builder
                .status(crate::model::AdrStatus::Proposed)
                .decider("TBD");
        }

        builder.build().expect("Failed to build item for edit")
    }

    /// Performs a non-interactive edit operation.
    pub fn edit(
        &self,
        graph: &KnowledgeGraph,
        opts: &EditOptions,
    ) -> Result<EditResult, SaraError> {
        // 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::test_utils::create_test_item_with_name;

    #[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_with_name("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\""));
    }
}