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
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
//! SpecToIntentConverter - Converts domain specs to executable Intents
//!
//! This is the core integration between Spec DSL and the execution pipeline.

use thiserror::Error;

use super::types::*;
use crate::intent::{EstimatedScope, Goal, Intent, ScopeHint, SelfParam};

/// Conversion error
#[derive(Debug, Error)]
pub enum ConversionError {
    #[error("Invalid module path: {0}")]
    InvalidModulePath(String),

    #[error("Missing required field: {0}")]
    MissingField(String),

    #[error("Invalid variant type format: {0}")]
    InvalidVariantType(String),

    #[error("Unsupported refactor kind: {0}")]
    UnsupportedRefactor(String),
}

/// Conversion result with phase information
#[derive(Debug, Clone)]
pub struct ConversionResult {
    /// All generated intents organized by phase
    pub phases: Vec<PhaseIntents>,

    /// Total intent count
    pub total_intents: usize,

    /// Estimated lines of code
    pub estimated_loc: usize,
}

/// Intents for a single phase
#[derive(Debug, Clone)]
pub struct PhaseIntents {
    /// Phase name
    pub name: String,

    /// Phase number (1-based)
    pub phase: usize,

    /// Generated Goal
    pub goal: Goal,

    /// Description
    pub description: String,
}

/// Converter from DomainSpec to Vec<Intent>
pub struct SpecToIntentConverter {
    /// Project name for symbol paths
    _crate_name: String,
}

impl SpecToIntentConverter {
    /// Create a new converter
    pub fn new(crate_name: impl Into<String>) -> Self {
        Self {
            _crate_name: crate_name.into(),
        }
    }

    /// Convert entire spec to ConversionResult
    pub fn convert(&self, spec: &DomainSpec) -> Result<ConversionResult, ConversionError> {
        let mut phases = Vec::new();
        let mut total_intents = 0;

        // Phase 1: Module Structure
        let phase1_intents = self.convert_modules(spec)?;
        if !phase1_intents.is_empty() {
            total_intents += phase1_intents.len();
            phases.push(PhaseIntents {
                name: "Module Structure".to_string(),
                phase: 1,
                goal: self.create_goal("Phase 1: Create module structure", phase1_intents),
                description: "Create module hierarchy".to_string(),
            });
        }

        // Phase 2: Common Types
        let phase2_intents = self.convert_common_types(spec)?;
        if !phase2_intents.is_empty() {
            total_intents += phase2_intents.len();
            phases.push(PhaseIntents {
                name: "Common Types".to_string(),
                phase: 2,
                goal: self.create_goal("Phase 2: Create common types", phase2_intents),
                description: "Create newtypes, value objects".to_string(),
            });
        }

        // Phase 3: Domain Entities
        let phase3_intents = self.convert_entities(spec)?;
        if !phase3_intents.is_empty() {
            total_intents += phase3_intents.len();
            phases.push(PhaseIntents {
                name: "Domain Entities".to_string(),
                phase: 3,
                goal: self.create_goal("Phase 3: Create domain entities", phase3_intents),
                description: "Create structs, enums".to_string(),
            });
        }

        // Phase 4: Error Types
        let phase4_intents = self.convert_errors(spec)?;
        if !phase4_intents.is_empty() {
            total_intents += phase4_intents.len();
            phases.push(PhaseIntents {
                name: "Error Types".to_string(),
                phase: 4,
                goal: self.create_goal("Phase 4: Create error types", phase4_intents),
                description: "Create error enums".to_string(),
            });
        }

        // Phase 5: Implementations
        let phase5_intents = self.convert_implementations(spec)?;
        if !phase5_intents.is_empty() {
            total_intents += phase5_intents.len();
            phases.push(PhaseIntents {
                name: "Implementations".to_string(),
                phase: 5,
                goal: self.create_goal("Phase 5: Add methods", phase5_intents),
                description: "Add impl blocks and methods".to_string(),
            });
        }

        // Phase 6: Refactoring
        let phase6_intents = self.convert_refactors(spec)?;
        if !phase6_intents.is_empty() {
            total_intents += phase6_intents.len();
            phases.push(PhaseIntents {
                name: "Refactoring".to_string(),
                phase: 6,
                goal: self.create_goal("Phase 6: Apply refactorings", phase6_intents),
                description: "Builder patterns, From/Into, etc.".to_string(),
            });
        }

        // Estimate LOC: ~50 lines per intent on average
        let estimated_loc = total_intents * 50;

        Ok(ConversionResult {
            phases,
            total_intents,
            estimated_loc,
        })
    }

    /// Convert modules to CreateMod intents
    fn convert_modules(&self, spec: &DomainSpec) -> Result<Vec<Intent>, ConversionError> {
        let mut intents = Vec::new();

        for module in &spec.modules {
            // Skip "lib" as root - it's already the crate root
            if module.name == "lib" {
                // Process children directly
                for child in &module.children {
                    self.collect_module_intents(child, &[], &mut intents);
                }
            } else {
                self.collect_module_intents(module, &[], &mut intents);
            }
        }

        Ok(intents)
    }

    /// Recursively collect CreateMod intents
    fn collect_module_intents(
        &self,
        module: &ModuleSpec,
        parent_path: &[String],
        intents: &mut Vec<Intent>,
    ) {
        intents.push(Intent::CreateMod {
            parent_mod: parent_path.to_vec(),
            mod_name: module.name.clone(),
            content: String::new(),
            is_pub: module.is_pub,
        });

        let mut new_path = parent_path.to_vec();
        new_path.push(module.name.clone());

        for child in &module.children {
            self.collect_module_intents(child, &new_path, intents);
        }
    }

    /// Convert common types (newtypes, value objects)
    fn convert_common_types(&self, spec: &DomainSpec) -> Result<Vec<Intent>, ConversionError> {
        let mut intents = Vec::new();

        if let Some(common) = &spec.common_types {
            // Newtypes
            for newtype in &common.newtypes {
                // Generate newtype struct code
                let derives_str = if newtype.derives.is_empty() {
                    String::new()
                } else {
                    format!("#[derive({})]\n", newtype.derives.join(", "))
                };

                let content = format!(
                    "{}pub struct {}(pub {});",
                    derives_str, newtype.name, newtype.inner
                );

                intents.push(Intent::AddItem {
                    symbol_id: None,
                    symbol_path: None,
                    target_mod: Some(newtype.module.clone()),
                    content,
                    item_kind: ryo_source::ItemKind::Struct,
                });
            }

            // Value objects (structs/enums)
            for vo in &common.value_objects {
                intents.extend(self.convert_entity(vo)?);
            }
        }

        Ok(intents)
    }

    /// Convert entities to AddItem/AddEnum intents
    fn convert_entities(&self, spec: &DomainSpec) -> Result<Vec<Intent>, ConversionError> {
        let mut intents = Vec::new();

        for entity in &spec.entities {
            intents.extend(self.convert_entity(entity)?);
        }

        Ok(intents)
    }

    /// Convert a single entity
    fn convert_entity(&self, entity: &EntitySpec) -> Result<Vec<Intent>, ConversionError> {
        let mut intents = Vec::new();

        match entity.kind {
            EntityKind::Struct | EntityKind::Newtype => {
                // Generate struct code
                let derives_str = if entity.derives.is_empty() {
                    String::new()
                } else {
                    format!("#[derive({})]\n", entity.derives.join(", "))
                };

                let fields_str: String = entity
                    .fields
                    .iter()
                    .map(|f| {
                        let vis = if f.is_pub { "pub " } else { "" };
                        format!("    {}{}: {},", vis, f.name, f.ty)
                    })
                    .collect::<Vec<_>>()
                    .join("\n");

                let content = format!(
                    "{}pub struct {} {{\n{}\n}}",
                    derives_str, entity.name, fields_str
                );

                intents.push(Intent::AddItem {
                    symbol_id: None,
                    symbol_path: None,
                    target_mod: Some(entity.module.clone()),
                    content,
                    item_kind: ryo_source::ItemKind::Struct,
                });
            }
            EntityKind::Enum => {
                // Use AddEnum intent
                let variants: Vec<String> = entity
                    .variants
                    .iter()
                    .map(|v| v.name().to_string())
                    .collect();

                intents.push(Intent::AddEnum {
                    symbol_path: entity.module.clone(),
                    name: entity.name.clone(),
                    variants,
                    is_pub: true,
                    derives: entity.derives.clone(),
                });
            }
        }

        Ok(intents)
    }

    /// Convert error types
    fn convert_errors(&self, spec: &DomainSpec) -> Result<Vec<Intent>, ConversionError> {
        let mut intents = Vec::new();

        for error in &spec.errors {
            // Generate error enum with complex variants
            let derives_str = if error.derives.is_empty() {
                String::new()
            } else {
                format!("#[derive({})]\n", error.derives.join(", "))
            };

            let variants_str: String = error
                .variants
                .iter()
                .map(|v| {
                    let name = v.name();
                    match v.variant_type() {
                        None => format!("    {},", name),
                        Some(vt) => {
                            // Parse variant type: "struct:field1:Type1,field2:Type2"
                            if let Some(fields) = vt.strip_prefix("struct:") {
                                let field_parts: Vec<&str> = fields.split(',').collect();
                                let fields_str: String = field_parts
                                    .iter()
                                    .map(|fp| {
                                        let parts: Vec<&str> = fp.split(':').collect();
                                        if parts.len() == 2 {
                                            format!("{}: {}", parts[0], parts[1])
                                        } else {
                                            fp.to_string()
                                        }
                                    })
                                    .collect::<Vec<_>>()
                                    .join(", ");
                                format!("    {} {{ {} }},", name, fields_str)
                            } else {
                                format!("    {}({}),", name, vt)
                            }
                        }
                    }
                })
                .collect::<Vec<_>>()
                .join("\n");

            let content = format!(
                "{}pub enum {} {{\n{}\n}}",
                derives_str, error.name, variants_str
            );

            intents.push(Intent::AddItem {
                symbol_id: None,
                symbol_path: None,
                target_mod: Some(error.module.clone()),
                content,
                item_kind: ryo_source::ItemKind::Enum,
            });
        }

        Ok(intents)
    }

    /// Convert implementations to AddMethod intents
    fn convert_implementations(&self, spec: &DomainSpec) -> Result<Vec<Intent>, ConversionError> {
        let mut intents = Vec::new();

        for impl_spec in &spec.implementations {
            for method in &impl_spec.methods {
                let self_param = method.self_param.map(|sp| match sp {
                    SelfParamSpec::Ref => SelfParam::Ref,
                    SelfParamSpec::Mut => SelfParam::Mut,
                    SelfParamSpec::Owned => SelfParam::Owned,
                });

                intents.push(Intent::AddMethod {
                    symbol_id: None,
                    symbol_path: None,
                    target_type: Some(impl_spec.target.clone()),
                    method_name: method.name.clone(),
                    params: method.params.clone(),
                    return_type: method.return_type.clone(),
                    body: method.body.clone(),
                    is_pub: method.is_pub,
                    self_param,
                });
            }
        }

        Ok(intents)
    }

    /// Convert refactoring specs
    fn convert_refactors(&self, spec: &DomainSpec) -> Result<Vec<Intent>, ConversionError> {
        let mut intents = Vec::new();

        for refactor in &spec.refactors {
            match refactor {
                RefactorSpec::AddBuilderPattern { targets } => {
                    // For each target, add builder-related methods
                    for target in targets {
                        // Add builder() method
                        intents.push(Intent::AddMethod {
                            symbol_id: None,
                            symbol_path: None,
                            target_type: Some(target.clone()),
                            method_name: "builder".to_string(),
                            params: vec![],
                            return_type: Some(format!("{}Builder", target)),
                            body: format!("{}Builder::default()", target),
                            is_pub: true,
                            self_param: None,
                        });

                        // Note: Full builder struct would require more complex generation
                        // For now, we generate a stub that can be expanded
                    }
                }
                RefactorSpec::AddFromInto { pairs } => {
                    for (from, to) in pairs {
                        // Add From<Inner> for Newtype
                        let content = format!(
                            "impl From<{}> for {} {{\n    fn from(v: {}) -> Self {{\n        Self(v)\n    }}\n}}",
                            to, from, to
                        );

                        intents.push(Intent::AddItem {
                            symbol_id: None,
                            symbol_path: Some(from.clone()),
                            target_mod: None,
                            content,
                            item_kind: ryo_source::ItemKind::Impl,
                        });
                    }
                }
                RefactorSpec::AddDefault { targets } => {
                    for target in targets {
                        intents.push(Intent::AddDerive {
                            symbol_id: None,
                            symbol_path: None,
                            target_type: Some(target.clone()),
                            derives: vec!["Default".to_string()],
                        });
                    }
                }
                RefactorSpec::OrganizeImports { target_modules } => match target_modules {
                    TargetModules::All => {
                        intents.push(Intent::OrganizeImports {
                            target_mod: None,
                            deduplicate: true,
                            merge_groups: true,
                        });
                    }
                    TargetModules::List(modules) => {
                        for module in modules {
                            intents.push(Intent::OrganizeImports {
                                target_mod: Some(module.clone()),
                                deduplicate: true,
                                merge_groups: true,
                            });
                        }
                    }
                },
            }
        }

        Ok(intents)
    }

    /// Create a Goal from intents
    fn create_goal(&self, query: &str, intents: Vec<Intent>) -> Goal {
        Goal::with_intents(query, intents).with_scope(
            ScopeHint::new()
                .with_file_patterns(vec!["src/**/*.rs".to_string()])
                .with_estimated_scope(EstimatedScope::ProjectWide),
        )
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::spec_dsl::parser::parse_spec;

    #[test]
    fn test_convert_modules() {
        let yaml = r#"
project:
  name: "test"
  crate_name: "test_crate"

modules:
  - name: lib
    is_pub: true
    children:
      - name: user
        is_pub: true
      - name: product
        is_pub: true
"#;

        let spec = parse_spec(yaml).unwrap();
        let converter = SpecToIntentConverter::new("test_crate");
        let result = converter.convert(&spec).unwrap();

        assert!(!result.phases.is_empty());
        assert_eq!(result.phases[0].name, "Module Structure");
        assert_eq!(result.phases[0].goal.intents.len(), 2); // user, product
    }

    #[test]
    fn test_convert_entities() {
        let yaml = r#"
project:
  name: "test"

entities:
  - name: User
    module: user
    fields:
      - name: id
        type: UserId
      - name: name
        type: String
    derives: [Debug, Clone]

  - name: UserStatus
    module: user
    kind: enum
    variants:
      - Active
      - Inactive
    derives: [Debug, Clone, Copy]
"#;

        let spec = parse_spec(yaml).unwrap();
        let converter = SpecToIntentConverter::new("test_crate");
        let result = converter.convert(&spec).unwrap();

        // Should have Domain Entities phase
        let entity_phase = result.phases.iter().find(|p| p.name == "Domain Entities");
        assert!(entity_phase.is_some());

        let phase = entity_phase.unwrap();
        assert_eq!(phase.goal.intents.len(), 2);
    }

    #[test]
    fn test_convert_implementations() {
        let yaml = r#"
project:
  name: "test"

implementations:
  - target: UserId
    methods:
      - name: new
        self_param: null
        return_type: Self
        body: "Self(uuid::Uuid::new_v4())"
        is_pub: true
      - name: inner
        self_param: ref
        return_type: "uuid::Uuid"
        body: "self.0"
        is_pub: true
"#;

        let spec = parse_spec(yaml).unwrap();
        let converter = SpecToIntentConverter::new("test_crate");
        let result = converter.convert(&spec).unwrap();

        let impl_phase = result.phases.iter().find(|p| p.name == "Implementations");
        assert!(impl_phase.is_some());

        let phase = impl_phase.unwrap();
        assert_eq!(phase.goal.intents.len(), 2);

        // Check first method
        if let Intent::AddMethod {
            method_name,
            self_param,
            ..
        } = &phase.goal.intents[0]
        {
            assert_eq!(method_name, "new");
            assert!(self_param.is_none());
        } else {
            panic!("Expected AddMethod intent");
        }

        // Check second method
        if let Intent::AddMethod {
            method_name,
            self_param,
            ..
        } = &phase.goal.intents[1]
        {
            assert_eq!(method_name, "inner");
            assert_eq!(*self_param, Some(SelfParam::Ref));
        } else {
            panic!("Expected AddMethod intent");
        }
    }

    #[test]
    fn test_total_intent_count() {
        let yaml = r#"
project:
  name: "ecommerce"

modules:
  - name: lib
    children:
      - name: user
        is_pub: true
      - name: product
        is_pub: true

entities:
  - name: User
    module: user
    fields:
      - name: id
        type: UserId
    derives: [Debug, Clone]

implementations:
  - target: User
    methods:
      - name: new
        return_type: Self
        body: "todo!()"
        is_pub: true

refactors:
  - kind: OrganizeImports
    target_modules: all
"#;

        let spec = parse_spec(yaml).unwrap();
        let converter = SpecToIntentConverter::new("ecommerce");
        let result = converter.convert(&spec).unwrap();

        // 2 modules + 1 entity + 1 method + 1 organize = 5 intents
        assert_eq!(result.total_intents, 5);
        assert!(result.estimated_loc > 0);
    }
}