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
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
//! SuggestStore - Lifecycle management for suggestions
//!
//! Manages suggestion lifecycle in sync with AnalysisContext using
//! HashMap-based storage with generation-based invalidation.

use std::collections::HashMap;
use std::time::Instant;

use ryo_analysis::SymbolId;

use crate::id::SuggestId;
use crate::suggest::{compute_priority, OpportunityId, SafetyLevel, SuggestOpportunity};

/// Precheck verification status
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum PrecheckStatus {
    /// Not yet checked (default for non-precheck scans)
    #[default]
    NotChecked,
    /// Precheck passed - mutation is safe to apply
    Passed,
    /// Precheck failed - mutation would cause errors
    Failed,
}

/// Index into SuggestRegistry (newtype for type safety)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SuggestIndex(pub(crate) usize);

impl SuggestIndex {
    /// Get the underlying index value
    pub fn as_usize(self) -> usize {
        self.0
    }
}

/// Internal storage for a suggestion
#[derive(Debug)]
pub struct StoredSuggestion {
    /// The detected opportunity
    pub opportunity: SuggestOpportunity,

    /// Index into SuggestRegistry
    pub suggest_idx: SuggestIndex,

    /// Safety level (cached from Suggest)
    pub safety: SafetyLevel,

    /// Priority score (0-255, higher = more important)
    /// Computed from: confidence * safety_weight
    pub priority: u8,

    /// Precheck verification status
    pub precheck_status: PrecheckStatus,

    /// Generation counter (incremented on symbol modification)
    pub generation: u32,

    /// Closed flag (user dismissed or superseded)
    pub closed: bool,

    /// Reason for closing (if closed)
    pub close_reason: Option<String>,

    /// Creation timestamp (for GC)
    pub created_at: Instant,

    /// Close timestamp (for GC)
    pub closed_at: Option<Instant>,
}

impl StoredSuggestion {
    /// Create a new stored suggestion
    ///
    /// # Arguments
    /// - `opportunity`: The detected opportunity
    /// - `suggest_idx`: Index into SuggestRegistry
    /// - `safety`: Safety level from the Suggest implementation
    /// - `pattern_weight`: Priority weight from `Suggest::priority_weight()`
    pub fn new(
        opportunity: SuggestOpportunity,
        suggest_idx: SuggestIndex,
        safety: SafetyLevel,
        pattern_weight: f32,
    ) -> Self {
        let priority = compute_priority(opportunity.confidence, safety, pattern_weight);
        Self {
            opportunity,
            suggest_idx,
            safety,
            priority,
            precheck_status: PrecheckStatus::NotChecked,
            generation: 0,
            closed: false,
            close_reason: None,
            created_at: Instant::now(),
            closed_at: None,
        }
    }

    /// Create a stored suggestion with pre-computed priority
    ///
    /// Use this when priority has already been calculated (e.g., for sorting
    /// before expensive precheck operations).
    pub fn new_with_priority(
        opportunity: SuggestOpportunity,
        suggest_idx: SuggestIndex,
        safety: SafetyLevel,
        priority: u8,
    ) -> Self {
        Self {
            opportunity,
            suggest_idx,
            safety,
            priority,
            precheck_status: PrecheckStatus::NotChecked,
            generation: 0,
            closed: false,
            close_reason: None,
            created_at: Instant::now(),
            closed_at: None,
        }
    }

    /// Mark this suggestion as closed
    pub fn close(&mut self, reason: impl Into<String>) {
        self.closed = true;
        self.close_reason = Some(reason.into());
        self.closed_at = Some(Instant::now());
    }

    /// Bump the generation (invalidates previous references)
    pub fn bump_generation(&mut self) {
        self.generation += 1;
    }
}

/// Manages suggestion lifecycle in sync with AnalysisContext
pub struct SuggestStore {
    /// Primary storage: maps index to stored suggestion
    suggestions: HashMap<u32, StoredSuggestion>,

    /// Maps target symbol to suggestion indices (for invalidation)
    symbol_to_suggests: HashMap<SymbolId, Vec<u32>>,

    /// Dedup index: (pattern_index, opportunity_id) → suggestion index.
    /// Prevents the same opportunity from being inserted multiple times
    /// when detect() is called repeatedly (e.g., scan invoked multiple times).
    dedup_index: HashMap<(SuggestIndex, OpportunityId), u32>,

    /// Next index for SuggestId generation
    next_index: u32,
}

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

impl SuggestStore {
    /// Create a new empty store
    pub fn new() -> Self {
        Self {
            suggestions: HashMap::new(),
            symbol_to_suggests: HashMap::new(),
            dedup_index: HashMap::new(),
            next_index: 1, // Start at 1 for human-friendly IDs
        }
    }

    /// Insert a new suggestion, returning its ID.
    ///
    /// Returns `None` if an active (non-closed) suggestion with the same
    /// (pattern, opportunity_id) already exists (dedup).
    pub fn insert(&mut self, suggestion: StoredSuggestion) -> Option<SuggestId> {
        let dedup_key = (suggestion.suggest_idx, suggestion.opportunity.id);

        // Check for existing active suggestion with same identity
        if let Some(&existing_idx) = self.dedup_index.get(&dedup_key) {
            if self
                .suggestions
                .get(&existing_idx)
                .is_some_and(|s| !s.closed)
            {
                return None; // Active duplicate exists, skip
            }
        }

        let index = self.next_index;
        self.next_index += 1;

        let generation = suggestion.generation;
        let targets = suggestion.opportunity.targets.clone();

        // Track symbol → suggestion mapping
        for target in targets {
            self.symbol_to_suggests
                .entry(target)
                .or_default()
                .push(index);
        }

        self.dedup_index.insert(dedup_key, index);
        self.suggestions.insert(index, suggestion);

        Some(SuggestId::new(index, generation))
    }

    /// Get a suggestion by ID (returns None if invalid, stale, or closed)
    pub fn get(&self, id: SuggestId) -> Option<&StoredSuggestion> {
        self.suggestions
            .get(&id.index())
            .filter(|sug| sug.generation == id.generation() && !sug.closed)
    }

    /// Get a mutable reference to a suggestion by ID
    pub fn get_mut(&mut self, id: SuggestId) -> Option<&mut StoredSuggestion> {
        self.suggestions
            .get_mut(&id.index())
            .filter(|sug| sug.generation == id.generation() && !sug.closed)
    }

    /// Remove all suggestions for a deleted symbol
    pub fn remove_for_symbol(&mut self, symbol: &SymbolId) {
        if let Some(indices) = self.symbol_to_suggests.remove(symbol) {
            for index in indices {
                if let Some(removed) = self.suggestions.remove(&index) {
                    let dedup_key = (removed.suggest_idx, removed.opportunity.id);
                    self.dedup_index.remove(&dedup_key);
                }
            }
        }
    }

    /// Invalidate (bump generation) for all suggestions targeting a modified symbol
    pub fn invalidate_for_symbol(&mut self, symbol: &SymbolId) {
        if let Some(indices) = self.symbol_to_suggests.get(symbol) {
            for &index in indices {
                if let Some(sug) = self.suggestions.get_mut(&index) {
                    sug.bump_generation();
                }
            }
        }
    }

    /// Check if a suggestion ID is still valid
    pub fn is_valid(&self, id: SuggestId) -> bool {
        self.get(id).is_some()
    }

    /// Get the current generation for a suggestion ID's index
    pub fn current_generation(&self, id: SuggestId) -> Option<u32> {
        self.suggestions.get(&id.index()).map(|s| s.generation)
    }

    /// Mark a suggestion as closed
    pub fn close(&mut self, id: SuggestId, reason: impl Into<String>) -> bool {
        if let Some(sug) = self.get_mut(id) {
            sug.close(reason);
            true
        } else {
            false
        }
    }

    /// Iterate over all active suggestions
    pub fn iter(&self) -> impl Iterator<Item = (SuggestId, &StoredSuggestion)> {
        self.suggestions
            .iter()
            .filter(|(_, s)| !s.closed)
            .map(|(&index, sug)| (SuggestId::new(index, sug.generation), sug))
    }

    /// Count active (non-closed) suggestions
    pub fn len(&self) -> usize {
        self.suggestions.iter().filter(|(_, s)| !s.closed).count()
    }

    /// Check if store is empty
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Total number of suggestions (including closed)
    pub fn total_count(&self) -> usize {
        self.suggestions.len()
    }

    /// Clear all suggestions
    pub fn clear(&mut self) {
        self.suggestions.clear();
        self.symbol_to_suggests.clear();
        self.dedup_index.clear();
        self.next_index = 1;
    }
}

/// GC configuration for SuggestStore
#[derive(Debug, Clone)]
pub struct GcConfig {
    /// How long to keep closed suggestions
    pub max_closed_age: std::time::Duration,

    /// Maximum number of suggestions before triggering GC
    pub max_suggestions: usize,

    /// GC interval
    pub gc_interval: std::time::Duration,
}

impl Default for GcConfig {
    fn default() -> Self {
        Self {
            max_closed_age: std::time::Duration::from_secs(300), // 5 minutes
            max_suggestions: 1000,
            gc_interval: std::time::Duration::from_secs(60), // 1 minute
        }
    }
}

impl SuggestStore {
    /// Garbage collect old/stale suggestions
    ///
    /// Removes:
    /// - Closed suggestions older than max_closed_age
    /// - Suggestions with all targets removed
    pub fn gc(&mut self, config: &GcConfig, valid_symbols: &impl Fn(&SymbolId) -> bool) {
        let now = Instant::now();
        let mut to_remove = Vec::new();

        for (&index, sug) in self.suggestions.iter() {
            // Remove old closed suggestions
            if sug.closed {
                if let Some(closed_at) = sug.closed_at {
                    if now.duration_since(closed_at) > config.max_closed_age {
                        to_remove.push(index);
                        continue;
                    }
                }
            }

            // Remove suggestions where all targets are invalid
            let any_valid = sug.opportunity.targets.iter().any(valid_symbols);
            if !any_valid {
                to_remove.push(index);
            }
        }

        // Remove and clean up mappings
        for index in to_remove {
            if let Some(sug) = self.suggestions.remove(&index) {
                let dedup_key = (sug.suggest_idx, sug.opportunity.id);
                self.dedup_index.remove(&dedup_key);
                for target in &sug.opportunity.targets {
                    if let Some(indices) = self.symbol_to_suggests.get_mut(target) {
                        indices.retain(|&i| i != index);
                    }
                }
            }
        }
    }
}

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

    fn make_opportunity(id: u32, targets: Vec<SymbolId>) -> SuggestOpportunity {
        SuggestOpportunity::new(
            OpportunityId::new(id),
            targets,
            SuggestLocation::for_test("test.rs", "Test"),
            "Test suggestion",
            0.9,
            OpportunityContext::Derive {
                derive_name: "Default".into(),
                missing_impls: vec![],
            },
        )
    }

    #[test]
    fn test_suggest_id_format() {
        let id = SuggestId::new(1, 0);
        assert_eq!(id.to_string(), "S001g0");

        let id2 = SuggestId::new(42, 3);
        assert_eq!(id2.to_string(), "S042g3");
    }

    #[test]
    fn test_suggest_id_parse() {
        let id: SuggestId = "S001g0".parse().unwrap();
        assert_eq!(id.index(), 1);
        assert_eq!(id.generation(), 0);

        let id2: SuggestId = "S042g3".parse().unwrap();
        assert_eq!(id2.index(), 42);
        assert_eq!(id2.generation(), 3);
    }

    #[test]
    fn test_store_insert_and_get() {
        let mut store = SuggestStore::new();
        let sym = SymbolId::parse("100v1").unwrap();
        let opp = make_opportunity(1, vec![sym]);
        let sug = StoredSuggestion::new(opp, SuggestIndex(0), SafetyLevel::Auto, 1.0);

        let id = store.insert(sug).expect("first insert should succeed");
        assert_eq!(id.index(), 1);
        assert_eq!(id.generation(), 0);

        let retrieved = store.get(id).unwrap();
        assert_eq!(retrieved.safety, SafetyLevel::Auto);
    }

    #[test]
    fn test_store_invalidation() {
        let mut store = SuggestStore::new();
        let sym = SymbolId::parse("100v1").unwrap();
        let opp = make_opportunity(1, vec![sym]);
        let sug = StoredSuggestion::new(opp, SuggestIndex(0), SafetyLevel::Auto, 1.0);

        let id = store.insert(sug).expect("insert should succeed");
        assert!(store.is_valid(id));

        // Invalidate
        store.invalidate_for_symbol(&sym);

        // Old ID is now invalid
        assert!(!store.is_valid(id));

        // New generation exists
        let new_gen = store.current_generation(id).unwrap();
        assert_eq!(new_gen, 1);
    }

    #[test]
    fn test_store_close() {
        let mut store = SuggestStore::new();
        let sym = SymbolId::parse("100v1").unwrap();
        let opp = make_opportunity(1, vec![sym]);
        let sug = StoredSuggestion::new(opp, SuggestIndex(0), SafetyLevel::Auto, 1.0);

        let id = store.insert(sug).expect("insert should succeed");
        assert!(store.is_valid(id));
        assert_eq!(store.len(), 1);

        store.close(id, "Applied");
        assert!(!store.is_valid(id));
        assert_eq!(store.len(), 0);
        assert_eq!(store.total_count(), 1); // Still stored for audit
    }

    #[test]
    fn test_store_remove_for_symbol() {
        let mut store = SuggestStore::new();
        let sym1 = SymbolId::parse("100v1").unwrap();
        let sym2 = SymbolId::parse("200v1").unwrap();

        let opp1 = make_opportunity(1, vec![sym1]);
        let opp2 = make_opportunity(2, vec![sym2]);

        let sug1 = StoredSuggestion::new(opp1, SuggestIndex(0), SafetyLevel::Auto, 1.0);
        let sug2 = StoredSuggestion::new(opp2, SuggestIndex(0), SafetyLevel::Auto, 1.0);

        let id1 = store.insert(sug1).expect("insert sug1");
        let id2 = store.insert(sug2).expect("insert sug2");

        assert_eq!(store.len(), 2);

        store.remove_for_symbol(&sym1);

        assert!(!store.is_valid(id1));
        assert!(store.is_valid(id2));
        assert_eq!(store.len(), 1);
    }

    #[test]
    fn test_store_iter() {
        let mut store = SuggestStore::new();
        let sym = SymbolId::parse("100v1").unwrap();

        for i in 0..5 {
            let opp = make_opportunity(i, vec![sym]);
            let sug = StoredSuggestion::new(opp, SuggestIndex(0), SafetyLevel::Auto, 1.0);
            store.insert(sug);
        }

        let ids: Vec<_> = store.iter().map(|(id, _)| id).collect();
        assert_eq!(ids.len(), 5);
    }
}