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
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
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
//! SuggestService - ReadOnly interface for concurrent access
//!
//! Provides thread-safe access to suggestions for LLM and UI queries.
//! Uses parking_lot::RwLock for concurrent read access with exclusive writes.

use parking_lot::{MappedRwLockReadGuard, RwLock, RwLockReadGuard};
use rayon::prelude::*;

use ryo_analysis::context::AnalysisContext;
use ryo_analysis::SymbolId;

use crate::allow::AllowStore;
use crate::id::SuggestId;
use crate::store::{GcConfig, StoredSuggestion, SuggestIndex, SuggestStore};
use crate::suggest::{
    LintSeverity, MutationSpec, ParamDef, SafetyLevel, SuggestCategory, SuggestOpportunity,
    SuggestParams, SymbolScope,
};
use crate::suggest_registry::SuggestRegistry;
use crate::trigger::{AcChanges, PendingChanges, SuggestStrategy, SuggestTrigger};

/// Information about a parameterized suggestion.
///
/// Used by LLMs to discover available generation patterns
/// and their parameter schemas.
#[derive(Debug, Clone)]
pub struct ParameterizedSuggestInfo {
    /// Suggestion name (rule ID)
    pub name: &'static str,
    /// Human-readable description
    pub description: String,
    /// Category for filtering
    pub category: SuggestCategory,
    /// Parameter schema
    pub param_schema: Vec<ParamDef>,
}

/// Query filter for suggestions
#[derive(Debug, Clone, Default)]
pub struct SuggestQuery {
    /// Filter by category
    pub category: Option<SuggestCategory>,

    /// Filter by safety level (max level to include)
    pub max_safety: Option<SafetyLevel>,

    /// Filter by minimum confidence
    pub min_confidence: Option<f32>,

    /// Filter by target symbols (any of these)
    pub target_symbols: Option<Vec<SymbolId>>,

    /// Limit results
    pub limit: Option<usize>,
}

impl SuggestQuery {
    /// Create an empty query (matches all)
    pub fn all() -> Self {
        Self::default()
    }

    /// Filter by category
    pub fn with_category(mut self, category: SuggestCategory) -> Self {
        self.category = Some(category);
        self
    }

    /// Filter by maximum safety level
    pub fn with_max_safety(mut self, safety: SafetyLevel) -> Self {
        self.max_safety = Some(safety);
        self
    }

    /// Filter by minimum confidence
    pub fn with_min_confidence(mut self, confidence: f32) -> Self {
        self.min_confidence = Some(confidence);
        self
    }

    /// Filter by target symbols
    pub fn with_targets(mut self, symbols: Vec<SymbolId>) -> Self {
        self.target_symbols = Some(symbols);
        self
    }

    /// Limit number of results
    pub fn with_limit(mut self, limit: usize) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Check if a suggestion matches this query
    fn matches(&self, stored: &StoredSuggestion, registry: &SuggestRegistry) -> bool {
        // Category filter
        if let Some(cat) = self.category {
            if let Some(suggest) = registry.get(stored.suggest_idx) {
                if suggest.category() != cat {
                    return false;
                }
            }
        }

        // Safety filter
        if let Some(max_safety) = self.max_safety {
            if stored.safety > max_safety {
                return false;
            }
        }

        // Confidence filter
        if let Some(min_conf) = self.min_confidence {
            if stored.opportunity.confidence < min_conf {
                return false;
            }
        }

        // Target symbol filter
        if let Some(ref targets) = self.target_symbols {
            let has_match = stored
                .opportunity
                .targets
                .iter()
                .any(|t| targets.contains(t));
            if !has_match {
                return false;
            }
        }

        true
    }
}

/// View of a suggestion returned by queries
#[derive(Debug)]
pub struct SuggestView<'a> {
    /// The suggestion ID
    pub id: SuggestId,

    /// The stored suggestion data
    pub stored: &'a StoredSuggestion,

    /// Pattern name
    pub pattern_name: &'static str,

    /// Pattern category
    pub category: SuggestCategory,
}

/// Thread-safe service for accessing suggestions
///
/// Provides read-only queries for LLM and UI consumers.
/// Write operations go through SuggestEngine (not this service).
pub struct SuggestService {
    /// Thread-safe store access
    store: RwLock<SuggestStore>,

    /// Pattern registry (immutable after initialization)
    registry: SuggestRegistry,

    /// Evaluation strategy
    strategy: SuggestStrategy,

    /// Pending changes tracker
    pending: RwLock<PendingChanges>,

    /// GC configuration
    gc_config: GcConfig,
}

impl SuggestService {
    /// Create a new service with the given registry
    pub fn new(registry: SuggestRegistry) -> Self {
        Self {
            store: RwLock::new(SuggestStore::new()),
            registry,
            strategy: SuggestStrategy::default(),
            pending: RwLock::new(PendingChanges::new()),
            gc_config: GcConfig::default(),
        }
    }

    /// Create a service with custom strategy
    pub fn with_strategy(registry: SuggestRegistry, strategy: SuggestStrategy) -> Self {
        Self {
            store: RwLock::new(SuggestStore::new()),
            registry,
            strategy,
            pending: RwLock::new(PendingChanges::new()),
            gc_config: GcConfig::default(),
        }
    }

    /// Create a service with custom GC configuration
    pub fn with_gc_config(registry: SuggestRegistry, gc_config: GcConfig) -> Self {
        Self {
            store: RwLock::new(SuggestStore::new()),
            registry,
            strategy: SuggestStrategy::default(),
            pending: RwLock::new(PendingChanges::new()),
            gc_config,
        }
    }

    // ========== Read Operations (concurrent safe) ==========

    /// Get a suggestion by ID
    ///
    /// Returns a mapped guard that holds the read lock while providing
    /// access to the stored suggestion.
    pub fn get(&self, id: SuggestId) -> Option<MappedRwLockReadGuard<'_, StoredSuggestion>> {
        let guard = self.store.read();
        RwLockReadGuard::try_map(guard, |store| store.get(id)).ok()
    }

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

    /// Query suggestions with filter
    pub fn query(&self, query: &SuggestQuery) -> Vec<(SuggestId, SuggestCategory, SafetyLevel)> {
        let store = self.store.read();

        let mut results: Vec<_> = store
            .iter()
            .filter(|(_, stored)| query.matches(stored, &self.registry))
            .map(|(id, stored)| {
                let category = self
                    .registry
                    .get(stored.suggest_idx)
                    .map(|s| s.category())
                    .unwrap_or(SuggestCategory::Refactor);
                (id, category, stored.safety)
            })
            .collect();

        // Apply limit
        if let Some(limit) = query.limit {
            results.truncate(limit);
        }

        results
    }

    /// Get all suggestions for auto-application (safety=Auto)
    pub fn auto_applicable(&self) -> Vec<SuggestId> {
        self.query(&SuggestQuery::all().with_max_safety(SafetyLevel::Auto))
            .into_iter()
            .map(|(id, _, _)| id)
            .collect()
    }

    /// Get suggestions by category
    pub fn by_category(&self, category: SuggestCategory) -> Vec<SuggestId> {
        self.query(&SuggestQuery::all().with_category(category))
            .into_iter()
            .map(|(id, _, _)| id)
            .collect()
    }

    /// Get suggestion count
    pub fn count(&self) -> usize {
        self.store.read().len()
    }

    /// Check if there are any suggestions
    pub fn is_empty(&self) -> bool {
        self.count() == 0
    }

    /// Get pattern names for a suggestion
    pub fn pattern_name(&self, id: SuggestId) -> Option<&'static str> {
        let store = self.store.read();
        let stored = store.get(id)?;
        self.registry.get(stored.suggest_idx).map(|s| s.name())
    }

    /// Get rule ID for a suggestion (e.g., "RL021").
    /// Returns None for non-pattern-based suggestions.
    pub fn rule_id(&self, id: SuggestId) -> Option<&str> {
        let store = self.store.read();
        let stored = store.get(id)?;
        self.registry
            .get(stored.suggest_idx)
            .and_then(|s| s.rule_id())
    }

    /// Get registry access (for pattern lookup)
    pub fn registry(&self) -> &SuggestRegistry {
        &self.registry
    }

    // ========== MutationSpec Generation ==========

    /// Generate MutationSpecs for a suggestion
    ///
    /// Takes AnalysisContext to resolve types and generate accurate specs.
    pub fn to_mutation_specs(
        &self,
        id: SuggestId,
        ctx: &AnalysisContext,
    ) -> Option<Vec<MutationSpec>> {
        let store = self.store.read();
        let stored = store.get(id)?;
        let suggest = self.registry.get(stored.suggest_idx)?;

        suggest.to_mutation_specs(ctx, &stored.opportunity).ok()
    }

    // ========== Parameterized Generation ==========

    /// Generate suggestions with external parameters.
    ///
    /// This method enables code generation from patterns with user-provided
    /// parameters. For example, generating `OrderAPI` from an API pattern
    /// with `{ "name": "Order" }`.
    ///
    /// # Arguments
    /// * `ctx` - Analysis context for code graph queries
    /// * `rule_id` - Rule ID of the parameterized suggestion (e.g., "api-pattern")
    /// * `params` - User-provided parameters (e.g., `{ "name": "Order" }`)
    ///
    /// # Returns
    /// * `Some(opportunities)` - Generated opportunities if rule exists and accepts params
    /// * `None` - If rule not found or doesn't accept params
    ///
    /// # Example
    /// ```ignore
    /// let params = [("name".to_string(), "Order".to_string())].into_iter().collect();
    /// let opps = service.generate_with_params(&ctx, "api-pattern", &params);
    /// ```
    pub fn generate_with_params(
        &self,
        ctx: &AnalysisContext,
        rule_id: &str,
        params: &SuggestParams,
    ) -> Option<Vec<SuggestOpportunity>> {
        let (_, suggest) = self.registry.get_by_name(rule_id)?;

        if !suggest.accepts_params() {
            return None;
        }

        Some(suggest.detect_with_params(ctx, &[], params))
    }

    /// Generate suggestions and store them.
    ///
    /// Like `generate_with_params`, but also stores the generated opportunities
    /// in the service for later retrieval and application.
    ///
    /// Returns the number of suggestions stored.
    pub fn generate_and_store(
        &self,
        ctx: &AnalysisContext,
        rule_id: &str,
        params: &SuggestParams,
    ) -> usize {
        let Some((idx, suggest)) = self.registry.get_by_name(rule_id) else {
            return 0;
        };

        if !suggest.accepts_params() {
            return 0;
        }

        let opportunities = suggest.detect_with_params(ctx, &[], params);
        let mut count = 0;

        for opportunity in opportunities {
            let stored = StoredSuggestion::new(
                opportunity,
                idx,
                suggest.safety_level(),
                suggest.priority_weight(),
            );
            if self.insert(stored).is_some() {
                count += 1;
            }
        }

        count
    }

    /// List all parameterized suggestions with their schemas.
    ///
    /// Returns suggestions that accept external parameters, along with
    /// their parameter schemas. Useful for LLMs to discover available
    /// generation patterns.
    pub fn list_parameterized(&self) -> Vec<ParameterizedSuggestInfo> {
        self.registry
            .iter()
            .filter_map(|(_, suggest)| {
                if suggest.accepts_params() {
                    Some(ParameterizedSuggestInfo {
                        name: suggest.name(),
                        description: suggest.description().to_string(),
                        category: suggest.category(),
                        param_schema: suggest.param_schema(),
                    })
                } else {
                    None
                }
            })
            .collect()
    }

    // ========== Write Operations (exclusive access) ==========

    /// Record changes and check if evaluation should trigger
    pub fn record_changes(&self, trigger: SuggestTrigger) -> bool {
        let mut pending = self.pending.write();

        // Accumulate changes
        if let Some(changes) = trigger.changes() {
            pending.record_goal(changes.clone());
        }

        // Check if we should evaluate
        self.strategy.should_evaluate(&trigger, &pending)
    }

    /// Take pending changes (for evaluation)
    pub fn take_pending(&self) -> (usize, AcChanges) {
        self.pending.write().take()
    }

    /// Insert a new suggestion (write operation).
    ///
    /// Returns `None` if an active suggestion with the same identity
    /// (pattern + opportunity_id) already exists.
    pub fn insert(&self, suggestion: StoredSuggestion) -> Option<SuggestId> {
        self.store.write().insert(suggestion)
    }

    /// Close a suggestion (write operation)
    pub fn close(&self, id: SuggestId, reason: impl Into<String>) -> bool {
        self.store.write().close(id, reason)
    }

    /// Invalidate suggestions for a modified symbol
    pub fn invalidate_for_symbol(&self, symbol: &SymbolId) {
        self.store.write().invalidate_for_symbol(symbol);
    }

    /// Remove suggestions for a deleted symbol
    pub fn remove_for_symbol(&self, symbol: &SymbolId) {
        self.store.write().remove_for_symbol(symbol);
    }

    /// Run garbage collection
    pub fn gc(&self, valid_symbols: impl Fn(&SymbolId) -> bool) {
        self.store.write().gc(&self.gc_config, &valid_symbols);
    }

    /// Clear all suggestions
    pub fn clear(&self) {
        self.store.write().clear();
    }

    // ========== Detection (batch operation) ==========

    /// Detect suggestions for given symbols using registered patterns.
    ///
    /// This is the main entry point for suggestion detection.
    /// Automatically filters out suggestions for symbols with `@spec:allow(...)` directives.
    ///
    /// Returns the number of new suggestions found.
    pub fn detect(&self, ctx: &AnalysisContext, symbols: &[SymbolId]) -> usize {
        // Build allow store from context (extracts @spec:allow directives)
        let allow_store = AllowStore::from_context(ctx);
        self.detect_with_allow(ctx, symbols, &allow_store)
    }

    /// Detect suggestions with custom AllowStore.
    ///
    /// Use this when you want to reuse an AllowStore across multiple detect calls
    /// or when you have a pre-built AllowStore.
    pub fn detect_with_allow(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
    ) -> usize {
        let mut count = 0;

        for (idx, suggest) in self.registry.iter() {
            let rule_id = suggest.rule_id();
            let opportunities = suggest.detect(ctx, symbols);

            for opportunity in opportunities {
                // Check if this opportunity should be skipped due to @spec:allow
                if let Some(rule_id) = rule_id {
                    if allow_store.is_allowed_for_symbols(ctx, &opportunity.targets, rule_id) {
                        continue; // Skip allowed suggestions
                    }
                }

                let stored = StoredSuggestion::new(
                    opportunity,
                    idx,
                    suggest.safety_level(),
                    suggest.priority_weight(),
                );
                if self.insert(stored).is_some() {
                    count += 1;
                }
            }
        }

        count
    }

    /// Detect suggestions with rule filter.
    ///
    /// The `is_rule_enabled` closure takes (rule_id, file_path) to check if a rule should be processed.
    /// Rules returning `false` are skipped. This enables project and module-level rule configuration.
    pub fn detect_with_rule_filter<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        is_rule_enabled: F,
    ) -> usize
    where
        F: Fn(&str, &str) -> bool,
    {
        let allow_store = AllowStore::from_context(ctx);
        self.detect_with_allow_and_rule_filter(ctx, symbols, &allow_store, is_rule_enabled)
    }

    /// Detect suggestions with custom AllowStore and rule filter.
    ///
    /// Combines symbol-level allow directives with project/module-level rule filtering.
    /// The `is_rule_enabled` closure takes (rule_id, file_path) to support module configs.
    pub fn detect_with_allow_and_rule_filter<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
        is_rule_enabled: F,
    ) -> usize
    where
        F: Fn(&str, &str) -> bool,
    {
        self.detect_with_config(ctx, symbols, allow_store, is_rule_enabled, |_| None)
    }

    /// Detect suggestions with full configuration support.
    ///
    /// This is the most complete variant that supports:
    /// - Custom AllowStore for symbol-level @spec:allow directives
    /// - Rule filter closure for project-level rule configuration
    /// - Severity override closure for per-rule severity changes
    ///
    /// The `severity_override` closure takes a rule_id and returns an optional
    /// new severity. If None, the default severity is used.
    ///
    /// The `is_rule_enabled` closure takes (rule_id, file_path) to support
    /// module-level rule configuration.
    pub fn detect_with_config<F, S>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
        is_rule_enabled: F,
        severity_override: S,
    ) -> usize
    where
        F: Fn(&str, &str) -> bool,
        S: Fn(&str) -> Option<LintSeverity>,
    {
        self.detect_with_config_and_scope(
            ctx,
            symbols,
            allow_store,
            is_rule_enabled,
            severity_override,
            &[],
        )
    }

    /// Detect suggestions with full configuration and scope filtering.
    ///
    /// Extends `detect_with_config` with scope-based filtering.
    /// Each opportunity is tagged with its `SymbolScope` (Lib/Bin/Test)
    /// based on symbol context. If `scope_filter` is non-empty, only
    /// opportunities matching one of the specified scopes are stored.
    pub fn detect_with_config_and_scope<F, S>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
        is_rule_enabled: F,
        severity_override: S,
        scope_filter: &[SymbolScope],
    ) -> usize
    where
        F: Fn(&str, &str) -> bool,
        S: Fn(&str) -> Option<LintSeverity>,
    {
        let mut count = 0;

        // Pre-compute binary crate names once for scope resolution
        let binary_crates = SymbolScope::binary_crate_names(ctx);

        for (idx, suggest) in self.registry.iter() {
            let rule_id = suggest.rule_id();

            let opportunities = suggest.detect(ctx, symbols);

            for opportunity in opportunities {
                // Check module-level and project-level rule filter
                if let Some(rule_id) = rule_id {
                    let file_path = &opportunity.location.file;
                    if !is_rule_enabled(rule_id, file_path) {
                        continue;
                    }
                }

                // Check symbol-level @spec:allow
                if let Some(rule_id) = rule_id {
                    if allow_store.is_allowed_for_symbols(ctx, &opportunity.targets, rule_id) {
                        continue;
                    }
                }

                // Resolve scope from primary target symbol
                let scope = opportunity
                    .primary_target()
                    .map(|sid| SymbolScope::resolve(ctx, sid, &binary_crates))
                    .unwrap_or_default();

                // Apply CLI scope filter (empty = allow all)
                if !scope_filter.is_empty() && !scope_filter.contains(&scope) {
                    continue;
                }

                // Apply suggest-level scope constraint (e.g., Safety rules → lib+bin only)
                let target_scopes = suggest.target_scopes();
                if !target_scopes.is_empty() && !target_scopes.contains(&scope) {
                    continue;
                }

                // Tag opportunity with resolved scope
                let opportunity = opportunity.with_scope(scope);

                // Apply severity override if configured
                let opportunity = if let Some(rule_id) = rule_id {
                    if let Some(new_severity) = severity_override(rule_id) {
                        opportunity.with_severity_override(new_severity)
                    } else {
                        opportunity
                    }
                } else {
                    opportunity
                };

                // Determine safety level:
                // - For Lint context, use lint_severity (which may be overridden)
                // - For other contexts, use the pattern's default safety_level
                let safety = opportunity
                    .lint_severity()
                    .map(SafetyLevel::from)
                    .unwrap_or_else(|| suggest.safety_level());

                let stored =
                    StoredSuggestion::new(opportunity, idx, safety, suggest.priority_weight());
                if self.insert(stored).is_some() {
                    count += 1;
                }
            }
        }

        count
    }

    /// Detect suggestions for specific patterns only.
    ///
    /// Automatically filters out suggestions for symbols with `@spec:allow(...)` directives.
    pub fn detect_patterns(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        pattern_names: &[&str],
    ) -> usize {
        let allow_store = AllowStore::from_context(ctx);
        self.detect_patterns_with_allow(ctx, symbols, pattern_names, &allow_store)
    }

    /// Detect suggestions for specific patterns with custom AllowStore.
    pub fn detect_patterns_with_allow(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        pattern_names: &[&str],
        allow_store: &AllowStore,
    ) -> usize {
        let mut count = 0;

        for name in pattern_names {
            if let Some((idx, suggest)) = self.registry.get_by_name(name) {
                let rule_id = suggest.rule_id();
                let opportunities = suggest.detect(ctx, symbols);

                for opportunity in opportunities {
                    // Check if this opportunity should be skipped due to @spec:allow
                    if let Some(rule_id) = rule_id {
                        if allow_store.is_allowed_for_symbols(ctx, &opportunity.targets, rule_id) {
                            continue;
                        }
                    }

                    let stored = StoredSuggestion::new(
                        opportunity,
                        idx,
                        suggest.safety_level(),
                        suggest.priority_weight(),
                    );
                    if self.insert(stored).is_some() {
                        count += 1;
                    }
                }
            }
        }

        count
    }

    /// Detect suggestions with pre-check filter.
    ///
    /// The `precheck` callback is called for each opportunity with:
    /// - The opportunity itself
    /// - The generated MutationSpecs
    ///
    /// Only opportunities where `precheck` returns `true` are stored.
    /// This enables scan-time verification to ensure Apply will succeed.
    ///
    /// # Example
    ///
    /// ```ignore
    /// let count = service.detect_with_precheck(ctx, symbols, |opp, specs, ctx| {
    ///     // Run GraphVerifier on specs
    ///     verify_specs(specs, ctx)
    /// });
    /// ```
    pub fn detect_with_precheck<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool,
    {
        let allow_store = AllowStore::from_context(ctx);
        self.detect_with_precheck_and_allow(ctx, symbols, &allow_store, precheck)
    }

    /// Detect suggestions with pre-check filter and custom AllowStore.
    pub fn detect_with_precheck_and_allow<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool,
    {
        let mut result = DetectWithPrecheckResult::default();

        for (idx, suggest) in self.registry.iter() {
            let rule_id = suggest.rule_id();
            let opportunities = suggest.detect(ctx, symbols);

            for opportunity in opportunities {
                // Check if this opportunity should be skipped due to @spec:allow
                if let Some(rule_id) = rule_id {
                    if allow_store.is_allowed_for_symbols(ctx, &opportunity.targets, rule_id) {
                        continue; // Skip allowed suggestions
                    }
                }

                // Generate MutationSpecs for pre-check
                let specs = match suggest.to_mutation_specs(ctx, &opportunity) {
                    Ok(s) => s,
                    Err(_) => {
                        result.skipped_no_specs += 1;
                        continue;
                    }
                };

                if specs.is_empty() {
                    result.skipped_no_specs += 1;
                    continue;
                }

                // Run pre-check
                if precheck(&opportunity, &specs, ctx) {
                    let stored = StoredSuggestion::new(
                        opportunity,
                        idx,
                        suggest.safety_level(),
                        suggest.priority_weight(),
                    );
                    if self.insert(stored).is_some() {
                        result.passed += 1;
                    }
                } else {
                    result.failed_precheck += 1;
                }
            }
        }

        result
    }

    /// Detect suggestions with parallel pre-check execution.
    ///
    /// This method parallelizes the expensive precheck phase using rayon:
    /// 1. Phase 1 (sequential): Detect all opportunities and generate specs
    /// 2. Phase 2 (parallel): Run precheck on each candidate
    /// 3. Phase 3 (sequential): Insert passed suggestions
    ///
    /// This significantly reduces wall-clock time when precheck involves
    /// expensive operations like fork_clone() (~100ms each).
    ///
    /// # Example
    ///
    /// ```ignore
    /// let result = service.detect_with_parallel_precheck(ctx, symbols, |opp, specs, ctx| {
    ///     // This closure runs in parallel - must be Sync
    ///     let mut forked = ctx.fork_clone();
    ///     executor.execute_v2(&blueprint, &mut forked).success
    /// });
    /// ```
    pub fn detect_with_parallel_precheck<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool + Sync,
    {
        self.detect_with_parallel_precheck_limited(ctx, symbols, None, precheck)
    }

    /// Detect suggestions with parallel pre-check and optional limit.
    ///
    /// When `limit` is Some(N), only the top N candidates by priority are checked.
    /// Candidates are sorted by priority (confidence * safety_weight) before precheck.
    pub fn detect_with_parallel_precheck_limited<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        limit: Option<usize>,
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool + Sync,
    {
        let allow_store = AllowStore::from_context(ctx);
        self.detect_with_parallel_precheck_and_allow_limited(
            ctx,
            symbols,
            &allow_store,
            limit,
            precheck,
        )
    }

    /// Detect suggestions with parallel pre-check, custom AllowStore, and optional limit.
    pub fn detect_with_parallel_precheck_and_allow<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool + Sync,
    {
        self.detect_with_parallel_precheck_and_allow_limited(
            ctx,
            symbols,
            allow_store,
            None,
            precheck,
        )
    }

    /// Detect suggestions with parallel pre-check, custom AllowStore, and optional limit.
    pub fn detect_with_parallel_precheck_and_allow_limited<F>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
        limit: Option<usize>,
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool + Sync,
    {
        self.detect_with_parallel_precheck_full(
            ctx,
            symbols,
            allow_store,
            limit,
            |_| true,
            precheck,
        )
    }

    /// Detect suggestions with parallel pre-check, rule filter, and optional limit.
    ///
    /// This is the most complete variant that supports:
    /// - Custom AllowStore for symbol-level @spec:allow directives
    /// - Rule filter closure for project-level rule configuration
    /// - Optional limit on candidates to check
    /// - Parallel precheck execution
    pub fn detect_with_parallel_precheck_and_rule_filter<F, R>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        limit: Option<usize>,
        is_rule_enabled: R,
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool + Sync,
        R: Fn(&str) -> bool,
    {
        let allow_store = AllowStore::from_context(ctx);
        self.detect_with_parallel_precheck_full(
            ctx,
            symbols,
            &allow_store,
            limit,
            is_rule_enabled,
            precheck,
        )
    }

    /// Full-featured parallel precheck detection with all options.
    ///
    /// This is the internal implementation that other parallel precheck methods delegate to.
    pub fn detect_with_parallel_precheck_full<F, R>(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        allow_store: &AllowStore,
        limit: Option<usize>,
        is_rule_enabled: R,
        precheck: F,
    ) -> DetectWithPrecheckResult
    where
        F: Fn(&SuggestOpportunity, &[MutationSpec], &AnalysisContext) -> bool + Sync,
        R: Fn(&str) -> bool,
    {
        // Phase 1: Collect all candidates (sequential, lightweight)
        // Each candidate contains: (opportunity, specs, suggest_idx, safety_level, priority)
        let mut candidates: Vec<(
            SuggestOpportunity,
            Vec<MutationSpec>,
            SuggestIndex,
            SafetyLevel,
            u8,
        )> = Vec::new();
        let mut skipped_no_specs = 0;

        for (idx, suggest) in self.registry.iter() {
            let rule_id = suggest.rule_id();

            // Check project-level rule filter first (skip entire pattern if disabled)
            if let Some(rule_id) = rule_id {
                if !is_rule_enabled(rule_id) {
                    continue;
                }
            }

            let opportunities = suggest.detect(ctx, symbols);

            for opportunity in opportunities {
                // Check symbol-level @spec:allow
                if let Some(rule_id) = rule_id {
                    if allow_store.is_allowed_for_symbols(ctx, &opportunity.targets, rule_id) {
                        continue;
                    }
                }

                // Generate MutationSpecs
                let specs = match suggest.to_mutation_specs(ctx, &opportunity) {
                    Ok(s) => s,
                    Err(_) => {
                        skipped_no_specs += 1;
                        continue;
                    }
                };

                if specs.is_empty() {
                    skipped_no_specs += 1;
                    continue;
                }

                let safety = suggest.safety_level();
                let priority = crate::suggest::compute_priority(
                    opportunity.confidence,
                    safety,
                    suggest.priority_weight(),
                );
                candidates.push((opportunity, specs, idx, safety, priority));
            }
        }

        // Phase 1.5: Sort by priority (descending) and limit if requested
        candidates.sort_by_key(|b| std::cmp::Reverse(b.4)); // Higher priority first
        let total_candidates = candidates.len();
        let skipped_by_limit = if let Some(limit) = limit {
            if candidates.len() > limit {
                let skipped = candidates.len() - limit;
                candidates.truncate(limit);
                skipped
            } else {
                0
            }
        } else {
            0
        };

        // Phase 2: Run precheck in parallel (expensive, CPU-bound)
        // Each task gets its own forked context via the precheck closure
        let precheck_results: Vec<Option<StoredSuggestion>> = candidates
            .into_par_iter()
            .map(|(opportunity, specs, suggest_idx, safety, priority)| {
                if precheck(&opportunity, &specs, ctx) {
                    let mut stored = StoredSuggestion::new_with_priority(
                        opportunity,
                        suggest_idx,
                        safety,
                        priority,
                    );
                    stored.precheck_status = crate::store::PrecheckStatus::Passed;
                    Some(stored)
                } else {
                    None
                }
            })
            .collect();

        // Phase 3: Insert passed suggestions (sequential, needs write lock)
        let mut passed = 0;
        let mut failed_precheck = 0;

        for result in precheck_results {
            match result {
                Some(stored) => {
                    if self.insert(stored).is_some() {
                        passed += 1;
                    }
                }
                None => {
                    failed_precheck += 1;
                }
            }
        }

        DetectWithPrecheckResult {
            passed,
            failed_precheck,
            skipped_no_specs,
            skipped_by_limit,
            total_candidates,
        }
    }
}

/// Result of detection with pre-check.
#[derive(Debug, Clone, Default)]
pub struct DetectWithPrecheckResult {
    /// Number of suggestions that passed pre-check and were stored
    pub passed: usize,
    /// Number of suggestions that failed pre-check
    pub failed_precheck: usize,
    /// Number of suggestions skipped due to no MutationSpecs generated
    pub skipped_no_specs: usize,
    /// Number of suggestions skipped due to limit
    pub skipped_by_limit: usize,
    /// Total candidates before limiting (for logging)
    pub total_candidates: usize,
}

impl DetectWithPrecheckResult {
    /// Total suggestions detected (before pre-check filtering)
    pub fn total_detected(&self) -> usize {
        self.passed + self.failed_precheck + self.skipped_no_specs
    }

    /// Number of suggestions that were prechecked
    pub fn prechecked(&self) -> usize {
        self.passed + self.failed_precheck
    }
}

/// Statistics about service state
#[derive(Debug, Clone, Default)]
pub struct SuggestStats {
    /// Total active suggestions
    pub active_count: usize,

    /// Suggestions by category
    pub by_category: std::collections::HashMap<SuggestCategory, usize>,

    /// Suggestions by safety level
    pub by_safety: std::collections::HashMap<SafetyLevel, usize>,

    /// Number of registered patterns
    pub pattern_count: usize,
}

impl SuggestService {
    /// Get statistics about current state
    pub fn stats(&self) -> SuggestStats {
        let mut stats = SuggestStats {
            pattern_count: self.registry.len(),
            ..SuggestStats::default()
        };

        let store = self.store.read();

        for (_, stored) in store.iter() {
            stats.active_count += 1;

            // Count by category
            if let Some(suggest) = self.registry.get(stored.suggest_idx) {
                *stats.by_category.entry(suggest.category()).or_default() += 1;
            }

            // Count by safety
            *stats.by_safety.entry(stored.safety).or_default() += 1;
        }

        stats
    }

    /// Take the store contents, leaving an empty store.
    ///
    /// Used for preserving suggestions across API reload.
    pub fn take_store(&self) -> SuggestStore {
        std::mem::take(&mut *self.store.write())
    }

    /// Restore store contents from a previous backup.
    ///
    /// Used for preserving suggestions across API reload.
    pub fn restore_store(&self, store: SuggestStore) {
        *self.store.write() = store;
    }
}

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

    #[test]
    fn test_suggest_query_builder() {
        let query = SuggestQuery::all()
            .with_category(SuggestCategory::Derive)
            .with_max_safety(SafetyLevel::Confirm)
            .with_min_confidence(0.8)
            .with_limit(10);

        assert_eq!(query.category, Some(SuggestCategory::Derive));
        assert_eq!(query.max_safety, Some(SafetyLevel::Confirm));
        assert_eq!(query.min_confidence, Some(0.8));
        assert_eq!(query.limit, Some(10));
    }

    #[test]
    fn test_service_new() {
        let registry = SuggestRegistry::new();
        let service = SuggestService::new(registry);

        assert!(service.is_empty());
        assert_eq!(service.count(), 0);
    }

    #[test]
    fn test_service_with_strategy() {
        let registry = SuggestRegistry::new();
        let strategy = SuggestStrategy::high_perf();
        let service = SuggestService::with_strategy(registry, strategy);

        assert!(service.is_empty());
    }
}