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
//! Suggest trait and core types for continuous refactoring
//!
//! This module defines the domain model for detecting improvement opportunities
//! and generating MutationSpecs for execution.
//!
//! # Architecture: Suggest and the Two-Layer Mutation System
//!
//! Ryo has two mutation specification layers:
//! - [`Intent`](ryo_app::intent::Intent): Public DSL for CLI users (pattern-based)
//! - [`MutationSpec`]: Execution-level specification (concrete targets)
//!
//! The `Suggest` system **bypasses Intent** and generates `MutationSpec` directly:
//!
//! ```text
//! ┌─────────────────────────────────────────────────────────────────┐
//! │  Suggest::detect()                                              │
//! │  - Analyzes code for improvement opportunities                  │
//! │  - Returns SuggestOpportunity with concrete SymbolIds           │
//! └───────────────────────────┬─────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │  Suggest::to_mutation_specs()                                   │
//! │  - Converts opportunity to MutationSpec(s)                      │
//! │  - Skips Intent layer (no pattern resolution needed)            │
//! └───────────────────────────┬─────────────────────────────────────┘
//!//! ┌─────────────────────────────────────────────────────────────────┐
//! │  Executor                                                       │
//! │  - Applies MutationSpecs to AST                                 │
//! └─────────────────────────────────────────────────────────────────┘
//! ```
//!
//! ## Why Bypass Intent?
//!
//! - Suggest already has resolved symbols from `AnalysisContext`
//! - No need for pattern matching (targets are concrete)
//! - More efficient: direct path to execution
//!
//! ## Re-export of MutationSpec
//!
//! `MutationSpec` is re-exported here for convenience. Users of the Suggest
//! system can import both `Suggest` trait and `MutationSpec` from this module
//! without needing to depend on `ryo-executor` directly.

use std::collections::HashMap;
use std::fmt;

use ryo_analysis::context::AnalysisContext;
use ryo_analysis::{SymbolId, SymbolPath};
use serde::{Deserialize, Serialize};
use thiserror::Error;

// =============================================================================
// Error Types
// =============================================================================

/// Error type for `to_mutation_specs()` operations
#[derive(Debug, Error)]
pub enum SuggestError {
    #[error("Failed to resolve module path for spec at {path}")]
    ModulePathResolution { path: String },

    #[error("Invalid symbol path: {reason}")]
    InvalidSymbolPath { reason: String },

    #[error("Missing required context: {context}")]
    MissingContext { context: String },
}

/// Result type for Suggest operations
pub type SuggestResult<T> = Result<T, SuggestError>;

// =============================================================================
// Parameterized Suggest Types
// =============================================================================

/// Parameters for parameterized suggestions.
///
/// Used to pass variables like `{ "name": "Order" }` to generate
/// context-specific code (e.g., `OrderAPI`, `OrderService`).
pub type SuggestParams = HashMap<String, String>;

/// Definition of a parameter for parameterized suggestions.
///
/// Used by LLMs to understand what parameters a suggestion accepts.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ParamDef {
    /// Parameter name (e.g., "name")
    pub name: String,
    /// Human-readable description (e.g., "Name of the API to generate")
    pub description: String,
    /// Whether this parameter is required
    pub required: bool,
}

impl ParamDef {
    /// Create a required parameter definition
    pub fn required(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            required: true,
        }
    }

    /// Create an optional parameter definition
    pub fn optional(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            required: false,
        }
    }
}

// Re-export MutationSpec and related types from ryo-executor for convenience.
// Suggest implementations generate MutationSpecs directly, bypassing Intent.
pub use ryo_executor::executor::{EnumToTraitStrategy, MatchHandling, MutationSpec};

/// Category for suggestion classification
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum SuggestCategory {
    /// Derive macros (Default, Clone, Debug, etc.)
    Derive,
    /// Design patterns (Builder, Factory, etc.)
    Pattern,
    /// Performance improvements (Atomic, RwLock, etc.)
    Performance,
    /// Safety improvements (LockScope, etc.)
    Safety,
    /// Idiomatic transformations (match→if-let, etc.)
    Idiom,
    /// Code organization (extract, inline, etc.)
    Refactor,
    /// Lint rules (code quality checks, test coverage, etc.)
    Lint,
}

impl fmt::Display for SuggestCategory {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Derive => write!(f, "Derive"),
            Self::Pattern => write!(f, "Pattern"),
            Self::Performance => write!(f, "Performance"),
            Self::Safety => write!(f, "Safety"),
            Self::Idiom => write!(f, "Idiom"),
            Self::Refactor => write!(f, "Refactor"),
            Self::Lint => write!(f, "Lint"),
        }
    }
}

/// Safety classification for auto-application decisions
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum SafetyLevel {
    /// Fully automatic - no side effects, guaranteed safe
    /// Examples: Add #[derive(Default)] to struct with all-defaultable fields
    Auto,

    /// Confirmation recommended - standard refactoring
    /// Examples: Generate Builder pattern, extract function
    Confirm,

    /// Manual only - potential breaking changes
    /// Examples: Change public API, remove unused code
    Manual,
}

impl fmt::Display for SafetyLevel {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Auto => write!(f, "AUTO"),
            Self::Confirm => write!(f, "CONFIRM"),
            Self::Manual => write!(f, "MANUAL"),
        }
    }
}

// =============================================================================
// Priority Computation
// =============================================================================

/// Compute priority score from confidence, safety level, and pattern weight.
///
/// Returns 0-255 (higher = more important).
///
/// # Formula
/// ```text
/// priority = confidence × safety_weight × normalized_pattern_weight × 255
/// ```
///
/// Where:
/// - `confidence`: 0.0-1.0 from the opportunity
/// - `safety_weight`: Auto=1.0, Confirm=0.7, Manual=0.4
/// - `normalized_pattern_weight`: pattern_weight normalized to 0.4-1.0 range
///   (input range 0.5-2.5 maps to 0.4-1.0)
///
/// # Examples
/// ```ignore
/// // High priority: high confidence + auto safety + critical pattern
/// compute_priority(0.95, SafetyLevel::Auto, 2.5) // → ~242
///
/// // Low priority: medium confidence + manual safety + low pattern weight
/// compute_priority(0.7, SafetyLevel::Manual, 0.8) // → ~29
/// ```
pub fn compute_priority(confidence: f32, safety: SafetyLevel, pattern_weight: f32) -> u8 {
    let safety_weight = match safety {
        SafetyLevel::Auto => 1.0,
        SafetyLevel::Confirm => 0.7,
        SafetyLevel::Manual => 0.4,
    };
    // Normalize pattern_weight: 0.5-2.5 → 0.4-1.0
    // This ensures pattern weight affects but doesn't dominate priority
    let normalized_pattern = (pattern_weight / 2.5).clamp(0.4, 1.0);
    (confidence * safety_weight * normalized_pattern * 255.0).clamp(0.0, 255.0) as u8
}

/// Newtype for opportunity IDs (unique within a detection run)
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct OpportunityId(pub u32);

impl OpportunityId {
    pub fn new(id: u32) -> Self {
        Self(id)
    }

    pub fn as_u32(self) -> u32 {
        self.0
    }
}

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

/// Location information for a suggestion
///
/// Uses SymbolId/SymbolPath for precise symbol reference.
/// The `file` field is derived from the symbol's span when available.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SuggestLocation {
    /// Symbol ID for precise reference
    pub symbol_id: SymbolId,

    /// Symbol path (e.g., "test_crate::module::SymbolName")
    pub symbol_path: SymbolPath,

    /// File path (derived from symbol span, for display)
    pub file: String,
}

impl SuggestLocation {
    /// Create a new SuggestLocation from symbol information
    pub fn new(symbol_id: SymbolId, symbol_path: SymbolPath, file: impl Into<String>) -> Self {
        Self {
            symbol_id,
            symbol_path,
            file: file.into(),
        }
    }

    /// Create from AnalysisContext by looking up the symbol
    pub fn from_context(ctx: &AnalysisContext, symbol_id: SymbolId) -> Option<Self> {
        let symbol_path = ctx.registry().resolve(symbol_id)?;
        let file = ctx
            .registry()
            .span(symbol_id)
            .map(|span| span.file.to_string())
            .unwrap_or_else(|| symbol_path.crate_name().to_string());
        Some(Self::new(symbol_id, symbol_path.clone(), file))
    }

    /// Get the symbol name (last component of path)
    pub fn symbol_name(&self) -> &str {
        self.symbol_path.name()
    }

    /// Create a test location with dummy SymbolId
    #[cfg(any(test, feature = "testing"))]
    pub fn for_test(file: impl Into<String>, symbol_name: impl Into<String>) -> Self {
        let name = symbol_name.into();
        // Use a fixed test SymbolId (0v1 format)
        let symbol_id = SymbolId::parse("0v1").expect("test SymbolId");
        let symbol_path = SymbolPath::builder("test")
            .push(&name)
            .build()
            .expect("test path");
        Self {
            symbol_id,
            symbol_path,
            file: file.into(),
        }
    }
}

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

/// Severity level for lint violations (maps to SafetyLevel)
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LintSeverity {
    /// Informational message
    Info,
    /// Warning that should be addressed
    Warning,
    /// Error that must be fixed
    Error,
}

impl fmt::Display for LintSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Info => write!(f, "info"),
            Self::Warning => write!(f, "warning"),
            Self::Error => write!(f, "error"),
        }
    }
}

impl std::str::FromStr for LintSeverity {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "info" | "hint" => Ok(Self::Info),
            "warning" | "warn" => Ok(Self::Warning),
            "error" | "err" => Ok(Self::Error),
            _ => Err(format!("Unknown severity: {}", s)),
        }
    }
}

impl From<LintSeverity> for SafetyLevel {
    fn from(severity: LintSeverity) -> Self {
        match severity {
            LintSeverity::Info => SafetyLevel::Auto,
            LintSeverity::Warning => SafetyLevel::Confirm,
            LintSeverity::Error => SafetyLevel::Manual,
        }
    }
}

impl From<SafetyLevel> for LintSeverity {
    fn from(level: SafetyLevel) -> Self {
        match level {
            SafetyLevel::Auto => LintSeverity::Info,
            SafetyLevel::Confirm => LintSeverity::Warning,
            SafetyLevel::Manual => LintSeverity::Error,
        }
    }
}

/// Type-safe context for different suggestion types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum OpportunityContext {
    /// Default derive opportunity
    Derive {
        derive_name: String,
        #[serde(default)]
        missing_impls: Vec<String>,
    },

    /// Builder pattern opportunity
    Builder {
        struct_name: String,
        field_count: usize,
        has_required_fields: bool,
    },

    /// Atomic replacement opportunity
    Atomic {
        current_type: String,
        suggested_atomic: String,
    },

    /// From/Into implementation opportunity
    FromInto {
        source_type: String,
        target_type: String,
    },

    /// Lint violation context
    Lint {
        /// Rule code (e.g., "RL001")
        code: String,
        /// Rule name (e.g., "require-test-for-mutation")
        rule: String,
        /// Severity level
        severity: LintSeverity,
        /// Optional suggestion for fixing
        #[serde(default)]
        suggestion: Option<String>,
        /// Expected pattern (what should exist)
        #[serde(default)]
        expected: Option<String>,
        /// Actual pattern (what was found)
        #[serde(default)]
        actual: Option<String>,
    },

    /// Spec (domain specification) opportunity
    Spec {
        /// Rule code (e.g., "RS001")
        code: String,
        /// Spec alias name (e.g., "TaskSpec")
        #[serde(default)]
        alias_name: Option<String>,
        /// Base type name (e.g., "Task")
        #[serde(default)]
        base_type: Option<String>,
        /// Group name (e.g., "DomainGroup")
        #[serde(default)]
        group: Option<String>,
        /// Related types (for relation suggestions)
        #[serde(default)]
        related_types: Vec<String>,
        /// Optional suggestion for fixing
        #[serde(default)]
        suggestion: Option<String>,
    },

    /// Generic context for extensibility
    Custom {
        #[serde(flatten)]
        data: serde_json::Value,
    },

    /// Parameterized code generation context.
    ///
    /// Used when generating code from a pattern with user-provided parameters.
    /// Example: API pattern with `{ "name": "Order" }` generates `OrderAPI`.
    Generation {
        /// Pattern name (e.g., "api", "domain", "service")
        pattern: String,
        /// User-provided parameters (e.g., `{ "name": "Order" }`)
        params: HashMap<String, String>,
    },
}

// =============================================================================
// Symbol Scope
// =============================================================================

/// The code scope where a symbol is defined.
///
/// Used to classify suggestions by their origin context, enabling
/// consumers to filter suggestions (e.g., show only library code issues).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum SymbolScope {
    /// Library code (src/lib.rs and its modules)
    #[default]
    Lib,
    /// Binary crate code (src/main.rs, src/bin/*.rs and their modules)
    Bin,
    /// Test code (#[cfg(test)] modules, tests/ directory)
    Test,
}

impl SymbolScope {
    /// Check if this scope represents production code (Lib or Bin)
    pub fn is_production(&self) -> bool {
        matches!(self, Self::Lib | Self::Bin)
    }
}

impl fmt::Display for SymbolScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Lib => write!(f, "lib"),
            Self::Bin => write!(f, "bin"),
            Self::Test => write!(f, "test"),
        }
    }
}

impl std::str::FromStr for SymbolScope {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "lib" => Ok(Self::Lib),
            "bin" => Ok(Self::Bin),
            "test" => Ok(Self::Test),
            other => Err(format!(
                "unknown scope: '{}' (expected: lib, bin, test)",
                other
            )),
        }
    }
}

impl SymbolScope {
    /// Resolve the scope for a symbol from AnalysisContext.
    ///
    /// Resolution order:
    /// 1. Check if symbol path contains a "tests" segment → Test
    /// 2. Check if symbol's file path is in tests/ directory → Test
    /// 3. Check if symbol's crate has a binary entry point → Bin
    /// 4. Otherwise → Lib
    ///
    /// The `binary_crates` set should be pre-computed via
    /// `SymbolScope::binary_crate_names(ctx)` for efficiency.
    pub fn resolve(
        ctx: &AnalysisContext,
        symbol_id: SymbolId,
        binary_crates: &std::collections::HashSet<String>,
    ) -> Self {
        // 1. Check symbol path for test module segments.
        //    Matches:
        //      - "tests" / "tests_*"  — any segment (standard #[cfg(test)] names)
        //      - "test_*"             — non-root segments only (module names like
        //        "test_utils", "test_harness"; excludes crate names like "test_crate")
        if let Some(path) = ctx.registry.path(symbol_id) {
            for (i, segment) in path.segments().enumerate() {
                if segment == "tests" || segment.starts_with("tests_") {
                    return Self::Test;
                }
                // test_ prefix only for module segments (skip crate name at index 0)
                if i > 0 && segment.starts_with("test_") {
                    return Self::Test;
                }
            }
        }

        // 2. Check file path for tests/ directory
        if let Some(span) = ctx.registry.span(symbol_id) {
            let relative = span.file.as_relative().to_string_lossy();
            if relative.contains("/tests/") || relative.starts_with("tests/") {
                return Self::Test;
            }

            // 3. Check if this symbol's crate is a binary crate
            let crate_name = span.file.crate_name().as_str();
            if binary_crates.contains(crate_name) {
                return Self::Bin;
            }
        }

        // 4. Default: library code
        Self::Lib
    }

    /// Pre-compute the set of binary crate names from AnalysisContext.
    ///
    /// A crate is binary if any of its files is a binary entry point
    /// (main.rs or src/bin/*.rs).
    pub fn binary_crate_names(ctx: &AnalysisContext) -> std::collections::HashSet<String> {
        ctx.files()
            .keys()
            .filter(|f| f.is_binary_entry())
            .map(|f| f.crate_name().as_str().to_string())
            .collect()
    }
}

// =============================================================================
// Suggest Opportunity
// =============================================================================

/// A detected opportunity for improvement
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SuggestOpportunity {
    /// Unique ID within this detection run
    pub id: OpportunityId,

    /// Target symbol(s) for this opportunity
    pub targets: Vec<SymbolId>,

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

    /// Human-readable suggestion message
    pub message: String,

    /// Confidence score (0.0 - 1.0)
    pub confidence: f32,

    /// Pattern-specific context (type-safe via enum)
    pub context: OpportunityContext,

    /// Code scope where this opportunity was detected
    #[serde(default)]
    pub scope: SymbolScope,
}

impl SuggestOpportunity {
    /// Create a new opportunity
    ///
    /// Scope defaults to `Lib`. The pipeline (detect_with_config) resolves
    /// and overwrites the scope based on symbol context.
    pub fn new(
        id: OpportunityId,
        targets: Vec<SymbolId>,
        location: SuggestLocation,
        message: impl Into<String>,
        confidence: f32,
        context: OpportunityContext,
    ) -> Self {
        Self {
            id,
            targets,
            location,
            message: message.into(),
            confidence: confidence.clamp(0.0, 1.0),
            context,
            scope: SymbolScope::default(),
        }
    }

    /// Set the scope for this opportunity
    pub fn with_scope(mut self, scope: SymbolScope) -> Self {
        self.scope = scope;
        self
    }

    /// Get the primary target symbol (first in the list)
    pub fn primary_target(&self) -> Option<SymbolId> {
        self.targets.first().copied()
    }

    /// Override severity for Lint context.
    ///
    /// Only affects Lint context - other contexts are unchanged.
    /// Returns self for chaining.
    pub fn with_severity_override(mut self, new_severity: LintSeverity) -> Self {
        if let OpportunityContext::Lint {
            ref mut severity, ..
        } = self.context
        {
            *severity = new_severity;
        }
        self
    }

    /// Get the lint severity if this is a Lint context
    pub fn lint_severity(&self) -> Option<LintSeverity> {
        if let OpportunityContext::Lint { severity, .. } = &self.context {
            Some(*severity)
        } else {
            None
        }
    }

    /// Get the lint rule code if this is a Lint context
    pub fn lint_code(&self) -> Option<&str> {
        if let OpportunityContext::Lint { code, .. } = &self.context {
            Some(code)
        } else {
            None
        }
    }

    /// Get the spec rule code if this is a Spec context
    pub fn spec_code(&self) -> Option<&str> {
        if let OpportunityContext::Spec { code, .. } = &self.context {
            Some(code)
        } else {
            None
        }
    }

    // ========== Builder Methods ==========

    /// Set suggestion text for Lint or Spec context.
    /// Returns self for chaining.
    pub fn with_suggestion(mut self, suggestion: impl Into<String>) -> Self {
        match &mut self.context {
            OpportunityContext::Lint {
                suggestion: ref mut s,
                ..
            } => {
                *s = Some(suggestion.into());
            }
            OpportunityContext::Spec {
                suggestion: ref mut s,
                ..
            } => {
                *s = Some(suggestion.into());
            }
            _ => {}
        }
        self
    }

    /// Set expected/actual for Lint context.
    /// Returns self for chaining.
    pub fn with_expected_actual(
        mut self,
        expected: impl Into<String>,
        actual: impl Into<String>,
    ) -> Self {
        if let OpportunityContext::Lint {
            expected: ref mut e,
            actual: ref mut a,
            ..
        } = &mut self.context
        {
            *e = Some(expected.into());
            *a = Some(actual.into());
        }
        self
    }

    /// Set related types for Spec context.
    /// Returns self for chaining.
    pub fn with_related_types(mut self, types: Vec<String>) -> Self {
        if let OpportunityContext::Spec {
            related_types: ref mut rt,
            ..
        } = &mut self.context
        {
            *rt = types;
        }
        self
    }

    /// Override confidence score.
    /// Returns self for chaining.
    pub fn with_confidence(mut self, confidence: f32) -> Self {
        self.confidence = confidence.clamp(0.0, 1.0);
        self
    }
}

/// Detection + MutationSpec generation capability
///
/// Each implementor:
/// 1. Detects opportunities from AnalysisContext for given symbols
/// 2. Generates MutationSpecs (NOT Mutations) for each opportunity
///
/// This separation ensures:
/// - Detect logic stays with Suggest implementations
/// - Execution flows through standard MutationSpec → Executor pipeline
/// - No special handling needed in Executor for Suggest-originated mutations
///
/// # Parameterized Suggestions
///
/// Suggestions can accept external parameters for code generation.
/// Override `accepts_params()`, `param_schema()`, and `detect_with_params()`
/// to enable parameterized generation.
///
/// ```ignore
/// impl Suggest for ApiPatternSuggest {
///     fn accepts_params(&self) -> bool { true }
///
///     fn param_schema(&self) -> Vec<ParamDef> {
///         vec![ParamDef::required("name", "API name (e.g., Order)")]
///     }
///
///     fn detect_with_params(&self, ctx, symbols, params) -> Vec<SuggestOpportunity> {
///         let name = params.get("name").unwrap();
///         // Generate OrderAPI opportunities...
///     }
/// }
/// ```
pub trait Suggest: Send + Sync {
    /// Name of this suggestion pattern (e.g., "Builder", "Default")
    fn name(&self) -> &'static str;

    /// Human-readable description
    fn description(&self) -> &str;

    /// Category for filtering/grouping
    fn category(&self) -> SuggestCategory;

    /// Safety level for auto-application decisions
    fn safety_level(&self) -> SafetyLevel;

    /// Priority weight for ranking (higher = more important)
    fn priority_weight(&self) -> f32 {
        1.0
    }

    /// Optional rule ID for pattern-based rules (e.g., "RL021").
    /// Returns None for non-pattern suggestions.
    fn rule_id(&self) -> Option<&str> {
        None
    }

    /// Target scopes where this suggest applies.
    ///
    /// When non-empty, opportunities are filtered to only those in the specified scopes.
    /// When empty (default), the suggest applies to all scopes.
    ///
    /// Example: `vec![SymbolScope::Lib, SymbolScope::Bin]` excludes test code.
    fn target_scopes(&self) -> Vec<SymbolScope> {
        vec![]
    }

    // ========== Parameterized Suggest Support ==========

    /// Whether this suggestion accepts external parameters.
    ///
    /// If true, `detect_with_params` should be overridden to handle parameters.
    /// LLMs can query this to determine if a suggestion supports generation mode.
    fn accepts_params(&self) -> bool {
        false
    }

    /// Schema of accepted parameters (for LLM consumption).
    ///
    /// Returns parameter definitions that LLMs can use to construct
    /// valid parameter sets for `detect_with_params`.
    fn param_schema(&self) -> Vec<ParamDef> {
        vec![]
    }

    /// Detect opportunities with external parameters.
    ///
    /// Override this method for parameterized code generation.
    /// The `params` map contains user-provided values like `{ "name": "Order" }`.
    ///
    /// Default implementation ignores params and delegates to `detect`.
    fn detect_with_params(
        &self,
        ctx: &AnalysisContext,
        symbols: &[SymbolId],
        _params: &SuggestParams,
    ) -> Vec<SuggestOpportunity> {
        self.detect(ctx, symbols)
    }

    // ========== Core Detection ==========

    /// Detect opportunities for the given symbols
    ///
    /// Takes:
    /// - ctx: Full AnalysisContext for graph queries, type info, etc.
    /// - symbols: Target symbols to check (batch processing)
    ///
    /// Returns: Opportunities found (may be empty)
    fn detect(&self, ctx: &AnalysisContext, symbols: &[SymbolId]) -> Vec<SuggestOpportunity>;

    /// Convert a detected opportunity to executable MutationSpecs
    ///
    /// Takes:
    /// - ctx: AnalysisContext for resolving SymbolPath, type info, etc.
    /// - opportunity: The detected opportunity
    ///
    /// Returns Vec because one opportunity may require multiple specs
    /// (e.g., Builder pattern needs struct + impl + methods)
    ///
    /// # Errors
    /// Returns `SuggestError` if mutation spec generation fails
    fn to_mutation_specs(
        &self,
        ctx: &AnalysisContext,
        opportunity: &SuggestOpportunity,
    ) -> SuggestResult<Vec<MutationSpec>>;
}

/// Boxed Suggest trait object
pub type SuggestBox = Box<dyn Suggest>;

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

    #[test]
    fn test_safety_level_ordering() {
        assert!(SafetyLevel::Auto < SafetyLevel::Confirm);
        assert!(SafetyLevel::Confirm < SafetyLevel::Manual);
    }

    #[test]
    fn test_opportunity_id_display() {
        let id = OpportunityId::new(42);
        assert_eq!(id.to_string(), "O0042");
    }

    #[test]
    fn test_suggest_location_display() {
        let loc = SuggestLocation::for_test("src/lib.rs", "MyStruct");
        // for_test creates path as "test::MyStruct"
        assert_eq!(loc.to_string(), "test::MyStruct (src/lib.rs)");
    }

    #[test]
    fn test_opportunity_context_serde() {
        let ctx = OpportunityContext::Builder {
            struct_name: "Config".into(),
            field_count: 5,
            has_required_fields: true,
        };

        let json = serde_json::to_string(&ctx).unwrap();
        let parsed: OpportunityContext = serde_json::from_str(&json).unwrap();

        match parsed {
            OpportunityContext::Builder {
                struct_name,
                field_count,
                ..
            } => {
                assert_eq!(struct_name, "Config");
                assert_eq!(field_count, 5);
            }
            _ => panic!("Wrong variant"),
        }
    }

    #[test]
    fn test_confidence_clamping() {
        let opp = SuggestOpportunity::new(
            OpportunityId::new(1),
            vec![],
            SuggestLocation::for_test("test.rs", "Test"),
            "Test message",
            1.5, // Over 1.0
            OpportunityContext::Derive {
                derive_name: "Default".into(),
                missing_impls: vec![],
            },
        );
        assert_eq!(opp.confidence, 1.0);

        let opp2 = SuggestOpportunity::new(
            OpportunityId::new(2),
            vec![],
            SuggestLocation::for_test("test.rs", "Test"),
            "Test message",
            -0.5, // Below 0.0
            OpportunityContext::Derive {
                derive_name: "Default".into(),
                missing_impls: vec![],
            },
        );
        assert_eq!(opp2.confidence, 0.0);
    }

    #[test]
    fn test_lint_severity_from_str() {
        use std::str::FromStr;

        // Lowercase
        assert_eq!(LintSeverity::from_str("info").unwrap(), LintSeverity::Info);
        assert_eq!(
            LintSeverity::from_str("warning").unwrap(),
            LintSeverity::Warning
        );
        assert_eq!(
            LintSeverity::from_str("error").unwrap(),
            LintSeverity::Error
        );

        // Titlecase (from YAML/TOML)
        assert_eq!(LintSeverity::from_str("Info").unwrap(), LintSeverity::Info);
        assert_eq!(
            LintSeverity::from_str("Warning").unwrap(),
            LintSeverity::Warning
        );
        assert_eq!(
            LintSeverity::from_str("Error").unwrap(),
            LintSeverity::Error
        );

        // Aliases
        assert_eq!(LintSeverity::from_str("hint").unwrap(), LintSeverity::Info);
        assert_eq!(
            LintSeverity::from_str("warn").unwrap(),
            LintSeverity::Warning
        );
        assert_eq!(LintSeverity::from_str("err").unwrap(), LintSeverity::Error);

        // Invalid
        assert!(LintSeverity::from_str("invalid").is_err());
    }

    #[test]
    fn test_opportunity_severity_override() {
        let opp = SuggestOpportunity::new(
            OpportunityId::new(1),
            vec![],
            SuggestLocation::for_test("test.rs", "Test"),
            "Test message",
            0.8,
            OpportunityContext::Lint {
                code: "RL001".into(),
                rule: "no-unwrap".into(),
                severity: LintSeverity::Warning,
                suggestion: None,
                expected: None,
                actual: None,
            },
        );

        // Original severity
        assert_eq!(opp.lint_severity(), Some(LintSeverity::Warning));

        // Override severity
        let opp = opp.with_severity_override(LintSeverity::Error);
        assert_eq!(opp.lint_severity(), Some(LintSeverity::Error));

        // Non-lint context is unchanged
        let opp2 = SuggestOpportunity::new(
            OpportunityId::new(2),
            vec![],
            SuggestLocation::for_test("test.rs", "Test"),
            "Test message",
            0.8,
            OpportunityContext::Derive {
                derive_name: "Default".into(),
                missing_impls: vec![],
            },
        );
        let opp2 = opp2.with_severity_override(LintSeverity::Error);
        assert_eq!(opp2.lint_severity(), None); // Still None, not Lint context
    }
}