ryo-app 0.1.0

[preview] Application layer for RYO - Project management, Intent handling, API
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
//! SpecFlow service - builds and queries SpecFlowGraphV2.

use std::collections::{HashMap, HashSet};
use std::path::Path;

use ryo_analysis::{
    AnalysisContext, SpecFlowBuilderV2, SpecFlowGraphV2, SpecSource, SymbolId, SymbolKind,
    SymbolRegistry, TypeAliasRegistryBuilder,
};
use thiserror::Error;

use super::response::{
    LintSeverity, SpecGroupInfo, SpecInfo, SpecLintIssue, SpecLintResult, SpecRelation,
    SpecRelationKind, SpecShowResponse, SpecSourceKind, SpecStats,
};
use crate::Project;

/// SpecFlow service error.
#[derive(Debug, Error)]
pub enum SpecError {
    /// Project error.
    #[error("Project error: {0}")]
    Project(String),
}

/// SpecFlow service for building and querying SpecFlowGraphV2.
pub struct SpecService;

impl SpecService {
    /// Create a new SpecService.
    pub fn new() -> Self {
        Self
    }

    /// Build SpecFlowData from an existing AnalysisContext.
    ///
    /// This is the preferred method for server mode where AnalysisContext
    /// is already loaded and cached.
    pub fn from_context(ctx: &AnalysisContext) -> Result<SpecFlowData, SpecError> {
        // Build symbol lookup
        let symbol_lookup = build_symbol_lookup(ctx.registry());

        // Build TypeAliasRegistry
        let alias_files: Vec<_> = ctx
            .files()
            .iter()
            .map(|(wfp, pure_file)| (wfp.clone(), pure_file.as_ref()))
            .collect();

        let alias_registry_builder = TypeAliasRegistryBuilder::new(ctx.registry(), &symbol_lookup);
        let alias_registry = alias_registry_builder.build(&alias_files);

        // Build SpecFlowGraphV2 (DoD - names pre-resolved)
        let specflow_builder = SpecFlowBuilderV2::new(&alias_registry, ctx.registry());
        let specflow = specflow_builder.build();

        Ok(SpecFlowData { specflow })
    }

    /// Create AnalysisContext from a project using workspace_root.
    fn build_context(project: &Project) -> Result<AnalysisContext, SpecError> {
        AnalysisContext::from_workspace_root(project.workspace_root())
            .map_err(|e| SpecError::Project(e.to_string()))
    }

    /// Load SpecFlowGraphV2 from a project.
    ///
    /// **Note**: This rebuilds AnalysisContext from scratch. For server mode,
    /// prefer `from_context()` which reuses the existing context.
    pub fn load(&self, project: &Project) -> Result<SpecFlowData, SpecError> {
        let ctx = Self::build_context(project)?;
        Self::from_context(&ctx)
    }

    /// Load SpecFlowGraphV2 from a path.
    pub fn from_path(&self, path: &Path) -> Result<SpecFlowData, SpecError> {
        let project = Project::load(path).map_err(|e| SpecError::Project(e.to_string()))?;
        self.load(&project)
    }

    /// Get spec show response (groups, relations, stats).
    pub fn show(&self, project: &Project) -> Result<SpecShowResponse, SpecError> {
        let data = self.load(project)?;
        Ok(data.to_show_response())
    }

    /// Get stats only.
    pub fn stats(&self, project: &Project) -> Result<SpecStats, SpecError> {
        let data = self.load(project)?;
        Ok(data.stats())
    }

    /// Get groups only.
    pub fn groups(&self, project: &Project) -> Result<Vec<String>, SpecError> {
        let data = self.load(project)?;
        Ok(data.group_names())
    }

    /// Get specs in a group.
    pub fn specs_in_group(
        &self,
        project: &Project,
        group: &str,
    ) -> Result<Vec<SpecInfo>, SpecError> {
        let data = self.load(project)?;
        Ok(data.specs_in_group(group))
    }

    /// Lint specs for consistency issues.
    pub fn lint(&self, project: &Project) -> Result<SpecLintResult, SpecError> {
        let data = self.load(project)?;
        Ok(data.lint())
    }

    /// Generate Mermaid diagram.
    pub fn mermaid(&self, project: &Project) -> Result<String, SpecError> {
        let data = self.load(project)?;
        Ok(data.to_mermaid())
    }
}

impl Default for SpecService {
    fn default() -> Self {
        Self::new()
    }
}

/// Loaded SpecFlow data (DoD - no registry needed).
pub struct SpecFlowData {
    pub specflow: SpecFlowGraphV2,
}

impl SpecFlowData {
    /// Get statistics.
    pub fn stats(&self) -> SpecStats {
        SpecStats {
            groups: self.specflow.group_count(),
            specs: self.specflow.spec_count(),
            nodes: self.specflow.node_count(),
            edges: self.specflow.edge_count(),
        }
    }

    /// Get all group names.
    pub fn group_names(&self) -> Vec<String> {
        self.specflow.group_names().map(|s| s.to_string()).collect()
    }

    /// Get specs in a group.
    pub fn specs_in_group(&self, group: &str) -> Vec<SpecInfo> {
        self.specflow
            .specs_in_group_by_name(group)
            .filter_map(|spec_id| {
                self.specflow.get_spec_alias(spec_id).map(|data| {
                    let alias_name = self
                        .specflow
                        .spec_name(spec_id)
                        .unwrap_or("<unknown>")
                        .to_string();
                    let wrapped_type_name = self
                        .specflow
                        .wrapped_type_name(spec_id)
                        .unwrap_or("<unknown>")
                        .to_string();

                    SpecInfo {
                        alias_name,
                        wrapped_type_name,
                        source: convert_source(data.source),
                    }
                })
            })
            .collect()
    }

    /// Convert to SpecShowResponse.
    pub fn to_show_response(&self) -> SpecShowResponse {
        let groups: Vec<SpecGroupInfo> = self
            .specflow
            .group_names()
            .map(|name| SpecGroupInfo {
                name: name.to_string(),
                specs: self.specs_in_group(name),
            })
            .collect();

        let relations = self.collect_relations();
        let stats = self.stats();

        SpecShowResponse {
            groups,
            relations,
            stats,
        }
    }

    /// Collect all dependency relations.
    fn collect_relations(&self) -> Vec<SpecRelation> {
        let mut relations = Vec::new();

        for group_name in self.specflow.group_names() {
            for spec_id in self.specflow.specs_in_group_by_name(group_name) {
                if let Some(from_name) = self.specflow.spec_name(spec_id) {
                    for dep_id in self.specflow.dependencies(spec_id) {
                        if let Some(to_name) = self.specflow.spec_name(dep_id) {
                            relations.push(SpecRelation {
                                from: from_name.to_string(),
                                to: to_name.to_string(),
                                kind: SpecRelationKind::DependsOn,
                            });
                        }
                    }
                }
            }
        }

        relations
    }

    /// Lint for consistency issues.
    pub fn lint(&self) -> SpecLintResult {
        let mut issues = Vec::new();

        // Check for empty specs
        if self.specflow.is_empty() {
            issues.push(SpecLintIssue {
                severity: LintSeverity::Warning,
                message: "No spec markers found in project".to_string(),
                location: None,
            });
        }

        // Check for duplicate names across groups
        let mut seen_specs: HashSet<String> = HashSet::new();
        for group_name in self.specflow.group_names() {
            for spec_id in self.specflow.specs_in_group_by_name(group_name) {
                if let Some(alias_name) = self.specflow.spec_name(spec_id) {
                    if seen_specs.contains(alias_name) {
                        issues.push(SpecLintIssue {
                            severity: LintSeverity::Warning,
                            message: format!(
                                "Spec '{}' appears in multiple groups (including '{}')",
                                alias_name, group_name
                            ),
                            location: None,
                        });
                    }
                    seen_specs.insert(alias_name.to_string());
                }
            }
        }

        // Check for self-references and circular dependencies
        for group_name in self.specflow.group_names() {
            for spec_id in self.specflow.specs_in_group_by_name(group_name) {
                if let Some(alias_name) = self.specflow.spec_name(spec_id) {
                    for dep_id in self.specflow.dependencies(spec_id) {
                        // Self-reference
                        if spec_id == dep_id {
                            issues.push(SpecLintIssue {
                                severity: LintSeverity::Error,
                                message: format!(
                                    "Self-reference detected: '{}' depends on itself",
                                    alias_name
                                ),
                                location: None,
                            });
                        }

                        // 2-hop circular
                        for back_dep_id in self.specflow.dependencies(dep_id) {
                            if back_dep_id == spec_id {
                                if let Some(dep_name) = self.specflow.spec_name(dep_id) {
                                    issues.push(SpecLintIssue {
                                        severity: LintSeverity::Warning,
                                        message: format!(
                                            "Circular dependency: '{}' <-> '{}'",
                                            alias_name, dep_name
                                        ),
                                        location: None,
                                    });
                                }
                            }
                        }
                    }
                }
            }
        }

        // Deduplicate
        issues.dedup_by(|a, b| a.message == b.message);

        let warnings = issues
            .iter()
            .filter(|i| i.severity == LintSeverity::Warning)
            .count();
        let errors = issues
            .iter()
            .filter(|i| i.severity == LintSeverity::Error)
            .count();

        SpecLintResult {
            issues,
            warnings,
            errors,
        }
    }

    /// Generate Mermaid diagram.
    pub fn to_mermaid(&self) -> String {
        let mut lines = vec!["graph TD".to_string()];

        // Subgraphs for groups
        for group_name in self.specflow.group_names() {
            lines.push(format!("    subgraph {}", group_name));
            for spec_id in self.specflow.specs_in_group_by_name(group_name) {
                if let Some(alias_name) = self.specflow.spec_name(spec_id) {
                    lines.push(format!("        {}[{}]", alias_name, alias_name));
                }
            }
            lines.push("    end".to_string());
        }

        // Relations
        for group_name in self.specflow.group_names() {
            for spec_id in self.specflow.specs_in_group_by_name(group_name) {
                if let Some(alias_name) = self.specflow.spec_name(spec_id) {
                    for dep_id in self.specflow.dependencies(spec_id) {
                        if let Some(dep_name) = self.specflow.spec_name(dep_id) {
                            lines.push(format!("    {}-->|depends|{}", alias_name, dep_name));
                        }
                    }
                }
            }
        }

        lines.join("\n")
    }
}

/// Build symbol lookup map from SymbolRegistry.
fn build_symbol_lookup(registry: &SymbolRegistry) -> HashMap<String, SymbolId> {
    let mut lookup = HashMap::new();

    for (id, path) in registry.iter() {
        if let Some(
            SymbolKind::Struct | SymbolKind::Enum | SymbolKind::Trait | SymbolKind::TypeAlias,
        ) = registry.kind(id)
        {
            // Full path
            lookup.insert(path.to_string(), id);
            // Short name (last segment)
            if let Some(name) = path.segments().last() {
                lookup.insert(name.to_string(), id);
            }
        }
    }

    lookup
}

/// Convert SpecSource to SpecSourceKind.
fn convert_source(source: SpecSource) -> SpecSourceKind {
    match source {
        SpecSource::TypeAlias => SpecSourceKind::TypeAlias,
        SpecSource::Comment => SpecSourceKind::Comment,
        SpecSource::Inferred => SpecSourceKind::Inferred,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn create_test_context(source: &str) -> AnalysisContext {
        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let src_dir = temp_dir.path().join("src");
        std::fs::create_dir_all(&src_dir).expect("Failed to create src dir");

        let lib_rs = src_dir.join("lib.rs");
        std::fs::write(&lib_rs, source).expect("Failed to write lib.rs");

        let cargo_toml = temp_dir.path().join("Cargo.toml");
        std::fs::write(
            &cargo_toml,
            r#"[package]
name = "test_crate"
version = "0.1.0"
edition = "2021"
"#,
        )
        .expect("Failed to write Cargo.toml");

        // Keep temp_dir alive by leaking it (tests don't need cleanup)
        let workspace_root = temp_dir.path().to_path_buf();
        std::mem::forget(temp_dir);

        AnalysisContext::from_workspace_root(&workspace_root)
            .expect("Failed to create AnalysisContext")
    }

    #[test]
    fn test_from_context_empty() {
        let ctx = create_test_context("");
        let result = SpecService::from_context(&ctx);
        assert!(result.is_ok());
        let data = result.unwrap();
        assert_eq!(data.stats().specs, 0);
    }

    #[test]
    fn test_from_context_with_type_alias() {
        let ctx = create_test_context(
            r#"
            pub type UserId = String;
            pub type Email = String;
            "#,
        );
        let result = SpecService::from_context(&ctx);
        assert!(result.is_ok());
        // Type aliases are parsed successfully
        let _data = result.unwrap();
    }

    #[test]
    fn test_from_context_with_struct() {
        let ctx = create_test_context(
            r#"
            pub struct User {
                pub id: String,
                pub name: String,
            }
            "#,
        );
        let result = SpecService::from_context(&ctx);
        assert!(result.is_ok());
    }

    #[test]
    fn test_from_context_groups() {
        let ctx = create_test_context(
            r#"
            pub type UserId = String;
            "#,
        );
        let result = SpecService::from_context(&ctx);
        assert!(result.is_ok());
        let data = result.unwrap();
        // group_names() should return without panic
        let _groups = data.group_names();
    }

    #[test]
    fn test_from_context_lint() {
        let ctx = create_test_context("");
        let result = SpecService::from_context(&ctx);
        assert!(result.is_ok());
        let data = result.unwrap();
        let lint = data.lint();
        // Empty context should have no lint issues
        assert_eq!(lint.errors, 0);
    }

    #[test]
    fn test_from_context_mermaid() {
        let ctx = create_test_context(
            r#"
            pub type UserId = String;
            "#,
        );
        let result = SpecService::from_context(&ctx);
        assert!(result.is_ok());
        let data = result.unwrap();
        let mermaid = data.to_mermaid();
        assert!(mermaid.starts_with("graph TD"));
    }

    #[test]
    fn test_from_context_complex_source() {
        // Verify from_context handles complex source
        let source = r#"
            pub type UserId = String;
            pub struct User { pub id: UserId }
        "#;
        let ctx = create_test_context(source);

        let result = SpecService::from_context(&ctx);
        assert!(result.is_ok());
        let data = result.unwrap();
        // Should have parsed stats
        let _stats = data.stats();
    }
}