offline-registry 0.4.0

Registry of Offline Protocol packages, skills, workflows, and templates
Documentation
//! Keyword search across packages, workflows, skills, and capabilities.

use serde::Serialize;

use crate::model::Capability;
use crate::store::Registry;

#[derive(Debug, Clone, Serialize)]
pub struct SearchHit {
    pub kind: String,
    pub name: String,
    pub description: String,
    pub score: f32,
}

pub(crate) fn tokenize(text: &str) -> Vec<String> {
    text.to_lowercase()
        .split(|c: char| !c.is_alphanumeric())
        .filter(|t| t.len() > 1)
        .map(str::to_string)
        .collect()
}

pub(crate) fn sort_hits(hits: &mut [SearchHit]) {
    hits.sort_by(|a, b| {
        b.score
            .partial_cmp(&a.score)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then_with(|| a.name.cmp(&b.name))
    });
}

impl Registry {
    /// Search all artifact kinds in one pass using the pre-built index.
    pub fn search_all(&self, query: &str, limit: usize) -> Vec<SearchHit> {
        let mut hits = self.search_index.search(query);
        hits.truncate(limit);
        hits
    }

    pub fn search_packages(&self, query: &str) -> Vec<SearchHit> {
        filter_kind(self.search_index.search(query), "package")
    }

    /// Workflows ranked by keyword overlap, except that a query describing
    /// one of the entrances (handoff, retained event delivery, nearby
    /// service) ranks that entrance first, as the planner does.
    pub fn search_workflows(&self, query: &str) -> Vec<SearchHit> {
        let mut hits = filter_kind(self.search_index.search(query), "workflow");
        if let Some(entrance) = crate::intent::classify_entrance(query) {
            let hit = match hits.iter().position(|h| h.name == entrance.workflow) {
                Some(pos) => Some(hits.remove(pos)),
                None => self.workflow(&entrance.workflow).map(|w| SearchHit {
                    kind: "workflow".to_string(),
                    name: w.name.clone(),
                    description: w.description.clone(),
                    score: entrance.score,
                }),
            };
            if let Some(hit) = hit {
                hits.insert(0, hit);
            }
        }
        hits
    }

    pub fn search_skills(&self, query: &str) -> Vec<SearchHit> {
        filter_kind(self.search_index.search(query), "skill")
    }

    pub fn search_examples(&self, query: &str) -> Vec<SearchHit> {
        filter_kind(self.search_index.search(query), "example")
    }

    pub fn search_capabilities(&self, query: &str) -> Vec<SearchHit> {
        filter_kind(self.search_index.search(query), "capability")
    }

    /// Capabilities aggregated from packages, workflows, and skills (built once at load).
    pub fn capabilities(&self) -> Vec<Capability> {
        self.aggregated_capabilities.clone()
    }
}

fn filter_kind(mut hits: Vec<SearchHit>, kind: &str) -> Vec<SearchHit> {
    hits.retain(|h| h.kind == kind);
    hits
}