ryo-suggest 0.1.0

[experimental] Pattern-based suggestion engine for RYO
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
//! Design choice types for multiple alternative suggestions.
//!
//! This module provides types for representing design choices when a suggestion
//! has multiple valid implementation approaches. For example, when converting
//! an enum to a trait, the user might choose between:
//! - Full dynamic dispatch (Box<dyn Trait>)
//! - Static dispatch with generics
//! - Enum-based wrapper
//!
//! # Example
//!
//! ```ignore
//! let choices = DesignChoiceSet {
//!     suggestion_id: suggestion.id,
//!     pattern_name: "EnumToTrait".to_string(),
//!     choices: vec![
//!         DesignChoice::new("A", "Full Dynamic", "Use Box<dyn Trait> for maximum flexibility"),
//!         DesignChoice::new("B", "Static Dispatch", "Use generics for better performance"),
//!     ],
//!     recommended: Some(ChoiceId::new("A")),
//! };
//! ```

use crate::SuggestId;
use ryo_executor::executor::MutationSpec;
use serde::{Deserialize, Serialize};
use std::fmt;
use std::path::PathBuf;

/// Unique identifier for a design choice within a set.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ChoiceId(String);

impl ChoiceId {
    /// Create a new choice ID.
    pub fn new(id: impl Into<String>) -> Self {
        Self(id.into())
    }

    /// Get the ID as a string reference.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl fmt::Display for ChoiceId {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl From<&str> for ChoiceId {
    fn from(s: &str) -> Self {
        Self::new(s)
    }
}

/// Rating level for trade-off dimensions (1-3 stars).
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[repr(u8)]
#[derive(Default)]
pub enum Rating {
    /// Low (★☆☆)
    Low = 1,
    /// Medium (★★☆)
    #[default]
    Medium = 2,
    /// High (★★★)
    High = 3,
}

impl Rating {
    /// Convert rating to star representation.
    pub fn stars(&self) -> &'static str {
        match self {
            Rating::Low => "★☆☆",
            Rating::Medium => "★★☆",
            Rating::High => "★★★",
        }
    }

    /// Get numeric value (1-3).
    pub fn value(&self) -> u8 {
        *self as u8
    }
}

impl fmt::Display for Rating {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.stars())
    }
}

/// Trade-off analysis for a design choice.
///
/// Provides a structured view of the pros/cons of each choice
/// to help users make informed decisions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TradeOffs {
    /// How easy it is to extend this design later.
    pub extensibility: Rating,

    /// Runtime performance characteristics.
    pub performance: Rating,

    /// Implementation complexity.
    pub complexity: Rating,

    /// Whether this change breaks existing API.
    pub breaking_change: bool,

    /// Files that will be affected by this choice.
    pub affected_files: Vec<PathBuf>,
}

impl TradeOffs {
    /// Create trade-offs with all medium ratings and no breaking change.
    pub fn default_medium() -> Self {
        Self {
            extensibility: Rating::Medium,
            performance: Rating::Medium,
            complexity: Rating::Medium,
            breaking_change: false,
            affected_files: Vec::new(),
        }
    }

    /// Builder method to set extensibility.
    pub fn with_extensibility(mut self, rating: Rating) -> Self {
        self.extensibility = rating;
        self
    }

    /// Builder method to set performance.
    pub fn with_performance(mut self, rating: Rating) -> Self {
        self.performance = rating;
        self
    }

    /// Builder method to set complexity.
    pub fn with_complexity(mut self, rating: Rating) -> Self {
        self.complexity = rating;
        self
    }

    /// Builder method to set breaking change flag.
    pub fn with_breaking_change(mut self, breaking: bool) -> Self {
        self.breaking_change = breaking;
        self
    }

    /// Builder method to add affected files.
    pub fn with_affected_files(mut self, files: Vec<PathBuf>) -> Self {
        self.affected_files = files;
        self
    }

    /// Calculate a simple score based on ratings.
    /// Higher is better. Penalizes complexity and breaking changes.
    pub fn score(&self) -> f32 {
        let ext = self.extensibility.value() as f32;
        let perf = self.performance.value() as f32;
        let comp = self.complexity.value() as f32;

        // Score formula: extensibility + performance - complexity/2
        // Breaking changes reduce score by 1
        let base_score = ext + perf - comp / 2.0;
        if self.breaking_change {
            base_score - 1.0
        } else {
            base_score
        }
    }
}

impl Default for TradeOffs {
    fn default() -> Self {
        Self::default_medium()
    }
}

/// A single design choice representing one possible implementation approach.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesignChoice {
    /// Unique identifier within the choice set (e.g., "A", "B", "C").
    pub id: ChoiceId,

    /// Short label for display (e.g., "A").
    pub label: String,

    /// Human-readable title (e.g., "Full Dynamic (Box<dyn Trait>)").
    pub title: String,

    /// Detailed description of this approach.
    pub description: String,

    /// Trade-off analysis.
    pub trade_offs: TradeOffs,

    /// Intent/MutationSpec group to execute for this choice.
    /// Already converted from Intents for direct execution.
    pub specs: Vec<MutationSpec>,
}

impl DesignChoice {
    /// Create a new design choice with minimal information.
    pub fn new(
        id: impl Into<ChoiceId>,
        label: impl Into<String>,
        title: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            title: title.into(),
            description: description.into(),
            trade_offs: TradeOffs::default(),
            specs: Vec::new(),
        }
    }

    /// Builder method to set trade-offs.
    pub fn with_trade_offs(mut self, trade_offs: TradeOffs) -> Self {
        self.trade_offs = trade_offs;
        self
    }

    /// Builder method to set specs.
    pub fn with_specs(mut self, specs: Vec<MutationSpec>) -> Self {
        self.specs = specs;
        self
    }

    /// Get the number of specs in this choice.
    pub fn spec_count(&self) -> usize {
        self.specs.len()
    }

    /// Check if this is a breaking change.
    pub fn is_breaking(&self) -> bool {
        self.trade_offs.breaking_change
    }
}

/// A set of design choices for a single suggestion.
///
/// When a suggestion has multiple valid approaches, this type
/// groups them together with a recommended default.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DesignChoiceSet {
    /// ID of the parent suggestion.
    pub suggestion_id: SuggestId,

    /// Name of the pattern that generated these choices (e.g., "EnumToTrait").
    pub pattern_name: String,

    /// Available choices.
    pub choices: Vec<DesignChoice>,

    /// Recommended choice ID (if any).
    pub recommended: Option<ChoiceId>,
}

impl DesignChoiceSet {
    /// Create a new choice set.
    pub fn new(suggestion_id: SuggestId, pattern_name: impl Into<String>) -> Self {
        Self {
            suggestion_id,
            pattern_name: pattern_name.into(),
            choices: Vec::new(),
            recommended: None,
        }
    }

    /// Add a choice to the set.
    pub fn add_choice(mut self, choice: DesignChoice) -> Self {
        self.choices.push(choice);
        self
    }

    /// Set the recommended choice.
    pub fn with_recommended(mut self, id: impl Into<ChoiceId>) -> Self {
        self.recommended = Some(id.into());
        self
    }

    /// Get a choice by ID.
    pub fn get_choice(&self, id: &ChoiceId) -> Option<&DesignChoice> {
        self.choices.iter().find(|c| &c.id == id)
    }

    /// Get the recommended choice (if set and exists).
    pub fn get_recommended(&self) -> Option<&DesignChoice> {
        self.recommended.as_ref().and_then(|id| self.get_choice(id))
    }

    /// Check if this set has multiple choices.
    pub fn has_alternatives(&self) -> bool {
        self.choices.len() > 1
    }

    /// Get the number of choices.
    pub fn choice_count(&self) -> usize {
        self.choices.len()
    }

    /// Get choices sorted by trade-off score (highest first).
    pub fn choices_by_score(&self) -> Vec<&DesignChoice> {
        let mut sorted: Vec<_> = self.choices.iter().collect();
        sorted.sort_by(|a, b| {
            b.trade_offs
                .score()
                .partial_cmp(&a.trade_offs.score())
                .unwrap_or(std::cmp::Ordering::Equal)
        });
        sorted
    }
}

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

    #[test]
    fn test_choice_id() {
        let id = ChoiceId::new("A");
        assert_eq!(id.as_str(), "A");
        assert_eq!(id.to_string(), "A");

        let id2: ChoiceId = "B".into();
        assert_eq!(id2.as_str(), "B");
    }

    #[test]
    fn test_rating_stars() {
        assert_eq!(Rating::Low.stars(), "★☆☆");
        assert_eq!(Rating::Medium.stars(), "★★☆");
        assert_eq!(Rating::High.stars(), "★★★");
    }

    #[test]
    fn test_rating_ordering() {
        assert!(Rating::Low < Rating::Medium);
        assert!(Rating::Medium < Rating::High);
    }

    #[test]
    fn test_trade_offs_score() {
        // High extensibility, high performance, low complexity = best score
        let good = TradeOffs::default_medium()
            .with_extensibility(Rating::High)
            .with_performance(Rating::High)
            .with_complexity(Rating::Low);
        assert!(good.score() > 4.0);

        // Low extensibility, low performance, high complexity = worst score
        let bad = TradeOffs::default_medium()
            .with_extensibility(Rating::Low)
            .with_performance(Rating::Low)
            .with_complexity(Rating::High);
        assert!(bad.score() < 2.0);

        // Breaking change penalty
        let breaking = TradeOffs::default_medium().with_breaking_change(true);
        let non_breaking = TradeOffs::default_medium().with_breaking_change(false);
        assert!(breaking.score() < non_breaking.score());
    }

    #[test]
    fn test_design_choice_builder() {
        let choice = DesignChoice::new(
            ChoiceId::new("A"),
            "A",
            "Full Dynamic",
            "Use Box<dyn Trait>",
        )
        .with_trade_offs(
            TradeOffs::default_medium()
                .with_extensibility(Rating::High)
                .with_performance(Rating::Low),
        );

        assert_eq!(choice.id.as_str(), "A");
        assert_eq!(choice.title, "Full Dynamic");
        assert_eq!(choice.trade_offs.extensibility, Rating::High);
        assert_eq!(choice.trade_offs.performance, Rating::Low);
    }

    #[test]
    fn test_design_choice_set() {
        let mut gen = SuggestIdGenerator::new();
        let suggestion_id = gen.next_id();

        let set = DesignChoiceSet::new(suggestion_id, "EnumToTrait")
            .add_choice(DesignChoice::new("A", "A", "Dynamic", "Box<dyn>"))
            .add_choice(DesignChoice::new("B", "B", "Static", "Generics"))
            .with_recommended("A");

        assert_eq!(set.choice_count(), 2);
        assert!(set.has_alternatives());
        assert!(set.get_choice(&ChoiceId::new("A")).is_some());
        assert!(set.get_choice(&ChoiceId::new("B")).is_some());
        assert!(set.get_choice(&ChoiceId::new("C")).is_none());

        let recommended = set.get_recommended();
        assert!(recommended.is_some());
        assert_eq!(recommended.unwrap().title, "Dynamic");
    }

    #[test]
    fn test_choices_by_score() {
        let mut gen = SuggestIdGenerator::new();
        let suggestion_id = gen.next_id();

        let set = DesignChoiceSet::new(suggestion_id, "Test")
            .add_choice(
                DesignChoice::new("A", "A", "Low Score", "desc").with_trade_offs(
                    TradeOffs::default_medium()
                        .with_extensibility(Rating::Low)
                        .with_performance(Rating::Low),
                ),
            )
            .add_choice(
                DesignChoice::new("B", "B", "High Score", "desc").with_trade_offs(
                    TradeOffs::default_medium()
                        .with_extensibility(Rating::High)
                        .with_performance(Rating::High),
                ),
            );

        let sorted = set.choices_by_score();
        assert_eq!(sorted[0].id.as_str(), "B"); // High score first
        assert_eq!(sorted[1].id.as_str(), "A");
    }

    #[test]
    fn test_trade_offs_serde() {
        let trade_offs = TradeOffs::default_medium()
            .with_extensibility(Rating::High)
            .with_breaking_change(true)
            .with_affected_files(vec![PathBuf::from("src/lib.rs")]);

        let json = serde_json::to_string(&trade_offs).unwrap();
        let parsed: TradeOffs = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.extensibility, Rating::High);
        assert!(parsed.breaking_change);
        assert_eq!(parsed.affected_files.len(), 1);
    }
}