refactor: rebuild desktop app with Tauri

This commit is contained in:
leookun committed 2026-08-24 02:49:00 +08:00
1 parent a3ec2a0dfc
commit 4053a7fb20
808 files changed
+87359 -181491

No files matched your search

+219
View File
@@ -0,0 +1,219 @@
//! Incremental BM25 document data and a compact runtime inverted index.
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use super::{IndexedFile, IndexedLexicalDocument, IndexedTermFrequency};
use crate::index::tokenize;
const K1: f32 = 1.5;
const B: f32 = 0.75;
#[derive(Clone, Copy, Deserialize, Serialize)]
struct Posting {
document: usize,
frequency: u32,
}
#[derive(Clone, Copy, Debug, PartialEq)]
pub(crate) struct Bm25Match {
pub document: usize,
pub score: f32,
pub coverage: f32,
}
#[derive(Deserialize, Serialize)]
pub struct Bm25Index {
document_lengths: Vec<u32>,
average_document_length: f32,
postings: HashMap<String, Vec<Posting>>,
}
impl Bm25Index {
pub fn from_files(files: &mut [IndexedFile]) -> Self {
let document_count = files
.iter()
.map(|file| file.lexical_documents.len())
.sum::<usize>();
let mut document_lengths = Vec::with_capacity(document_count);
let mut postings = HashMap::<String, Vec<Posting>>::new();
for file in files {
for document in std::mem::take(&mut file.lexical_documents) {
let position = document_lengths.len();
document_lengths.push(document.length);
for term in document.terms {
let posting = Posting {
document: position,
frequency: term.frequency,
};
postings.entry(term.term).or_default().push(posting);
}
}
}
let total_length = document_lengths
.iter()
.map(|length| u64::from(*length))
.sum::<u64>();
let average_document_length = if document_lengths.is_empty() {
0.0
} else {
total_length as f32 / document_lengths.len() as f32
};
Self {
document_lengths,
average_document_length,
postings,
}
}
pub(crate) fn search(&self, query: &str, limit: usize) -> Vec<Bm25Match> {
if limit == 0 || self.document_lengths.is_empty() {
return Vec::new();
}
let mut query_terms = HashMap::<String, u32>::new();
for term in tokenize(query) {
*query_terms.entry(term).or_default() += 1;
}
let corpus_size = self.document_lengths.len() as f32;
let average_length = self.average_document_length.max(f32::EPSILON);
let mut scores = HashMap::<usize, f32>::new();
let mut matched_weight = HashMap::<usize, f32>::new();
let mut query_weight = 0.0;
for (term, query_frequency) in query_terms {
let postings = self.postings.get(&term);
let document_frequency = postings.map_or(0.0, |values| values.len() as f32);
let inverse_document_frequency =
(1.0 + (corpus_size - document_frequency + 0.5) / (document_frequency + 0.5)).ln();
query_weight += inverse_document_frequency;
let Some(postings) = postings else {
continue;
};
for posting in postings {
let term_frequency = posting.frequency as f32;
let document_length = self.document_lengths[posting.document] as f32;
let normalized_frequency = term_frequency
/ (K1 * (1.0 - B + B * document_length / average_length) + term_frequency);
*scores.entry(posting.document).or_default() +=
query_frequency as f32 * inverse_document_frequency * normalized_frequency;
*matched_weight.entry(posting.document).or_default() += inverse_document_frequency;
}
}
let mut ranked = scores
.into_iter()
.filter(|(_, score)| *score > 0.0)
.map(|(document, score)| Bm25Match {
document,
score,
coverage: matched_weight.get(&document).copied().unwrap_or_default()
/ query_weight.max(f32::EPSILON),
})
.collect::<Vec<_>>();
ranked.sort_by(|left, right| {
right
.score
.total_cmp(&left.score)
.then_with(|| left.document.cmp(&right.document))
});
ranked.truncate(limit.min(ranked.len()));
ranked
}
pub(crate) fn validate(&self, chunks: usize) -> bool {
self.document_lengths.len() == chunks
&& self
.postings
.values()
.flatten()
.all(|posting| posting.document < chunks && posting.frequency > 0)
}
}
pub fn lexical_document(content: &str) -> IndexedLexicalDocument {
let tokens = tokenize(content);
let length = u32::try_from(tokens.len()).unwrap_or(u32::MAX);
let mut counts = HashMap::<String, u32>::new();
for token in tokens {
*counts.entry(token).or_default() += 1;
}
let mut terms = counts
.into_iter()
.map(|(term, frequency)| IndexedTermFrequency { term, frequency })
.collect::<Vec<_>>();
terms.sort_by(|left, right| left.term.cmp(&right.term));
IndexedLexicalDocument { length, terms }
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{source::FileStamp, Chunk, ContentType};
fn indexed_file(contents: &[&str]) -> IndexedFile {
let chunks = contents
.iter()
.enumerate()
.map(|(index, content)| Chunk {
file_path: "src/lib.rs".into(),
start_line: index + 1,
end_line: index + 1,
language: Some("rust".into()),
content: (*content).into(),
})
.collect::<Vec<_>>();
IndexedFile {
path: "src/lib.rs".into(),
stamp: FileStamp {
modified_ns: 1,
size: 1,
},
content_type: ContentType::Code,
lexical_documents: chunks
.iter()
.map(|chunk| lexical_document(&chunk.content))
.collect(),
chunks,
definitions: Vec::new(),
vectors: Vec::new(),
}
}
#[test]
fn ranks_identifier_aware_lexical_matches_and_excludes_zero_scores() {
let file = indexed_file(&[
"fn parseConfig() { parse_config(); }",
"fn authenticate() { verify_token(); }",
"fn parse_document() {}",
]);
let index = Bm25Index::from_files(&mut [file]);
let matches = index.search("parse config", 3);
assert_eq!(
matches
.iter()
.map(|matched| matched.document)
.collect::<Vec<_>>(),
vec![0, 2]
);
assert_eq!(matches[0].coverage, 1.0);
assert!(matches[1].coverage < matches[0].coverage);
assert!(index.search("missing_identifier", 3).is_empty());
}
#[test]
fn lexical_documents_store_sorted_term_frequencies() {
let document = lexical_document("parseConfig parse_config");
assert_eq!(document.length, 6);
assert!(document
.terms
.windows(2)
.all(|terms| terms[0].term < terms[1].term));
assert_eq!(
document
.terms
.iter()
.find(|term| term.term == "parse")
.map(|term| term.frequency),
Some(2)
);
}
}
+407
View File
@@ -0,0 +1,407 @@
//! Incremental index builder that reuses unchanged chunks and embeddings.
use std::{
collections::HashMap,
fs,
num::NonZeroUsize,
path::Path,
sync::Arc,
time::{Duration, Instant},
};
use lru::LruCache;
use parking_lot::Mutex;
use crate::{
cache::{load_runtime, load_snapshot, save_runtime, save_snapshot, CacheLayout},
chunk::chunk_source,
config::{SembleConfig, INDEX_FORMAT_VERSION},
embedding::Embedder,
index::extract_definitions,
language::detect_language,
source::discover_files,
ContentType, Error, Result,
};
use super::{lexical_document, IndexSnapshot, IndexedFile, LoadedIndex};
pub struct IndexRepository {
config: SembleConfig,
embedder: Arc<dyn Embedder>,
build_lock: Mutex<()>,
loaded: Mutex<LruCache<std::path::PathBuf, CachedIndex>>,
}
const SEARCH_REFRESH_INTERVAL: Duration = Duration::from_secs(1);
struct CachedIndex {
index: Arc<LoadedIndex>,
checked_at: Instant,
}
impl IndexRepository {
pub fn new(config: SembleConfig, embedder: Arc<dyn Embedder>) -> Self {
Self {
config,
embedder,
build_lock: Mutex::new(()),
loaded: Mutex::new(LruCache::new(
NonZeroUsize::new(10).expect("non-zero cache size"),
)),
}
}
pub fn load_or_build(
&self,
root: &Path,
identity: &str,
content: &[ContentType],
) -> Result<Arc<LoadedIndex>> {
let layout = CacheLayout::new(
&self.config.cache_dir,
identity,
self.embedder.id(),
content,
self.config.desired_chunk_bytes,
);
let files = discover_files(root, content, self.config.max_file_bytes)?;
if files.is_empty() {
return Err(Error::EmptyIndex(root.to_path_buf()));
}
if let Some(index) = self.checked_if_unchanged(&layout.snapshot, &files) {
return Ok(index);
}
let _guard = self.build_lock.lock();
if let Some(index) = self.checked_if_unchanged(&layout.snapshot, &files) {
return Ok(index);
}
let runtime = load_runtime(&layout.runtime)
.ok()
.flatten()
.filter(|runtime| {
runtime.metadata.source_identity == identity
&& runtime.metadata.model_id == self.embedder.id()
&& runtime.metadata.desired_chunk_bytes == self.config.desired_chunk_bytes
&& runtime.metadata.content == content
&& unchanged_loaded(&files, &runtime.metadata.files)
});
if let Some(runtime) = runtime {
let loaded = Arc::new(runtime);
self.store_loaded(layout.snapshot, loaded.clone());
return Ok(loaded);
}
let previous = load_snapshot(&layout.snapshot)
.ok()
.flatten()
.filter(|snapshot| {
snapshot.source_identity == identity
&& snapshot.model_id == self.embedder.id()
&& snapshot.desired_chunk_bytes == self.config.desired_chunk_bytes
&& snapshot.content == content
});
let snapshot_is_current = previous.as_ref().is_some_and(|snapshot| {
let stamps = snapshot
.files
.iter()
.map(|file| (file.path.as_str(), file.stamp))
.collect::<HashMap<_, _>>();
files.len() == snapshot.files.len()
&& files
.iter()
.all(|file| stamps.get(file.relative_path.as_str()) == Some(&file.stamp))
});
if snapshot_is_current {
let snapshot = previous.expect("current snapshot exists");
let loaded = Arc::new(LoadedIndex::from_snapshot(snapshot)?);
save_runtime(&layout.runtime, &loaded)?;
self.store_loaded(layout.snapshot, loaded.clone());
return Ok(loaded);
}
let mut old = previous
.map(|snapshot| {
snapshot
.files
.into_iter()
.map(|file| (file.path.clone(), file))
.collect::<HashMap<_, _>>()
})
.unwrap_or_default();
let mut indexed = Vec::new();
for file in files {
if let Some(cached) = old
.remove(&file.relative_path)
.filter(|cached| cached.stamp == file.stamp)
{
indexed.push(cached);
continue;
}
let bytes = fs::read(&file.absolute_path)
.map_err(|error| Error::io(&file.absolute_path, error))?;
if bytes.iter().take(8192).any(|byte| *byte == 0) {
continue;
}
let source = String::from_utf8_lossy(&bytes);
let language = detect_language(&file.absolute_path);
let chunks = chunk_source(
&source,
&file.relative_path,
language,
self.config.desired_chunk_bytes,
);
if chunks.is_empty() {
continue;
}
let texts = chunks
.iter()
.map(|chunk| chunk.content.clone())
.collect::<Vec<_>>();
let vectors =
quantize_vectors(self.embedder.encode(&texts)?, self.embedder.dimensions())?;
let lexical_documents = chunks
.iter()
.map(|chunk| lexical_document(&chunk.content))
.collect();
indexed.push(IndexedFile {
path: file.relative_path,
stamp: file.stamp,
content_type: file.content_type,
definitions: extract_definitions(&chunks),
lexical_documents,
chunks,
vectors,
});
}
if indexed.is_empty() {
return Err(Error::EmptyIndex(root.to_path_buf()));
}
let snapshot = IndexSnapshot {
format_version: INDEX_FORMAT_VERSION,
source_identity: identity.to_owned(),
model_id: self.embedder.id().to_owned(),
dimensions: self.embedder.dimensions(),
desired_chunk_bytes: self.config.desired_chunk_bytes,
content: content.to_vec(),
files: indexed,
};
save_snapshot(&layout.snapshot, &snapshot)?;
let loaded = Arc::new(LoadedIndex::from_snapshot(snapshot)?);
save_runtime(&layout.runtime, &loaded)?;
self.store_loaded(layout.snapshot, loaded.clone());
Ok(loaded)
}
/// Returns a recently checked in-memory index, refreshing stale entries first.
pub fn load_for_search(
&self,
root: &Path,
identity: &str,
content: &[ContentType],
) -> Result<Arc<LoadedIndex>> {
let layout = CacheLayout::new(
&self.config.cache_dir,
identity,
self.embedder.id(),
content,
self.config.desired_chunk_bytes,
);
if let Some(index) = self
.loaded
.lock()
.get(&layout.snapshot)
.filter(|cached| cached.checked_at.elapsed() < SEARCH_REFRESH_INTERVAL)
.map(|cached| cached.index.clone())
{
return Ok(index);
}
self.load_or_build(root, identity, content)
}
fn store_loaded(&self, snapshot: std::path::PathBuf, index: Arc<LoadedIndex>) {
self.loaded.lock().put(
snapshot,
CachedIndex {
index,
checked_at: Instant::now(),
},
);
}
fn checked_if_unchanged(
&self,
snapshot: &Path,
files: &[crate::source::SourceFile],
) -> Option<Arc<LoadedIndex>> {
let mut loaded = self.loaded.lock();
let cached = loaded.get_mut(snapshot)?;
if unchanged_loaded(files, &cached.index.metadata.files) {
cached.checked_at = Instant::now();
Some(cached.index.clone())
} else {
None
}
}
pub(crate) fn encode(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
self.embedder.encode(texts)
}
}
fn quantize_vectors(vectors: Vec<Vec<f32>>, dimensions: usize) -> Result<Vec<i8>> {
if vectors.iter().any(|vector| vector.len() != dimensions) {
return Err(Error::CorruptIndex(
"embedder returned an invalid vector shape".into(),
));
}
Ok(vectors
.into_iter()
.flatten()
.map(|value| (value.clamp(-1.0, 1.0) * 127.0).round() as i8)
.collect())
}
fn unchanged_loaded(files: &[crate::source::SourceFile], indexed: &[super::LoadedFile]) -> bool {
if files.len() != indexed.len() {
return false;
}
let stamps = indexed
.iter()
.map(|file| (file.path.as_str(), file.stamp))
.collect::<HashMap<_, _>>();
files
.iter()
.all(|file| stamps.get(file.relative_path.as_str()) == Some(&file.stamp))
}
#[cfg(test)]
mod tests {
use std::sync::atomic::{AtomicUsize, Ordering};
use super::*;
struct CountingEmbedder(AtomicUsize);
impl Embedder for CountingEmbedder {
fn id(&self) -> &str {
"counting-v1"
}
fn dimensions(&self) -> usize {
2
}
fn encode(&self, texts: &[String]) -> Result<Vec<Vec<f32>>> {
self.0.fetch_add(texts.len(), Ordering::SeqCst);
Ok(texts
.iter()
.map(|text| vec![text.len() as f32, 1.0])
.collect())
}
}
#[test]
fn unchanged_files_reuse_persisted_chunks_and_vectors() {
let source = tempfile::tempdir().unwrap();
let cache = tempfile::tempdir().unwrap();
fs::write(
source.path().join("lib.rs"),
"pub fn one() { println!(\"one\"); }\n",
)
.unwrap();
let embedder = Arc::new(CountingEmbedder(AtomicUsize::new(0)));
let repository = IndexRepository::new(SembleConfig::new(cache.path()), embedder.clone());
let first = repository
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
let encoded = embedder.0.load(Ordering::SeqCst);
assert!(encoded > 0);
let second = repository
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
assert_eq!(embedder.0.load(Ordering::SeqCst), encoded);
assert_eq!(first.chunks.len(), second.chunks.len());
fs::write(
source.path().join("lib.rs"),
"pub fn two() { println!(\"changed and longer\"); }\n",
)
.unwrap();
let changed = repository
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
assert!(embedder.0.load(Ordering::SeqCst) > encoded);
assert!(changed
.chunks
.iter()
.any(|chunk| chunk.content.contains("two")));
}
#[test]
fn a_new_repository_instance_loads_the_same_disk_snapshot() {
let source = tempfile::tempdir().unwrap();
let cache = tempfile::tempdir().unwrap();
fs::write(source.path().join("lib.rs"), "pub fn persisted() {}\n").unwrap();
let first_embedder = Arc::new(CountingEmbedder(AtomicUsize::new(0)));
IndexRepository::new(SembleConfig::new(cache.path()), first_embedder)
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
let second_embedder = Arc::new(CountingEmbedder(AtomicUsize::new(0)));
let loaded = IndexRepository::new(SembleConfig::new(cache.path()), second_embedder.clone())
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
assert_eq!(second_embedder.0.load(Ordering::SeqCst), 0);
assert_eq!(loaded.chunks[0].file_path, "lib.rs");
}
#[test]
fn a_new_repository_refreshes_changed_source_instead_of_using_stale_runtime_cache() {
let source = tempfile::tempdir().unwrap();
let cache = tempfile::tempdir().unwrap();
fs::write(source.path().join("lib.rs"), "pub fn before() {}\n").unwrap();
IndexRepository::new(
SembleConfig::new(cache.path()),
Arc::new(CountingEmbedder(AtomicUsize::new(0))),
)
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
fs::write(
source.path().join("lib.rs"),
"pub fn after() { println!(\"changed and longer\"); }\n",
)
.unwrap();
let embedder = Arc::new(CountingEmbedder(AtomicUsize::new(0)));
let loaded = IndexRepository::new(SembleConfig::new(cache.path()), embedder.clone())
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
assert!(embedder.0.load(Ordering::SeqCst) > 0);
assert!(loaded.chunks[0].content.contains("after"));
}
#[test]
fn search_cache_refreshes_after_the_fixed_interval() {
let source = tempfile::tempdir().unwrap();
let cache = tempfile::tempdir().unwrap();
fs::write(source.path().join("lib.rs"), "pub fn before() {}\n").unwrap();
let repository = IndexRepository::new(
SembleConfig::new(cache.path()),
Arc::new(CountingEmbedder(AtomicUsize::new(0))),
);
repository
.load_or_build(source.path(), "fixture", &[ContentType::Code])
.unwrap();
fs::write(source.path().join("lib.rs"), "pub fn after() {}\n").unwrap();
let cached = repository
.load_for_search(source.path(), "fixture", &[ContentType::Code])
.unwrap();
assert!(cached.chunks[0].content.contains("before"));
for (_, cached) in repository.loaded.lock().iter_mut() {
cached.checked_at = Instant::now() - SEARCH_REFRESH_INTERVAL;
}
let refreshed = repository
.load_for_search(source.path(), "fixture", &[ContentType::Code])
.unwrap();
assert!(refreshed.chunks[0].content.contains("after"));
}
}
+539
View File
@@ -0,0 +1,539 @@
//! Compact inverted lexical index and definition-aware symbol lookup.
use std::{
collections::{HashMap, HashSet},
sync::LazyLock,
};
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::Chunk;
use super::{IndexedDefinition, IndexedFile};
static DECLARATION: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?m)^\s*(?:(?:export|default|async|declare|public|private|protected|static|pub(?:\([^)]*\))?)\s+)*(?:function|fn|def|class|struct|enum|trait|interface|type|record|module|namespace|protocol)\s+([A-Za-z_][A-Za-z0-9_]*)",
)
.expect("static declaration regex")
});
static BINDING: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"(?m)^\s*(?:(?:export|default|declare|public|private|protected|static|pub(?:\([^)]*\))?)\s+)*(?:const|let|var|static)\s+([A-Za-z_][A-Za-z0-9_]*)\s*(?::[^=\n]+)?=",
)
.expect("static binding regex")
});
pub fn tokenize(text: &str) -> Vec<String> {
let bytes = text.as_bytes();
let mut output = Vec::new();
let mut index = 0;
while index < bytes.len() {
if !bytes[index].is_ascii_alphabetic() && bytes[index] != b'_' {
index += 1;
continue;
}
let start = index;
index += 1;
while index < bytes.len() && (bytes[index].is_ascii_alphanumeric() || bytes[index] == b'_')
{
index += 1;
}
output.extend(split_identifier(&text[start..index]));
}
output
}
fn split_identifier(token: &str) -> Vec<String> {
let lower = token.to_ascii_lowercase();
let mut parts = Vec::new();
if token.contains('_') {
parts.extend(
lower
.split('_')
.filter(|part| !part.is_empty())
.map(str::to_owned),
);
} else {
let chars = token.char_indices().collect::<Vec<_>>();
let mut start = 0;
for index in 1..chars.len() {
let previous = chars[index - 1].1;
let current = chars[index].1;
let next = chars.get(index + 1).map(|item| item.1);
if (previous.is_ascii_lowercase() && current.is_ascii_uppercase())
|| (previous.is_ascii_uppercase()
&& current.is_ascii_uppercase()
&& next.is_some_and(|value| value.is_ascii_lowercase()))
{
parts.push(token[start..chars[index].0].to_ascii_lowercase());
start = chars[index].0;
}
}
if start > 0 {
parts.push(token[start..].to_ascii_lowercase());
}
}
if parts.len() >= 2 {
std::iter::once(lower).chain(parts).collect()
} else {
vec![lower]
}
}
#[derive(Clone, Debug, Deserialize, Serialize)]
struct Definition {
symbol: String,
parts: Vec<String>,
chunk: usize,
implementation: bool,
}
#[derive(Deserialize, Serialize)]
pub struct SymbolIndex {
definitions: Vec<Definition>,
definitions_by_symbol: HashMap<String, Vec<usize>>,
}
impl SymbolIndex {
pub fn from_files(files: &mut [IndexedFile]) -> Self {
let mut definitions = Vec::new();
let mut definitions_by_symbol = HashMap::<String, Vec<usize>>::new();
let mut chunk_offset = 0;
for file in files {
for indexed in std::mem::take(&mut file.definitions) {
let parts = symbol_parts(&indexed.symbol);
let mut symbol = indexed.symbol;
symbol.make_ascii_lowercase();
let position = definitions.len();
definitions.push(Definition {
symbol: symbol.clone(),
parts,
chunk: chunk_offset + indexed.chunk,
implementation: indexed.implementation,
});
definitions_by_symbol
.entry(symbol)
.or_default()
.push(position);
}
chunk_offset += file.chunks.len();
}
Self {
definitions,
definitions_by_symbol,
}
}
pub fn exact_symbol(&self, query: &str, chunks: &[Chunk], limit: usize) -> Vec<(usize, f32)> {
let symbol = query
.rsplit([':', '.', '>'])
.find(|part| !part.is_empty())
.unwrap_or(query)
.trim()
.to_ascii_lowercase();
self.rank_symbol(&symbol, chunks, limit)
}
pub fn inferred_symbols(
&self,
query: &str,
chunks: &[Chunk],
limit: usize,
) -> Vec<(usize, f32)> {
let raw_terms = tokenize(query).into_iter().collect::<HashSet<_>>();
let mut query_terms = raw_terms
.iter()
.map(|term| normalize_term(term))
.collect::<HashSet<_>>();
if query_terms.contains("update") {
query_terms.insert("set".into());
}
let mut symbols = HashMap::<&str, f32>::new();
for definition in &self.definitions {
let meaningful = definition
.parts
.iter()
.filter(|part| !is_generic_symbol_part(part))
.collect::<Vec<_>>();
let matched = meaningful
.iter()
.filter(|part| query_terms.contains(&normalize_term(part)))
.count();
let exact = definition.parts.len() > 1 && raw_terms.contains(&definition.symbol);
let qualifies = exact
|| (meaningful.len() == 1 && matched == 1)
|| (meaningful.len() >= 2 && matched == meaningful.len())
|| (meaningful.len() >= 3 && matched >= 2);
if !qualifies {
continue;
}
let coverage = matched as f32 / meaningful.len().max(1) as f32;
let unmatched = meaningful.len().saturating_sub(matched) as f32;
let action_match = meaningful.iter().any(|part| {
let normalized = normalize_term(part);
query_terms.contains(&normalized) && is_action_symbol_part(&normalized)
});
let score = if exact { 1.0 } else { 0.0 } + coverage * 5.0 + matched as f32 * 2.0
- unmatched * 3.0
- meaningful.len() as f32 * 0.1
+ if action_match { 2.0 } else { 0.0 };
symbols
.entry(&definition.symbol)
.and_modify(|current| *current = current.max(score))
.or_insert(score);
}
let mut symbols = symbols.into_iter().collect::<Vec<_>>();
symbols.sort_by(|left, right| right.1.total_cmp(&left.1).then_with(|| left.0.cmp(right.0)));
symbols.truncate(limit.min(6));
let mut output = Vec::new();
for (symbol, symbol_score) in symbols {
for (chunk, source_score) in self.rank_symbol(symbol, chunks, 1) {
let path_matches = tokenize(&chunks[chunk].file_path)
.into_iter()
.map(|term| normalize_term(&term))
.collect::<HashSet<_>>()
.intersection(&query_terms)
.count();
let source_weight = source_priority(&chunks[chunk].file_path, symbol).min(1.0);
if source_weight < 0.5 {
continue;
}
output.push((
chunk,
(symbol_score * 10.0 + path_matches as f32 * 2.0) * source_weight
+ source_score,
));
}
}
output.sort_by(|left, right| {
right
.1
.total_cmp(&left.1)
.then_with(|| left.0.cmp(&right.0))
});
output.dedup_by_key(|item| item.0);
output.truncate(limit);
output
}
fn rank_symbol(&self, symbol: &str, chunks: &[Chunk], limit: usize) -> Vec<(usize, f32)> {
let mut output = self
.definitions_by_symbol
.get(symbol)
.into_iter()
.flatten()
.map(|&position| {
let definition = &self.definitions[position];
let chunk = &chunks[definition.chunk];
let score = (1.0 + if definition.implementation { 0.5 } else { 0.0 })
* source_priority(&chunk.file_path, symbol);
(definition.chunk, score)
})
.collect::<Vec<_>>();
output.sort_by(|left, right| {
right
.1
.total_cmp(&left.1)
.then_with(|| chunks[left.0].file_path.cmp(&chunks[right.0].file_path))
.then_with(|| chunks[right.0].start_line.cmp(&chunks[left.0].start_line))
});
output.dedup_by_key(|item| item.0);
output.truncate(limit);
output
}
pub(crate) fn validate(&self, chunks: usize) -> bool {
if self
.definitions
.iter()
.any(|definition| definition.chunk >= chunks)
{
return false;
}
let mut seen = vec![false; self.definitions.len()];
for (symbol, positions) in &self.definitions_by_symbol {
for &position in positions {
let Some(definition) = self.definitions.get(position) else {
return false;
};
if definition.symbol != *symbol || std::mem::replace(&mut seen[position], true) {
return false;
}
}
}
seen.into_iter().all(|value| value)
}
}
pub fn extract_definitions(chunks: &[Chunk]) -> Vec<IndexedDefinition> {
let mut definitions = Vec::new();
for (index, chunk) in chunks.iter().enumerate() {
for captures in DECLARATION
.captures_iter(&chunk.content)
.chain(BINDING.captures_iter(&chunk.content))
{
let Some(matched) = captures.get(1) else {
continue;
};
definitions.push(IndexedDefinition {
symbol: matched.as_str().to_owned(),
chunk: index,
implementation: chunk.content[matched.end()..]
.lines()
.take(12)
.any(|line| line.contains('{') || line.trim_end().ends_with("=>")),
});
}
}
definitions
}
fn symbol_parts(symbol: &str) -> Vec<String> {
let mut values = split_identifier(symbol);
if values.len() > 1 {
values.remove(0);
}
values
.into_iter()
.map(|part| normalize_term(&part))
.collect()
}
fn normalize_term(term: &str) -> String {
let lower = term.to_ascii_lowercase();
match lower.as_str() {
"application" | "applications" => "app".into(),
"listener" | "listeners" | "listening" => "listen".into(),
"rendered" | "rendering" => "render".into(),
"hydrated" | "hydrating" => "hydrate".into(),
"compiled" | "compiling" => "compile".into(),
"parsed" | "parsing" => "parse".into(),
"called" | "calling" => "call".into(),
"cancelled" | "cancelling" | "cancellation" => "cancel".into(),
"dispatched" | "dispatching" => "dispatch".into(),
"interrupted" | "interrupting" | "interruption" => "interrupt".into(),
"started" | "starting" => "start".into(),
_ if lower.len() > 4 && lower.ends_with('s') => lower[..lower.len() - 1].into(),
_ => lower,
}
}
fn is_action_symbol_part(part: &str) -> bool {
matches!(
part,
"build"
| "call"
| "cancel"
| "commit"
| "compile"
| "create"
| "define"
| "dispatch"
| "find"
| "handle"
| "hydrate"
| "interrupt"
| "listen"
| "load"
| "mount"
| "parse"
| "patch"
| "persist"
| "read"
| "reconcile"
| "record"
| "register"
| "render"
| "save"
| "schedule"
| "search"
| "send"
| "set"
| "start"
| "store"
| "update"
| "watch"
| "write"
)
}
fn is_generic_symbol_part(part: &str) -> bool {
matches!(
part,
"all" | "api" | "base" | "impl" | "internal" | "of" | "on" | "the" | "to"
)
}
fn source_priority(path: &str, symbol: &str) -> f32 {
let normalized = path.replace('\\', "/").to_ascii_lowercase();
let mut score = 1.0;
if normalized.contains("/src/") {
score += 0.35;
}
let parts = normalized.split('/').collect::<Vec<_>>();
if let Some(packages) = parts.iter().position(|part| *part == "packages") {
if parts
.get(packages + 1)
.is_some_and(|package| !package.contains('-'))
{
score += 1.0;
}
}
if normalized
.rsplit('/')
.next()
.and_then(|file| file.rsplit_once('.').map(|(stem, _)| stem))
.is_some_and(|stem| stem == symbol || stem.ends_with(symbol))
{
score += 0.4;
}
if normalized.split('/').any(|part| {
matches!(
part,
"test" | "tests" | "__tests__" | "fixtures" | "examples" | "benchmarks"
)
}) || normalized.contains(".test.")
|| normalized.contains(".spec.")
|| normalized.contains("dts-test")
{
score *= 0.08;
}
if normalized
.split('/')
.any(|part| matches!(part, "playground" | "demo" | "demos"))
{
score *= 0.2;
}
score
}
#[cfg(test)]
mod tests {
use super::*;
fn chunk(path: &str, content: &str) -> Chunk {
Chunk {
file_path: path.into(),
start_line: 1,
end_line: 1,
language: Some("typescript".into()),
content: content.into(),
}
}
#[test]
fn tokenizer_preserves_and_splits_common_identifiers() {
assert_eq!(
tokenize("HTTPResponse parse_request"),
vec![
"httpresponse",
"http",
"response",
"parse_request",
"parse",
"request"
]
);
}
#[test]
fn exact_symbol_prefers_implementations_and_non_test_sources() {
let chunks = [
chunk("tests/useState.test.ts", "function useState() {}"),
chunk("src/hooks.ts", "export function useState<T>(value: T)\n"),
chunk(
"src/hooks.ts",
"export function useState(value: unknown) { return value }",
),
];
let index = SymbolIndex::from_files(&mut [IndexedFile {
path: "fixture.ts".into(),
stamp: crate::source::FileStamp {
modified_ns: 1,
size: 1,
},
content_type: crate::ContentType::Code,
definitions: extract_definitions(&chunks),
lexical_documents: chunks
.iter()
.map(|chunk| super::super::lexical_document(&chunk.content))
.collect(),
chunks: chunks.to_vec(),
vectors: vec![0; chunks.len()],
}]);
assert_eq!(index.exact_symbol("useState", &chunks, 3)[0].0, 2);
}
#[test]
fn natural_queries_identify_composite_definitions() {
let chunks = [
chunk(
"src/renderer.ts",
"const patchKeyedChildren = () => { longestIncreasingSubsequence() }",
),
chunk("src/other.ts", "function unrelated() {}"),
];
let index = SymbolIndex::from_files(&mut [IndexedFile {
path: "fixture.ts".into(),
stamp: crate::source::FileStamp {
modified_ns: 1,
size: 1,
},
content_type: crate::ContentType::Code,
definitions: extract_definitions(&chunks),
lexical_documents: chunks
.iter()
.map(|chunk| super::super::lexical_document(&chunk.content))
.collect(),
chunks: chunks.to_vec(),
vectors: vec![0; chunks.len()],
}]);
assert_eq!(
index.inferred_symbols(
"diff keyed children using the longest increasing subsequence",
&chunks,
5,
)[0]
.0,
0
);
}
#[test]
fn natural_queries_prefer_symbols_that_match_behavior_words() {
let chunks = [
chunk("src/runtime.rs", "fn mcp_tool() {}"),
chunk("src/runtime.rs", "fn built_in() {}"),
chunk("src/dispatch.rs", "fn call_tool() {}"),
chunk("tests/dispatch.rs", "fn dispatch_call_tool() {}"),
];
let index = SymbolIndex::from_files(&mut [IndexedFile {
path: "fixture.ts".into(),
stamp: crate::source::FileStamp {
modified_ns: 1,
size: 1,
},
content_type: crate::ContentType::Code,
definitions: extract_definitions(&chunks),
lexical_documents: chunks
.iter()
.map(|chunk| super::super::lexical_document(&chunk.content))
.collect(),
chunks: chunks.to_vec(),
vectors: vec![0; chunks.len()],
}]);
assert_eq!(
index.inferred_symbols(
"dispatch built-in MCP tool calls to the registered server implementation",
&chunks,
5,
)[0]
.0,
2
);
}
}
+14
View File
@@ -0,0 +1,14 @@
//! Incremental persisted index construction and in-memory searchable snapshots.
mod bm25;
mod builder;
mod lexical;
mod snapshot;
pub(crate) use bm25::{lexical_document, Bm25Index, Bm25Match};
pub use builder::IndexRepository;
pub use lexical::{extract_definitions, tokenize, SymbolIndex};
pub use snapshot::{
IndexSnapshot, IndexedDefinition, IndexedFile, IndexedLexicalDocument, IndexedTermFrequency,
LoadedFile, LoadedIndex, LoadedMetadata,
};
+219
View File
@@ -0,0 +1,219 @@
//! Versioned binary snapshot format and flattened runtime representation.
use serde::{Deserialize, Serialize};
use crate::{config::INDEX_FORMAT_VERSION, source::FileStamp, Chunk, ContentType, Error, Result};
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IndexedFile {
pub path: String,
pub stamp: FileStamp,
pub content_type: ContentType,
pub chunks: Vec<Chunk>,
pub definitions: Vec<IndexedDefinition>,
pub lexical_documents: Vec<IndexedLexicalDocument>,
/// Row-major signed-byte unit vectors, one row per chunk.
pub vectors: Vec<i8>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IndexedLexicalDocument {
pub length: u32,
pub terms: Vec<IndexedTermFrequency>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IndexedTermFrequency {
pub term: String,
pub frequency: u32,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IndexedDefinition {
pub symbol: String,
pub chunk: usize,
pub implementation: bool,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
pub struct IndexSnapshot {
pub format_version: u32,
pub source_identity: String,
pub model_id: String,
pub dimensions: usize,
pub desired_chunk_bytes: usize,
pub content: Vec<ContentType>,
pub files: Vec<IndexedFile>,
}
impl IndexSnapshot {
pub fn validate(&self) -> Result<()> {
if self.format_version != INDEX_FORMAT_VERSION {
return Err(Error::CorruptIndex("format version mismatch".into()));
}
for file in &self.files {
if file
.definitions
.iter()
.any(|definition| definition.chunk >= file.chunks.len())
{
return Err(Error::CorruptIndex(format!(
"definition chunk is out of bounds in {}",
file.path
)));
}
if file.vectors.len() != file.chunks.len() * self.dimensions {
return Err(Error::CorruptIndex(format!(
"chunk/vector count mismatch in {}",
file.path
)));
}
if file.lexical_documents.len() != file.chunks.len() {
return Err(Error::CorruptIndex(format!(
"chunk/lexical document count mismatch in {}",
file.path
)));
}
for document in &file.lexical_documents {
let mut previous = None;
let mut length = 0_u64;
for term in &document.terms {
if term.term.is_empty()
|| term.frequency == 0
|| previous.is_some_and(|value| value >= term.term.as_str())
{
return Err(Error::CorruptIndex(format!(
"invalid lexical document in {}",
file.path
)));
}
previous = Some(term.term.as_str());
length += u64::from(term.frequency);
}
if length != u64::from(document.length) {
return Err(Error::CorruptIndex(format!(
"lexical document length mismatch in {}",
file.path
)));
}
}
}
Ok(())
}
}
#[derive(Deserialize, Serialize)]
pub struct LoadedFile {
pub path: String,
pub stamp: FileStamp,
pub content_type: ContentType,
}
#[derive(Deserialize, Serialize)]
pub struct LoadedMetadata {
pub source_identity: String,
pub model_id: String,
pub dimensions: usize,
pub desired_chunk_bytes: usize,
pub content: Vec<ContentType>,
pub files: Vec<LoadedFile>,
}
#[derive(Deserialize, Serialize)]
pub struct LoadedIndex {
pub metadata: LoadedMetadata,
pub chunks: Vec<Chunk>,
pub vectors: Vec<i8>,
pub lexical: super::SymbolIndex,
pub bm25: super::Bm25Index,
}
impl LoadedIndex {
pub fn from_snapshot(mut snapshot: IndexSnapshot) -> Result<Self> {
snapshot.validate()?;
let lexical = super::SymbolIndex::from_files(&mut snapshot.files);
let bm25 = super::Bm25Index::from_files(&mut snapshot.files);
let metadata = LoadedMetadata {
source_identity: std::mem::take(&mut snapshot.source_identity),
model_id: std::mem::take(&mut snapshot.model_id),
dimensions: snapshot.dimensions,
desired_chunk_bytes: snapshot.desired_chunk_bytes,
content: std::mem::take(&mut snapshot.content),
files: snapshot
.files
.iter_mut()
.map(|file| LoadedFile {
path: std::mem::take(&mut file.path),
stamp: file.stamp,
content_type: file.content_type,
})
.collect(),
};
let chunks = snapshot
.files
.iter_mut()
.flat_map(|file| std::mem::take(&mut file.chunks))
.collect::<Vec<_>>();
let vectors = snapshot
.files
.iter_mut()
.flat_map(|file| std::mem::take(&mut file.vectors))
.collect::<Vec<_>>();
Ok(Self {
metadata,
chunks,
vectors,
lexical,
bm25,
})
}
pub fn validate(&self) -> Result<()> {
if self.metadata.dimensions == 0
|| self.vectors.len() != self.chunks.len() * self.metadata.dimensions
|| !self.lexical.validate(self.chunks.len())
|| !self.bm25.validate(self.chunks.len())
{
return Err(Error::CorruptIndex("invalid runtime index".into()));
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use crate::source::FileStamp;
use super::*;
#[test]
fn validation_rejects_vector_shape_mismatches() {
let snapshot = IndexSnapshot {
format_version: INDEX_FORMAT_VERSION,
source_identity: "source".into(),
model_id: "model".into(),
dimensions: 2,
desired_chunk_bytes: 100,
content: vec![ContentType::Code],
files: vec![IndexedFile {
path: "lib.rs".into(),
stamp: FileStamp {
modified_ns: 1,
size: 1,
},
content_type: ContentType::Code,
chunks: vec![Chunk {
file_path: "lib.rs".into(),
start_line: 1,
end_line: 1,
language: Some("rust".into()),
content: "x".into(),
}],
definitions: Vec::new(),
lexical_documents: vec![super::super::lexical_document("x")],
vectors: vec![1],
}],
};
assert!(matches!(snapshot.validate(), Err(Error::CorruptIndex(_))));
}
}