1use std::path::{Path, PathBuf};
8use std::time::Instant;
9
10use crate::backend::EmbedBackend;
11use crate::cache::diff;
12use crate::cache::file_cache::FileCache;
13use crate::cache::manifest::Manifest;
14use crate::cache::store::ObjectStore;
15use crate::chunk::CodeChunk;
16use crate::embed::SearchConfig;
17use crate::hybrid::HybridIndex;
18use crate::profile::Profiler;
19
20#[derive(Debug)]
22pub struct ReindexStats {
23 pub chunks_total: usize,
25 pub chunks_reembedded: usize,
27 pub files_unchanged: usize,
29 pub files_changed: usize,
31 pub files_deleted: usize,
33 pub duration_ms: u64,
35}
36
37pub fn incremental_index(
48 root: &Path,
49 backends: &[&dyn EmbedBackend],
50 tokenizer: &tokenizers::Tokenizer,
51 cfg: &SearchConfig,
52 profiler: &Profiler,
53 model_repo: &str,
54 cache_dir_override: Option<&Path>,
55 repo_level: bool,
56) -> crate::Result<(HybridIndex, ReindexStats)> {
57 let start = Instant::now();
58 tracing::info!(root = %root.display(), model = model_repo, "incremental_index starting");
59
60 if backends.is_empty() {
61 return Err(crate::Error::Other(anyhow::anyhow!(
62 "no embedding backends provided"
63 )));
64 }
65
66 if repo_level {
69 let ripvec_dir = root.join(".ripvec");
70 let config_path = ripvec_dir.join("config.toml");
71 if !config_path.exists() {
72 let config = crate::cache::config::RepoConfig::new(
73 model_repo,
74 crate::cache::manifest::MANIFEST_VERSION.to_string(),
75 );
76 config.save(&ripvec_dir)?;
77 }
78 let gitignore_path = ripvec_dir.join(".gitignore");
81 if !gitignore_path.exists() {
82 let _ = std::fs::write(&gitignore_path, "cache/manifest.json\n");
83 }
84 }
85
86 let cache_dir = resolve_cache_dir(root, model_repo, cache_dir_override);
87 let portable = is_repo_local(&cache_dir);
88 let manifest_path = cache_dir.join("manifest.json");
89 let objects_dir = cache_dir.join("objects");
90 let store = ObjectStore::new(&objects_dir);
91
92 let existing_manifest = Manifest::load(&manifest_path)
94 .ok()
95 .or_else(|| rebuild_manifest_from_objects(&cache_dir, root, model_repo));
96
97 if let Some(manifest) = existing_manifest.filter(|m| m.is_compatible(model_repo)) {
98 tracing::info!(
99 files = manifest.files.len(),
100 "manifest loaded, running incremental diff"
101 );
102 incremental_path(
104 root, backends, tokenizer, cfg, profiler, model_repo, &cache_dir, &store, manifest,
105 start, portable,
106 )
107 } else {
108 full_index_path(
110 root, backends, tokenizer, cfg, profiler, model_repo, &cache_dir, &store, start,
111 portable,
112 )
113 }
114}
115
116#[expect(clippy::too_many_arguments, reason = "pipeline state passed through")]
118#[expect(
119 clippy::cast_possible_truncation,
120 reason = "duration in ms won't exceed u64"
121)]
122fn incremental_path(
123 root: &Path,
124 backends: &[&dyn EmbedBackend],
125 tokenizer: &tokenizers::Tokenizer,
126 cfg: &SearchConfig,
127 profiler: &Profiler,
128 _model_repo: &str,
129 cache_dir: &Path,
130 store: &ObjectStore,
131 mut manifest: Manifest,
132 start: Instant,
133 portable: bool,
134) -> crate::Result<(HybridIndex, ReindexStats)> {
135 let diff_result = diff::compute_diff(root, &manifest)?;
136
137 let files_changed = diff_result.dirty.len();
138 let files_deleted = diff_result.deleted.len();
139 let files_unchanged = diff_result.unchanged;
140
141 tracing::info!(
142 changed = files_changed,
143 deleted = files_deleted,
144 unchanged = files_unchanged,
145 "diff complete"
146 );
147
148 for deleted in &diff_result.deleted {
150 manifest.remove_file(deleted);
151 }
152
153 let mut new_chunks_count = 0;
155 for dirty_path in &diff_result.dirty {
156 let relative = dirty_path
157 .strip_prefix(root)
158 .unwrap_or(dirty_path)
159 .to_string_lossy()
160 .to_string();
161
162 manifest.remove_file(&relative);
164
165 let Some(source) = crate::embed::read_source(dirty_path) else {
167 continue;
168 };
169
170 let ext = dirty_path
171 .extension()
172 .and_then(|e| e.to_str())
173 .unwrap_or("");
174 let chunks = if cfg.text_mode {
175 crate::chunk::chunk_text(dirty_path, &source, &cfg.chunk)
176 } else {
177 match crate::languages::config_for_extension(ext) {
178 Some(lang_config) => {
179 crate::chunk::chunk_file(dirty_path, &source, &lang_config, &cfg.chunk)
180 }
181 None => crate::chunk::chunk_text(dirty_path, &source, &cfg.chunk),
182 }
183 };
184
185 if chunks.is_empty() {
186 continue;
187 }
188
189 let model_max = backends[0].max_tokens();
191 let encodings: Vec<Option<crate::backend::Encoding>> = chunks
192 .iter()
193 .map(|chunk| {
194 crate::tokenize::tokenize_query(&chunk.enriched_content, tokenizer, model_max).ok()
195 })
196 .collect();
197
198 let embeddings =
200 crate::embed::embed_distributed(&encodings, backends, cfg.batch_size, profiler)?;
201
202 let (good_chunks, good_embeddings): (Vec<_>, Vec<_>) = chunks
204 .into_iter()
205 .zip(embeddings.into_iter())
206 .filter(|(_, emb)| !emb.is_empty())
207 .unzip();
208
209 let hidden_dim = good_embeddings.first().map_or(384, Vec::len);
210
211 let content_hash = diff::hash_file(dirty_path)?;
213 let file_cache = FileCache {
214 chunks: good_chunks.clone(),
215 embeddings: good_embeddings.iter().flatten().copied().collect(),
216 hidden_dim,
217 };
218 let bytes = if portable {
219 file_cache.to_portable_bytes()
220 } else {
221 file_cache.to_bytes()
222 };
223 store.write(&content_hash, &bytes)?;
224
225 let mtime = diff::mtime_secs(dirty_path);
227 let size = std::fs::metadata(dirty_path).map_or(0, |m| m.len());
228 manifest.add_file(&relative, mtime, size, &content_hash, good_chunks.len());
229 new_chunks_count += good_chunks.len();
230 }
231
232 heal_manifest_mtimes(root, &mut manifest);
236
237 manifest.recompute_hashes();
239
240 let referenced = manifest.referenced_hashes();
242 store.gc(&referenced)?;
243
244 manifest.save(&cache_dir.join("manifest.json"))?;
246
247 tracing::info!("loading cached objects from store");
249 let (all_chunks, all_embeddings) = load_all_from_store(store, &manifest)?;
250 let chunks_total = all_chunks.len();
251 tracing::info!(
252 chunks = chunks_total,
253 "building HybridIndex (BM25 + PolarQuant)"
254 );
255 let hybrid = HybridIndex::new(all_chunks, &all_embeddings, None)?;
256 tracing::info!("HybridIndex ready");
257
258 Ok((
259 hybrid,
260 ReindexStats {
261 chunks_total,
262 chunks_reembedded: new_chunks_count,
263 files_unchanged,
264 files_changed,
265 files_deleted,
266 duration_ms: start.elapsed().as_millis() as u64,
267 },
268 ))
269}
270
271#[expect(clippy::too_many_arguments, reason = "pipeline state passed through")]
273#[expect(
274 clippy::cast_possible_truncation,
275 reason = "duration in ms won't exceed u64"
276)]
277fn full_index_path(
278 root: &Path,
279 backends: &[&dyn EmbedBackend],
280 tokenizer: &tokenizers::Tokenizer,
281 cfg: &SearchConfig,
282 profiler: &Profiler,
283 model_repo: &str,
284 cache_dir: &Path,
285 store: &ObjectStore,
286 start: Instant,
287 portable: bool,
288) -> crate::Result<(HybridIndex, ReindexStats)> {
289 let (chunks, embeddings) = crate::embed::embed_all(root, backends, tokenizer, cfg, profiler)?;
290
291 let hidden_dim = embeddings.first().map_or(384, Vec::len);
292
293 let mut manifest = Manifest::new(model_repo);
295 let mut file_groups: std::collections::BTreeMap<String, (Vec<CodeChunk>, Vec<Vec<f32>>)> =
296 std::collections::BTreeMap::new();
297
298 for (chunk, emb) in chunks.iter().zip(embeddings.iter()) {
299 file_groups
300 .entry(chunk.file_path.clone())
301 .or_default()
302 .0
303 .push(chunk.clone());
304 file_groups
305 .entry(chunk.file_path.clone())
306 .or_default()
307 .1
308 .push(emb.clone());
309 }
310
311 for (file_path, (file_chunks, file_embeddings)) in &file_groups {
312 let file_path_buf = PathBuf::from(file_path);
314
315 let content_hash = diff::hash_file(&file_path_buf).unwrap_or_else(|_| {
316 blake3::hash(file_chunks[0].content.as_bytes())
318 .to_hex()
319 .to_string()
320 });
321
322 let flat_emb: Vec<f32> = file_embeddings.iter().flatten().copied().collect();
323 let fc = FileCache {
324 chunks: file_chunks.clone(),
325 embeddings: flat_emb,
326 hidden_dim,
327 };
328 let bytes = if portable {
329 fc.to_portable_bytes()
330 } else {
331 fc.to_bytes()
332 };
333 store.write(&content_hash, &bytes)?;
334
335 let relative = file_path_buf
336 .strip_prefix(root)
337 .unwrap_or(&file_path_buf)
338 .to_string_lossy()
339 .to_string();
340 let mtime = diff::mtime_secs(&file_path_buf);
341 let size = std::fs::metadata(&file_path_buf).map_or(0, |m| m.len());
342 manifest.add_file(&relative, mtime, size, &content_hash, file_chunks.len());
343 }
344
345 manifest.recompute_hashes();
346 manifest.save(&cache_dir.join("manifest.json"))?;
347
348 let chunks_total = chunks.len();
349 let files_changed = file_groups.len();
350 let hybrid = HybridIndex::new(chunks, &embeddings, None)?;
351
352 Ok((
353 hybrid,
354 ReindexStats {
355 chunks_total,
356 chunks_reembedded: chunks_total,
357 files_unchanged: 0,
358 files_changed,
359 files_deleted: 0,
360 duration_ms: start.elapsed().as_millis() as u64,
361 },
362 ))
363}
364
365#[must_use]
367pub fn is_repo_local(cache_dir: &Path) -> bool {
368 cache_dir.components().any(|c| c.as_os_str() == ".ripvec")
369}
370
371pub fn heal_manifest_mtimes(root: &Path, manifest: &mut Manifest) {
377 for (relative, entry) in &mut manifest.files {
378 let file_path = root.join(relative);
379 let mtime = diff::mtime_secs(&file_path);
380 if mtime != entry.mtime_secs {
381 entry.mtime_secs = mtime;
382 }
383 }
384}
385
386#[must_use]
392pub fn check_auto_stash(root: &Path) -> Option<String> {
393 use std::process::Command;
394
395 let ripvec_dir = root.join(".ripvec");
396 let config = crate::cache::config::RepoConfig::load(&ripvec_dir).ok()?;
397 if !config.cache.local {
398 return None;
399 }
400
401 if config.cache.auto_stash.is_some() {
403 return None;
404 }
405
406 let git_check = Command::new("git")
408 .args(["config", "--local", "pull.autoStash"])
409 .current_dir(root)
410 .stdout(std::process::Stdio::piped())
411 .stderr(std::process::Stdio::null())
412 .output()
413 .ok()?;
414 if git_check.status.success() {
415 let val = String::from_utf8_lossy(&git_check.stdout)
417 .trim()
418 .eq_ignore_ascii_case("true");
419 let _ = apply_auto_stash(root, val);
420 return None;
421 }
422
423 Some(
424 "ripvec: Repo-local cache can dirty the worktree and block `git pull`.\n\
425 Enable `pull.autoStash` for this repo? (git stashes dirty files before pull, pops after)"
426 .to_string(),
427 )
428}
429
430pub fn apply_auto_stash(root: &Path, enable: bool) -> crate::Result<()> {
439 use std::process::Command;
440
441 let ripvec_dir = root.join(".ripvec");
442 let mut config = crate::cache::config::RepoConfig::load(&ripvec_dir)?;
443 config.cache.auto_stash = Some(enable);
444 config.save(&ripvec_dir)?;
445
446 if enable {
447 let _ = Command::new("git")
448 .args(["config", "--local", "pull.autoStash", "true"])
449 .current_dir(root)
450 .stdout(std::process::Stdio::null())
451 .stderr(std::process::Stdio::null())
452 .status();
453 }
454
455 Ok(())
456}
457
458fn load_file_cache(bytes: &[u8]) -> crate::Result<FileCache> {
461 if bytes.len() >= 2 && bytes[..2] == [0x42, 0x43] {
462 FileCache::from_portable_bytes(bytes)
463 } else {
464 FileCache::from_bytes(bytes)
465 }
466}
467
468fn load_all_from_store(
470 store: &ObjectStore,
471 manifest: &Manifest,
472) -> crate::Result<(Vec<CodeChunk>, Vec<Vec<f32>>)> {
473 let mut all_chunks = Vec::new();
474 let mut all_embeddings = Vec::new();
475
476 for entry in manifest.files.values() {
477 let bytes = store.read(&entry.content_hash)?;
478 let fc = load_file_cache(&bytes)?;
479 let dim = fc.hidden_dim;
480
481 for (i, chunk) in fc.chunks.into_iter().enumerate() {
482 let start = i * dim;
483 let end = start + dim;
484 if end <= fc.embeddings.len() {
485 all_embeddings.push(fc.embeddings[start..end].to_vec());
486 all_chunks.push(chunk);
487 }
488 }
489 }
490
491 Ok((all_chunks, all_embeddings))
492}
493
494#[must_use]
503pub fn load_cached_index(root: &Path, model_repo: &str) -> Option<HybridIndex> {
504 let cache_dir = resolve_cache_dir(root, model_repo, None);
505 let manifest_path = cache_dir.join("manifest.json");
506 let objects_dir = cache_dir.join("objects");
507 let lock_path = cache_dir.join("manifest.lock");
508
509 if !manifest_path.exists() {
511 return None;
512 }
513
514 let lock_file = std::fs::OpenOptions::new()
516 .create(true)
517 .truncate(false)
518 .write(true)
519 .read(true)
520 .open(&lock_path)
521 .ok()?;
522 let lock = fd_lock::RwLock::new(lock_file);
523 let _guard = lock.read().ok()?;
524
525 let manifest = Manifest::load(&manifest_path)
526 .ok()
527 .or_else(|| rebuild_manifest_from_objects(&cache_dir, root, model_repo))?;
528 if !manifest.is_compatible(model_repo) {
529 return None;
530 }
531
532 let store = ObjectStore::new(&objects_dir);
533 let (chunks, embeddings) = load_all_from_store(&store, &manifest).ok()?;
534 HybridIndex::new(chunks, &embeddings, None).ok()
535}
536
537#[must_use]
550pub fn resolve_cache_dir(root: &Path, model_repo: &str, override_dir: Option<&Path>) -> PathBuf {
551 if let Some(dir) = override_dir {
553 let project_hash = hash_project_root(root);
554 let version_dir = format_version_dir(model_repo);
555 return dir.join(&project_hash).join(version_dir);
556 }
557
558 if let Some(ripvec_dir) = crate::cache::config::find_repo_config(root)
560 && let Ok(config) = crate::cache::config::RepoConfig::load(&ripvec_dir)
561 {
562 if config.cache.model == model_repo {
563 return ripvec_dir.join("cache");
564 }
565 eprintln!(
566 "[ripvec] repo-local index model mismatch: config has '{}', runtime wants '{}' — falling back to user cache",
567 config.cache.model, model_repo
568 );
569 }
570
571 let project_hash = hash_project_root(root);
573 let version_dir = format_version_dir(model_repo);
574
575 let base = if let Ok(env_dir) = std::env::var("RIPVEC_CACHE") {
576 PathBuf::from(env_dir).join(&project_hash)
577 } else {
578 dirs::cache_dir()
579 .unwrap_or_else(|| PathBuf::from("/tmp"))
580 .join("ripvec")
581 .join(&project_hash)
582 };
583
584 base.join(version_dir)
585}
586
587fn hash_project_root(root: &Path) -> String {
589 let canonical = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
590 blake3::hash(canonical.to_string_lossy().as_bytes())
591 .to_hex()
592 .to_string()
593}
594
595fn format_version_dir(model_repo: &str) -> String {
597 let model_slug = model_repo
598 .rsplit('/')
599 .next()
600 .unwrap_or(model_repo)
601 .to_lowercase();
602 format!("v{}-{model_slug}", crate::cache::manifest::MANIFEST_VERSION)
603}
604
605#[cfg(test)]
606mod tests {
607 use super::*;
608 use tempfile::TempDir;
609
610 #[test]
611 fn heal_stale_mtimes() {
612 use crate::cache::diff;
613 use crate::cache::manifest::Manifest;
614 use std::io::Write;
615
616 let dir = TempDir::new().unwrap();
617 let file_path = dir.path().join("test.rs");
618 let content = "fn main() {}";
619 {
620 let mut f = std::fs::File::create(&file_path).unwrap();
621 f.write_all(content.as_bytes()).unwrap();
622 }
623
624 let content_hash = blake3::hash(content.as_bytes()).to_hex().to_string();
626 let mut manifest = Manifest::new("test-model");
627 manifest.add_file(
628 "test.rs",
629 9_999_999, content.len() as u64,
631 &content_hash,
632 1,
633 );
634
635 heal_manifest_mtimes(dir.path(), &mut manifest);
637 let actual_mtime = diff::mtime_secs(&file_path);
638 assert_eq!(manifest.files["test.rs"].mtime_secs, actual_mtime);
639 }
640
641 #[test]
642 fn resolve_uses_repo_local_when_present() {
643 let dir = TempDir::new().unwrap();
644 let cfg = crate::cache::config::RepoConfig::new("nomic-ai/modernbert-embed-base", "3");
645 cfg.save(&dir.path().join(".ripvec")).unwrap();
646
647 let result = resolve_cache_dir(dir.path(), "nomic-ai/modernbert-embed-base", None);
648 assert!(
649 result.starts_with(dir.path().join(".ripvec").join("cache")),
650 "expected repo-local cache dir, got: {result:?}"
651 );
652 }
653
654 #[test]
655 fn resolve_falls_back_to_user_cache_when_no_config() {
656 let dir = TempDir::new().unwrap();
657 let result = resolve_cache_dir(dir.path(), "nomic-ai/modernbert-embed-base", None);
658 assert!(
659 !result.to_string_lossy().contains(".ripvec"),
660 "should not use repo-local without config, got: {result:?}"
661 );
662 }
663
664 #[test]
665 fn resolve_override_takes_priority_over_repo_local() {
666 let dir = TempDir::new().unwrap();
667 let override_dir = TempDir::new().unwrap();
668
669 let cfg = crate::cache::config::RepoConfig::new("nomic-ai/modernbert-embed-base", "3");
670 cfg.save(&dir.path().join(".ripvec")).unwrap();
671
672 let result = resolve_cache_dir(
673 dir.path(),
674 "nomic-ai/modernbert-embed-base",
675 Some(override_dir.path()),
676 );
677 assert!(
678 !result.starts_with(dir.path().join(".ripvec")),
679 "override should win over repo-local, got: {result:?}"
680 );
681 }
682}
683
684#[must_use]
692pub fn rebuild_manifest_from_objects(
693 cache_dir: &std::path::Path,
694 root: &std::path::Path,
695 model_repo: &str,
696) -> Option<super::manifest::Manifest> {
697 use super::file_cache::FileCache;
698 use super::manifest::{FileEntry, MANIFEST_VERSION, Manifest};
699 use super::store::ObjectStore;
700 use std::collections::BTreeMap;
701
702 let store = ObjectStore::new(&cache_dir.join("objects"));
703 let hashes = store.list_hashes();
704 if hashes.is_empty() {
705 return None;
706 }
707
708 tracing::info!(
709 objects = hashes.len(),
710 "rebuilding manifest from object store"
711 );
712
713 let mut files = BTreeMap::new();
714
715 for hash in &hashes {
716 let Ok(bytes) = store.read(hash) else {
717 continue;
718 };
719 let Ok(fc) =
720 FileCache::from_portable_bytes(&bytes).or_else(|_| FileCache::from_bytes(&bytes))
721 else {
722 continue;
723 };
724 let Some(first_chunk) = fc.chunks.first() else {
725 continue;
726 };
727
728 let chunk_path = std::path::Path::new(&first_chunk.file_path);
731 let rel_path = chunk_path
732 .strip_prefix(root)
733 .unwrap_or(chunk_path)
734 .to_string_lossy()
735 .to_string();
736
737 let abs_path = root.join(&rel_path);
739 let (mtime_secs, size) = if let Ok(meta) = std::fs::metadata(&abs_path) {
740 let mtime = meta
741 .modified()
742 .ok()
743 .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
744 .map_or(0, |d| d.as_secs());
745 (mtime, meta.len())
746 } else {
747 (0, 0) };
749
750 files.insert(
751 rel_path,
752 FileEntry {
753 mtime_secs,
754 size,
755 content_hash: hash.clone(),
756 chunk_count: fc.chunks.len(),
757 },
758 );
759 }
760
761 if files.is_empty() {
762 return None;
763 }
764
765 let manifest = Manifest {
766 version: MANIFEST_VERSION,
767 model_repo: model_repo.to_string(),
768 root_hash: String::new(), directories: BTreeMap::new(), files,
771 };
772
773 tracing::info!(
774 files = manifest.files.len(),
775 "manifest rebuilt from objects"
776 );
777
778 let manifest_path = cache_dir.join("manifest.json");
780 if let Ok(json) = serde_json::to_string_pretty(&manifest) {
781 let _ = std::fs::write(&manifest_path, json);
782 }
783
784 Some(manifest)
785}