Skip to main content

Crate ryo_suggest

Crate ryo_suggest 

Source
Expand description

RYO Suggest - Continuous refactoring suggestion engine

This crate provides code improvement suggestions through pattern detection and generates MutationSpecs for execution via ryo-executor.

§Architecture

┌─────────────────────────────────────────────────────────────────┐
│  Suggest Domain Layer                                           │
│  ───────────────────                                            │
│  SuggestRegistry        SuggestStore         SuggestService     │
│    ├─ register()          ├─ insert()          ├─ query()       │
│    ├─ get()               ├─ get()             ├─ detect()      │
│    └─ by_category()       └─ gc()              └─ to_specs()    │
│           ↓                    ↓                     ↓          │
│  Suggest.detect() → SuggestOpportunity → MutationSpec           │
└─────────────────────────────────────────────────────────────────┘

§Usage

use ryo_suggest::{
    SuggestService, SuggestRegistry, SuggestQuery,
    Suggest, SuggestCategory, SafetyLevel,
};

// Create registry and register patterns
let mut registry = SuggestRegistry::new();
registry.register(MyPattern::new());

// Create service
let service = SuggestService::new(registry);

// Detect suggestions
let count = service.detect(&ctx, &symbols);

// Query suggestions
let auto_safe = service.query(
    &SuggestQuery::all().with_max_safety(SafetyLevel::Auto)
);

// Generate mutation specs
for (id, _, _) in auto_safe {
    if let Some(specs) = service.to_mutation_specs(id, &ctx) {
        // Execute specs via ryo-executor...
    }
}

§Key Components

§Spec Suggests

§Implemented (Problem Detection)

CodeNameCategorySafetyDescription
RS001MissingSpecForDomainTypeLintConfirmDetect domain types without Spec TypeAlias
RS002OrphanSpecRefactorConfirmDetect unused Spec TypeAliases
RS003InvalidSpecRelationLintManualDetect SpecRelation targets that don’t exist
RS004SpecGroupInconsistencyLintManualDetect mixed Groups in same module
RS005SpecRelationCycleLintManualDetect circular dependencies in SpecRelations
RS006MissingRelationPatternConfirmSuggest Relations based on struct field types

§Implemented (Spec-Driven)

CodeNameCategorySafetyDescription
RS007SpecRelationToFieldPatternConfirmSpec relation → struct field suggestion
RS008BidirectionalRelationPatternConfirmEnsure bidirectional Spec relations

§Future Candidates (Spec-Driven)

CodeNameCategoryDescription
RS009SpecDrivenMethodPatternSpec relation → accessor method suggestion
RS010SpecGroupTraitPatternGroup → common trait implementation
RS011SpecDrivenRepositoryPatternSpec → Repository trait generation

§Performance Suggestions

CodeNameCategorySafetyDescription
RP001UnnecessaryClonePerformanceConfirmDetect clone() where ownership is not needed

§Safety Suggestions

CodeNameCategorySafetyDescription
RS101UnwrapToExpectSafetyConfirmConvert unwrap() to expect() with descriptive message
RS102StringErrorTypeSafetyManualDetect string-based error types, suggest thiserror

§Spec-First Generation (Planned)

For greenfield development, a different approach is needed:

┌─────────────────────────────────────────────────────────────────┐
│  Spec-First Generation (vs Problem Detection)                   │
│  ─────────────────────────────────────────────                  │
│                                                                 │
│  Problem Detection (current):                                   │
│    Code → detect() → Problems → MutationSpec                    │
│                                                                 │
│  Spec-First Generation (planned):                               │
│    Spec Definition → generate() → New Code                      │
│                                                                 │
│  Use Cases:                                                     │
│    - New domain model from Spec                                 │
│    - Scaffold struct/fields/methods from Spec relations         │
│    - Generate Repository/Service patterns from Spec Group       │
└─────────────────────────────────────────────────────────────────┘

Re-exports§

pub use intent_lock::IntentId;
pub use intent_lock::IntentLockOps;
pub use intent_lock::IntentLockQuery;
pub use intent_lock::LockError;
pub use intent_lock::NoOpIntentLock;
pub use pattern::PatternBasedSuggest;
pub use pattern::RuleScope;
pub use pattern::RuleStore;
pub use pattern::RuleStoreError;
pub use design_choice::ChoiceId;
pub use design_choice::DesignChoice;
pub use design_choice::DesignChoiceSet;
pub use design_choice::Rating;
pub use design_choice::TradeOffs;
pub use enhanced::ApplyCommands;
pub use enhanced::EnhancedSuggestion;
pub use enhanced::VerificationStatus;
pub use enhanced::VerifiedCandidate;
pub use spec::BidirectionalRelation;
pub use spec::InvalidSpecRelation;
pub use spec::MissingRelation;
pub use spec::MissingSpecForDomainType;
pub use spec::OrphanSpec;
pub use spec::SpecGroupInconsistency;
pub use spec::SpecRelationCycle;
pub use spec::SpecRelationToField;
pub use spec::ApiPatternSuggest;
pub use spec::DomainStructSuggest;
pub use spec::DomainSpecGenerator;
pub use spec::GeneratorOptions;
pub use spec::SpecGenerator;
pub use spec::SpecGeneratorRegistry;
pub use generator::GeneratorEntry;
pub use generator::GeneratorScope;
pub use generator::GeneratorStore;
pub use generator::GeneratorStoreError;
pub use performance::PerformanceSuggest;
pub use performance::UnnecessaryClone;
pub use safety::SafetySuggest;
pub use safety::StringErrorType;
pub use safety::UnwrapToExpect;

Modules§

design_choice
Design choice types for multiple alternative suggestions.
enhanced
Enhanced suggestion types with verification and design choices.
generator
Generator Template System
intent_lock
IntentLock - Dirty read prevention for concurrent LLM operations
lint
Lint rules implemented as Suggest patterns
pattern
Pattern-based suggestion integration
performance
Performance suggestions - Detect performance improvement opportunities
safety
Safety suggestions - Detect code safety improvement opportunities
spec
Spec-related suggestions

Structs§

AcChanges
Changes to AnalysisContext (used for incremental updates)
AllowStore
Store for allow directives extracted from source files.
DetectWithPrecheckResult
Result of detection with pre-check.
GcConfig
GC configuration for SuggestStore
GeneratorLoader
Generator template loader
GeneratorMeta
Generator metadata
GeneratorTemplate
A generator template loaded from YAML
GoalId
Unique identifier for a Goal
OpportunityId
Newtype for opportunity IDs (unique within a detection run)
ParamDef
Definition of a parameter for parameterized suggestions.
ParamSpec
Parameter specification
ParameterizedSuggestInfo
Information about a parameterized suggestion.
PendingChanges
Accumulated changes waiting for evaluation
StoredSuggestion
Internal storage for a suggestion
SuggestId
Unique identifier for a suggestion coupled to AnalysisContext lifecycle
SuggestIdGenerator
Generator for sequential SuggestIds
SuggestIndex
Index into SuggestRegistry (newtype for type safety)
SuggestLocation
Location information for a suggestion
SuggestOpportunity
A detected opportunity for improvement
SuggestQuery
Query filter for suggestions
SuggestRegistry
Registry of all Suggest implementations
SuggestService
Thread-safe service for accessing suggestions
SuggestStats
Statistics about service state
SuggestStore
Manages suggestion lifecycle in sync with AnalysisContext
SuggestStrategy
Strategy for controlling suggestion re-evaluation timing
SuggestView
View of a suggestion returned by queries
TemplateSpec
Code template specification
WaveId
Unique identifier for a Wave (collection of Goals)

Enums§

EnumToTraitStrategy
Strategy for enum-to-trait conversion
EvalGranularity
Granularity of re-evaluation
GeneratorLoadError
Errors from generator loading
InsertPosition
Where to insert the generated code
LintSeverity
Severity level for lint violations (maps to SafetyLevel)
MatchHandling
How to handle match expressions on the converted enum
MutationSpec
Atomic mutation specification
OpportunityContext
Type-safe context for different suggestion types
ParseSuggestIdError
Error when parsing a SuggestId from string
PrecheckStatus
Precheck verification status
RenderError
Errors during template rendering
SafetyLevel
Safety classification for auto-application decisions
SuggestCategory
Category for suggestion classification
SuggestError
Error type for to_mutation_specs() operations
SuggestTrigger
Trigger for suggestion re-evaluation
SymbolScope
The code scope where a symbol is defined.
TriggerKind
Kind of trigger (for strategy configuration)

Traits§

Suggest
Detection + MutationSpec generation capability

Functions§

compute_priority
Compute priority score from confidence, safety level, and pattern weight.

Type Aliases§

SuggestBox
Boxed Suggest trait object
SuggestParams
Parameters for parameterized suggestions.
SuggestResult
Result type for Suggest operations