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
//! Enhanced suggestion types with verification and design choices.
//!
//! This module extends the basic suggestion model with:
//! - Design choice sets for alternative implementations
//! - Verification status for each candidate
//! - Apply commands for easy execution
//!
//! # Architecture
//!
//! ```text
//! SuggestOpportunity (basic)
//!//!//! EnhancedSuggestion
//!   ├── design_choices: Option<DesignChoiceSet>
//!   ├── verified_candidates: Vec<VerifiedCandidate>
//!   └── apply_commands: ApplyCommands
//! ```

use crate::design_choice::{ChoiceId, DesignChoiceSet};
use crate::{SuggestId, SuggestLocation, SuggestOpportunity};
use serde::{Deserialize, Serialize};
use std::fmt;

/// Verification status for a candidate.
///
/// Indicates how thoroughly a candidate has been verified
/// before presenting it to the user.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub enum VerificationStatus {
    /// Not yet verified.
    #[default]
    Pending,

    /// Passed GraphChecker pre-check only (in-memory, ~100ms).
    /// Fast but not complete verification.
    LightCheck,

    /// Passed cargo check in TempWorkspace (complete verification).
    /// Guarantees the code will compile.
    FullyVerified,

    /// Verification failed with errors.
    Failed {
        /// Error messages from verification.
        errors: Vec<String>,
    },

    /// Verification was skipped (e.g., dry-run mode).
    Skipped,
}

impl VerificationStatus {
    /// Check if verification passed (LightCheck or FullyVerified).
    pub fn is_passed(&self) -> bool {
        matches!(self, Self::LightCheck | Self::FullyVerified)
    }

    /// Check if verification failed.
    pub fn is_failed(&self) -> bool {
        matches!(self, Self::Failed { .. })
    }

    /// Check if fully verified (cargo check passed).
    pub fn is_fully_verified(&self) -> bool {
        matches!(self, Self::FullyVerified)
    }

    /// Get error messages (if failed).
    pub fn errors(&self) -> Option<&[String]> {
        match self {
            Self::Failed { errors } => Some(errors),
            _ => None,
        }
    }
}

impl fmt::Display for VerificationStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Pending => write!(f, "pending"),
            Self::LightCheck => write!(f, "light-check"),
            Self::FullyVerified => write!(f, "verified"),
            Self::Failed { errors } => {
                write!(f, "failed ({} errors)", errors.len())
            }
            Self::Skipped => write!(f, "skipped"),
        }
    }
}

/// A verified candidate representing a potential change.
///
/// Links a design choice to its verification result and
/// provides summary information for display.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VerifiedCandidate {
    /// Reference to the choice this candidate represents.
    pub choice_id: ChoiceId,

    /// Verification status.
    pub verification: VerificationStatus,

    /// Summary of changes (e.g., "3 files, +45/-12 lines").
    pub diff_summary: String,

    /// Confidence score (0.0 - 1.0).
    /// May be adjusted based on verification results.
    pub confidence: f32,
}

impl VerifiedCandidate {
    /// Create a new verified candidate.
    pub fn new(choice_id: impl Into<ChoiceId>, confidence: f32) -> Self {
        Self {
            choice_id: choice_id.into(),
            verification: VerificationStatus::Pending,
            diff_summary: String::new(),
            confidence: confidence.clamp(0.0, 1.0),
        }
    }

    /// Set verification status.
    pub fn with_verification(mut self, status: VerificationStatus) -> Self {
        self.verification = status;
        self
    }

    /// Set diff summary.
    pub fn with_diff_summary(mut self, summary: impl Into<String>) -> Self {
        self.diff_summary = summary.into();
        self
    }

    /// Check if this candidate passed verification.
    pub fn is_verified(&self) -> bool {
        self.verification.is_passed()
    }

    /// Check if this candidate is fully verified.
    pub fn is_fully_verified(&self) -> bool {
        self.verification.is_fully_verified()
    }
}

/// Commands for applying a suggestion.
///
/// Provides ready-to-use CLI commands for users.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ApplyCommands {
    /// Command to preview changes (dry-run).
    pub preview: String,

    /// Command to apply changes.
    pub apply: String,

    /// Command to apply with verification.
    pub apply_verified: String,
}

impl ApplyCommands {
    /// Create apply commands for a given suggestion ID.
    pub fn for_suggestion(id: &SuggestId) -> Self {
        let id_str = id.to_string();
        Self {
            preview: format!("ryo suggest apply {} --dry-run", id_str),
            apply: format!("ryo suggest apply {} -e", id_str),
            apply_verified: format!("ryo suggest apply {} -e --verify", id_str),
        }
    }

    /// Create apply commands for a specific choice.
    pub fn for_choice(suggestion_id: &SuggestId, choice_id: &ChoiceId) -> Self {
        let suggest_str = suggestion_id.to_string();
        let choice_str = choice_id.as_str();
        Self {
            preview: format!(
                "ryo suggest apply {} --choice {} --dry-run",
                suggest_str, choice_str
            ),
            apply: format!(
                "ryo suggest apply {} --choice {} -e",
                suggest_str, choice_str
            ),
            apply_verified: format!(
                "ryo suggest apply {} --choice {} -e --verify",
                suggest_str, choice_str
            ),
        }
    }
}

/// An enhanced suggestion with design choices and verification.
///
/// This extends the basic `SuggestOpportunity` with:
/// - Multiple design choice alternatives
/// - Pre-verified candidates with confidence scores
/// - Ready-to-use CLI commands
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EnhancedSuggestion {
    /// Unique suggestion ID.
    pub id: SuggestId,

    /// Human-readable title.
    pub title: String,

    /// Primary location for display.
    pub location: SuggestLocation,

    /// Detailed description.
    pub description: String,

    /// Optional design choices (for suggestions with alternatives).
    pub design_choices: Option<DesignChoiceSet>,

    /// Verified candidates (subset of choices that passed verification).
    pub verified_candidates: Vec<VerifiedCandidate>,

    /// Commands for applying this suggestion.
    pub apply_commands: ApplyCommands,

    /// Original confidence from pattern detection.
    pub original_confidence: f32,
}

impl EnhancedSuggestion {
    /// Create an enhanced suggestion from a basic opportunity.
    pub fn from_opportunity(opportunity: &SuggestOpportunity, id: SuggestId) -> Self {
        Self {
            id,
            title: opportunity.message.clone(),
            location: opportunity.location.clone(),
            description: String::new(),
            design_choices: None,
            verified_candidates: Vec::new(),
            apply_commands: ApplyCommands::for_suggestion(&id),
            original_confidence: opportunity.confidence,
        }
    }

    /// Set design choices.
    pub fn with_design_choices(mut self, choices: DesignChoiceSet) -> Self {
        self.design_choices = Some(choices);
        self
    }

    /// Add a verified candidate.
    pub fn add_verified_candidate(mut self, candidate: VerifiedCandidate) -> Self {
        self.verified_candidates.push(candidate);
        self
    }

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

    /// Check if this suggestion has design choices.
    pub fn has_choices(&self) -> bool {
        self.design_choices
            .as_ref()
            .map(|c| c.has_alternatives())
            .unwrap_or(false)
    }

    /// Get the number of verified candidates.
    pub fn verified_count(&self) -> usize {
        self.verified_candidates
            .iter()
            .filter(|c| c.is_verified())
            .count()
    }

    /// Get the best verified candidate (highest confidence).
    pub fn best_candidate(&self) -> Option<&VerifiedCandidate> {
        self.verified_candidates
            .iter()
            .filter(|c| c.is_verified())
            .max_by(|a, b| {
                a.confidence
                    .partial_cmp(&b.confidence)
                    .unwrap_or(std::cmp::Ordering::Equal)
            })
    }

    /// Check if any candidate is fully verified.
    pub fn has_fully_verified(&self) -> bool {
        self.verified_candidates
            .iter()
            .any(|c| c.is_fully_verified())
    }

    /// Get all fully verified candidates.
    pub fn fully_verified_candidates(&self) -> Vec<&VerifiedCandidate> {
        self.verified_candidates
            .iter()
            .filter(|c| c.is_fully_verified())
            .collect()
    }
}

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

    fn create_test_opportunity() -> (SuggestOpportunity, SuggestId) {
        let mut gen = SuggestIdGenerator::new();
        let id = gen.next_id();

        let opportunity = SuggestOpportunity::new(
            OpportunityId::new(1),
            vec![],
            SuggestLocation::for_test("src/lib.rs", "MyStruct"),
            "Add #[derive(Default)] to MyStruct",
            0.95,
            OpportunityContext::Derive {
                derive_name: "Default".to_string(),
                missing_impls: vec![],
            },
        );

        (opportunity, id)
    }

    #[test]
    fn test_verification_status() {
        assert!(VerificationStatus::LightCheck.is_passed());
        assert!(VerificationStatus::FullyVerified.is_passed());
        assert!(!VerificationStatus::Pending.is_passed());
        assert!(!VerificationStatus::Failed { errors: vec![] }.is_passed());

        assert!(VerificationStatus::FullyVerified.is_fully_verified());
        assert!(!VerificationStatus::LightCheck.is_fully_verified());

        let failed = VerificationStatus::Failed {
            errors: vec!["error 1".to_string()],
        };
        assert!(failed.is_failed());
        assert_eq!(failed.errors().unwrap().len(), 1);
    }

    #[test]
    fn test_verification_status_display() {
        assert_eq!(VerificationStatus::Pending.to_string(), "pending");
        assert_eq!(VerificationStatus::LightCheck.to_string(), "light-check");
        assert_eq!(VerificationStatus::FullyVerified.to_string(), "verified");
        assert_eq!(VerificationStatus::Skipped.to_string(), "skipped");

        let failed = VerificationStatus::Failed {
            errors: vec!["e1".to_string(), "e2".to_string()],
        };
        assert_eq!(failed.to_string(), "failed (2 errors)");
    }

    #[test]
    fn test_verified_candidate() {
        let candidate = VerifiedCandidate::new("A", 0.9)
            .with_verification(VerificationStatus::FullyVerified)
            .with_diff_summary("2 files, +20/-5 lines");

        assert!(candidate.is_verified());
        assert!(candidate.is_fully_verified());
        assert_eq!(candidate.diff_summary, "2 files, +20/-5 lines");
        assert_eq!(candidate.confidence, 0.9);
    }

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

        let commands = ApplyCommands::for_suggestion(&id);
        assert!(commands.preview.contains("--dry-run"));
        assert!(commands.apply.contains("-e"));
        assert!(commands.apply_verified.contains("--verify"));

        let choice_commands = ApplyCommands::for_choice(&id, &ChoiceId::new("B"));
        assert!(choice_commands.apply.contains("--choice B"));
    }

    #[test]
    fn test_enhanced_suggestion_from_opportunity() {
        let (opportunity, id) = create_test_opportunity();

        let enhanced = EnhancedSuggestion::from_opportunity(&opportunity, id);

        assert_eq!(enhanced.title, opportunity.message);
        assert_eq!(enhanced.location, opportunity.location);
        assert_eq!(enhanced.original_confidence, opportunity.confidence);
        assert!(!enhanced.has_choices());
        assert_eq!(enhanced.verified_count(), 0);
    }

    #[test]
    fn test_enhanced_suggestion_with_candidates() {
        let (opportunity, id) = create_test_opportunity();

        let enhanced = EnhancedSuggestion::from_opportunity(&opportunity, id)
            .add_verified_candidate(
                VerifiedCandidate::new("A", 0.9)
                    .with_verification(VerificationStatus::FullyVerified),
            )
            .add_verified_candidate(
                VerifiedCandidate::new("B", 0.7).with_verification(VerificationStatus::LightCheck),
            )
            .add_verified_candidate(VerifiedCandidate::new("C", 0.8).with_verification(
                VerificationStatus::Failed {
                    errors: vec!["type mismatch".to_string()],
                },
            ));

        assert_eq!(enhanced.verified_count(), 2); // A and B passed
        assert!(enhanced.has_fully_verified());
        assert_eq!(enhanced.fully_verified_candidates().len(), 1);

        let best = enhanced.best_candidate().unwrap();
        assert_eq!(best.choice_id.as_str(), "A"); // Highest confidence among verified
    }

    #[test]
    fn test_enhanced_suggestion_serde() {
        let (opportunity, id) = create_test_opportunity();

        let enhanced = EnhancedSuggestion::from_opportunity(&opportunity, id)
            .with_description("Test description")
            .add_verified_candidate(
                VerifiedCandidate::new("A", 0.9)
                    .with_verification(VerificationStatus::FullyVerified),
            );

        let json = serde_json::to_string(&enhanced).unwrap();
        let parsed: EnhancedSuggestion = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed.description, "Test description");
        assert_eq!(parsed.verified_candidates.len(), 1);
    }
}