Skip to main content

Api

Struct Api 

Source
pub struct Api { /* private fields */ }
Expand description

Main API for RYO operations.

This is the primary entry point for external consumers (CLI, UI, Agent). All operations go through this facade.

Implementations§

Source§

impl Api

Source

pub fn from_path(path: impl AsRef<Path>) -> ApiResult<Self>

Create a new API from a project path.

This loads the project and builds the analysis context. Uses from_workspace_root for full workspace analysis (not just entry points).

Source

pub fn with_context( context: AnalysisContext, project: Project, storage: Box<dyn Storage>, ) -> Self

Create a new API with a pre-built context.

This is useful for server mode where the context is already loaded. Loads suggest configuration from ryo.toml via the Project.

Source

pub fn new(storage: Box<dyn Storage>) -> Self

Create a new API with the given storage backend.

This is the legacy constructor for backward compatibility. Uses current directory to load project. Loads suggest configuration from ryo.toml.

§Panics

Panics if project cannot be loaded from current directory. Consider using from_path() instead.

Source

pub fn discover( &mut self, request: DiscoverRequest, ) -> ApiResult<DiscoverResponse>

Discover symbols by pattern.

§Example
let response = api.discover(DiscoverRequest {
    pattern: "Config*".to_string(),
    kind: Some(ItemKind::Struct),
    sort: Some(SortOrder::Refs),
    limit: Some(10),
})?;
Source

pub fn overview(&self, _request: OverviewRequest) -> ApiResult<OverviewResponse>

Get codebase overview (module tree, key types, statistics).

Source

pub fn query_ryoql(&self, request: RyoqlRequest) -> ApiResult<QueryResponse>

Execute a RyoQL query and return structured results.

Parses the query string (YAML/JSON), determines view mode, and executes against the analysis context.

Source

pub fn search_literal( &self, _request: LiteralSearchRequest, ) -> ApiResult<LiteralSearchResponse>

Search literals - stub when feature is disabled.

Source

pub fn suggest(&self, request: SuggestRequest) -> ApiResult<SuggestResponse>

Get improvement suggestions.

Uses the integrated SuggestService to query cached suggestions. Call suggest_scan() first to detect new suggestions.

§Example
let response = api.suggest(SuggestRequest {
    pattern_filter: Some("*Service*".to_string()),
    high_impact: true,
    quick: false,
})?;
Source

pub fn suggest_scan(&self) -> usize

Scan the codebase and detect new suggestions.

This runs all registered patterns against the current context and populates the suggestion cache.

Respects disabled_rules, enabled_rules, and severity_overrides from ryo.toml.

Source

pub fn suggest_scan_with_scope(&self, scope_filter: &[SymbolScope]) -> usize

Scan with scope filtering.

If scope_filter is empty, all scopes are included. Otherwise, only suggestions matching one of the specified scopes are stored.

Source

pub fn suggest_scan_with_precheck(&self) -> DetectWithPrecheckResult

Scan the codebase with pre-check verification.

This runs all registered patterns against the current context, verifies each suggestion speculatively, and only stores suggestions that pass the pre-check. This ensures that Apply will succeed.

§Example
let result = api.suggest_scan_with_precheck();
println!("Passed: {}, Failed: {}", result.passed, result.failed_precheck);
Source

pub fn suggest_service(&self) -> &SuggestService

Get the SuggestService for direct access.

Source

pub fn suggest_config(&self) -> &SuggestConfig

Get the SuggestConfig.

Source

pub fn take_suggest_store(&self) -> SuggestStore

Take the suggestion store contents for preservation across reload.

Returns the current store, leaving an empty store in place.

Source

pub fn restore_suggest_store(&self, store: SuggestStore)

Restore suggestion store contents after reload.

Source

pub fn suggest_apply( &mut self, request: SuggestApplyRequest, ) -> ApiResult<SuggestApplyResponse>

Apply suggestions by ID.

Takes suggestion IDs, generates MutationSpecs, and executes them. Returns information about which suggestions were successfully applied.

§Example
let response = api.suggest_apply(SuggestApplyRequest {
    ids: vec!["S001g0".to_string(), "S002g0".to_string()],
    dry_run: false,
    check_syntax: true,
})?;

if response.success {
    println!("Applied {} suggestions", response.applied_ids.len());
}
Source

pub fn graph_summary( &self, request: GraphSummaryRequest, ) -> ApiResult<GraphSummaryResponse>

Generate code graph summary.

§Example
let response = api.graph_summary(GraphSummaryRequest::new())?;
println!("{}", response.content);
Source

pub fn graph_cascade( &self, request: CascadeRequest, ) -> ApiResult<CascadeResponse>

Analyze cascade effects of changing a symbol.

§Example
let response = api.graph_cascade(CascadeRequest {
    id: "165v1".to_string(),
    uuid: None, // or Some("550e8400-e29b-41d4-a716-446655440000".to_string())
    depth: Some(3),
})?;
Source

pub fn graph_type( &self, request: TypeAnalysisRequest, ) -> ApiResult<TypeAnalysisResponse>

Type relationship analysis using TypeFlowGraph.

Analyzes type definitions → usage relationships with O(1) impact analysis via inverted index.

Source

pub fn graph_flow( &self, request: FlowAnalysisRequest, ) -> ApiResult<FlowAnalysisResponse>

Data flow analysis (provenance and impact tracking).

Tracks data provenance (where values come from) and impact (where values flow to). Identifies sources and sinks.

Source

pub fn graph_borrow( &self, request: BorrowAnalysisRequest, ) -> ApiResult<BorrowAnalysisResponse>

Borrow analysis (conflict detection, use-after-move).

Tracks active borrows and detects potential conflicts or use-after-move errors.

Source

pub fn graph_lock( &self, request: LockAnalysisRequest, ) -> ApiResult<LockAnalysisResponse>

Lock analysis (critical sections and optimization).

Analyzes lock usage patterns, critical section sizes, and provides optimization suggestions.

Source

pub fn graph_chain( &self, request: ChainAnalysisRequest, ) -> ApiResult<ChainAnalysisResponse>

Transitive call chain traversal.

Analyzes the transitive closure of call/use relationships up to a specified depth. Uses BFS for level-order traversal with accurate depth tracking.

§Directions
  • Callers: Who calls this function (transitively)?
  • Callees: What does this function call (transitively)?
  • Users: What types use this type (transitively)?
  • Uses: What types does this type use (transitively)?
Source

pub fn status(&self) -> StatusResponse

Get server/context status.

Source

pub fn spec(&mut self, request: SpecRequest) -> ApiResult<SpecResponse>

Query spec hierarchy.

Uses cached SpecFlowData for efficient repeated queries. The cache is initialized on first call and invalidated when files change.

§Example
let response = api.spec(SpecRequest::show())?;
Source

pub fn run(&mut self, request: RunRequest) -> ApiResult<RunResponse>

Execute code transformations.

§Example
let response = api.run(RunRequest {
    goal: Goal::new(Intent::RenameIdent { ... }),
    dry_run: false,
    check_syntax: true,
})?;
Source

pub fn execute(&mut self, goal: Goal) -> ApiResult<ExecutionResult>

Execute a goal with default options.

This is a convenience wrapper around execute_with_options with default settings.

Source

pub fn execute_with_options( &mut self, goal: Goal, options: ExecuteOptions, ) -> ApiResult<ExecutionResult>

Execute a goal on a project with custom options.

This is the main entry point for code transformations with full control.

§Flow
  1. Validate goal confidence
  2. Plan mutations from Intent using Planner
  3. Build ParallelBlueprint from MutationSpecs
  4. Handle conflicts according to ConflictStrategy
  5. Execute via BlueprintExecutor (unless dry_run)
  6. Verify syntax if check_syntax enabled
  7. Record mutations to TxLog
  8. Apply changes back to Project
§Conflict Handling
  • ConflictStrategy::Fail: Returns error if conflicts detected
  • ConflictStrategy::IntentOrder: Clears conflicts, executes in intent order
  • ConflictStrategy::ParallelOnly: Skips conflicting mutations
Source

pub fn execute_and_save(&mut self, goal: Goal) -> ApiResult<ExecutionResult>

Execute a goal and save the session.

Source

pub fn execute_and_save_with_options( &mut self, goal: Goal, options: ExecuteOptions, ) -> ApiResult<ExecutionResult>

Execute a goal with options and save the session.

Source

pub fn list_sessions(&self) -> ApiResult<Vec<String>>

List all sessions.

Source

pub fn load_session(&self, session_id: &str) -> ApiResult<TxLog>

Load a session’s transaction log.

Source

pub fn storage_mut(&mut self) -> &mut dyn Storage

Get mutable access to storage (for initialization, etc.)

Source

pub fn context(&self) -> &AnalysisContext

Get reference to the analysis context.

Source

pub fn project(&self) -> &Project

Get reference to the project.

Source

pub fn save_uuid_mappings(&self) -> ApiResult<()>

Save UUID mappings to disk for persistence across sessions.

Callers must explicitly call this method to persist UUID mappings. This is NOT called automatically on drop.

§When to Call
  • Server mode: On shutdown RPC and idle timeout (see RyoServer)
  • Standalone mode: At the end of commands that modify symbols

UUID mappings are saved to .ryo/uuid-mapping.json in the workspace root.

Source

pub fn suggest_choices( &self, request: SuggestChoicesRequest, ) -> ApiResult<SuggestChoicesResponse>

Get design choices for a suggestion.

Returns the available design choices for a suggestion that has multiple implementation approaches (e.g., different refactoring strategies).

§Example
let response = api.suggest_choices(SuggestChoicesRequest::new("S001g0"))?;
if response.has_choices {
    for choice in &response.choices {
        println!("{}: {} ({})", choice.label, choice.title, choice.description);
    }
}
Source

pub fn suggest_verify( &self, request: SuggestVerifyRequest, ) -> ApiResult<SuggestVerifyResponse>

Verify a suggestion before applying.

Runs verification checks on a suggestion to ensure it can be safely applied. Supports two verification levels:

  • Light: Fast in-memory graph check
  • Full: Cargo check in temporary workspace
§Example
let response = api.suggest_verify(SuggestVerifyRequest::new("S001g0").level(VerifyLevel::Full))?;
if response.passed {
    println!("Verification passed in {}ms", response.duration_ms);
} else {
    for diag in &response.diagnostics {
        println!("  {}", diag);
    }
}
Source

pub fn suggest_compare( &self, request: SuggestCompareRequest, ) -> ApiResult<SuggestCompareResponse>

Compare design choices for a suggestion.

Generates a comparison table showing trade-offs between different implementation approaches for a suggestion.

§Example
let response = api.suggest_compare(SuggestCompareRequest::new("S001g0"))?;
println!("{}", response.comparison_table);
for choice in &response.ranked_choices {
    println!("{}: {}", choice.label, choice.title);
}
Source

pub fn suggest_generate( &self, request: SuggestGenerateRequest, ) -> ApiResult<SuggestGenerateResponse>

Generate code from parameterized patterns.

This method supports two modes:

  1. List mode (list: true): Returns available parameterized patterns
  2. Generate mode: Creates code from a pattern with parameters
§Example
// List available patterns
let list_req = SuggestGenerateRequest::list_patterns();
let patterns = api.suggest_generate(list_req)?;

// Generate OrderAPI
let gen_req = SuggestGenerateRequest::generate("api-pattern")
    .with_param("name", "Order");
let result = api.suggest_generate(gen_req)?;

Auto Trait Implementations§

§

impl !Freeze for Api

§

impl !RefUnwindSafe for Api

§

impl Send for Api

§

impl Sync for Api

§

impl Unpin for Api

§

impl UnsafeUnpin for Api

§

impl !UnwindSafe for Api

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext wrapper. Read more
Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more